blob: 2806bff452219267101d490dbf5c1c77125ef435 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.media;
18
Andreas Huberd5f9fa52013-05-28 14:39:39 -070019import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.ContentResolver;
21import android.content.Context;
Andreas Huberd5f9fa52013-05-28 14:39:39 -070022import android.content.Intent;
23import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.content.res.AssetFileDescriptor;
25import android.net.Uri;
26import android.os.Handler;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070027import android.os.HandlerThread;
Andreas Huberd2506a52014-01-29 10:32:46 -080028import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.os.Looper;
30import android.os.Message;
Nicolas Catania20cb94e2009-05-12 23:25:55 -070031import android.os.Parcel;
Insun Kang41f3f712012-02-16 20:28:27 +090032import android.os.Parcelable;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070033import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.PowerManager;
35import android.util.Log;
36import android.view.Surface;
37import android.view.SurfaceHolder;
Glenn Kastencc562a32011-02-08 17:26:17 -080038import android.graphics.SurfaceTexture;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.media.AudioManager;
Lajos Molnar1c56a672013-08-15 12:05:52 -070040import android.media.MediaFormat;
Lajos Molnar3d998562013-08-15 17:05:05 -070041import android.media.MediaTimeProvider;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070042import android.media.SubtitleController;
Chong Zhang83ddaf62013-08-06 09:43:22 -070043import android.media.SubtitleData;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
James Donge00b6f32012-04-11 21:18:43 -070045import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import java.io.FileDescriptor;
James Donge00b6f32012-04-11 21:18:43 -070047import java.io.FileInputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import java.io.IOException;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070049import java.io.InputStream;
50import java.lang.Runnable;
John Grossman720aa282012-02-22 15:38:35 -080051import java.net.InetSocketAddress;
Andreas Huber25643002010-01-28 11:19:57 -080052import java.util.Map;
Lajos Molnar484ff7a92013-08-15 11:37:47 -070053import java.util.Scanner;
Nicolas Catania9193e082009-07-06 12:43:36 -070054import java.util.Set;
Lajos Molnar3d998562013-08-15 17:05:05 -070055import java.util.Vector;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.lang.ref.WeakReference;
57
58/**
59 * MediaPlayer class can be used to control playback
60 * of audio/video files and streams. An example on how to use the methods in
61 * this class can be found in {@link android.widget.VideoView}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062 *
63 * <p>Topics covered here are:
64 * <ol>
65 * <li><a href="#StateDiagram">State Diagram</a>
66 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
67 * <li><a href="#Permissions">Permissions</a>
James Dong9ddb7882011-06-14 14:01:57 -070068 * <li><a href="#Callbacks">Register informational and error callbacks</a>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 * </ol>
70 *
Joe Fernandez61fd1e82011-10-26 13:39:11 -070071 * <div class="special reference">
72 * <h3>Developer Guides</h3>
73 * <p>For more information about how to use MediaPlayer, read the
74 * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p>
75 * </div>
76 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077 * <a name="StateDiagram"></a>
78 * <h3>State Diagram</h3>
79 *
80 * <p>Playback control of audio/video files and streams is managed as a state
81 * machine. The following diagram shows the life cycle and the states of a
82 * MediaPlayer object driven by the supported playback control operations.
83 * The ovals represent the states a MediaPlayer object may reside
84 * in. The arcs represent the playback control operations that drive the object
Nicolas Catania32f82772009-06-11 16:33:49 -070085 * state transition. There are two types of arcs. The arcs with a single arrow
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086 * head represent synchronous method calls, while those with
87 * a double arrow head represent asynchronous method calls.</p>
88 *
89 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
90 * alt="MediaPlayer State diagram"
91 * border="0" /></p>
92 *
93 * <p>From this state diagram, one can see that a MediaPlayer object has the
94 * following states:</p>
95 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -070096 * <li>When a MediaPlayer object is just created using <code>new</code> or
97 * after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
98 * {@link #release()} is called, it is in the <em>End</em> state. Between these
99 * two states is the life cycle of the MediaPlayer object.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700101 * <li>There is a subtle but important difference between a newly constructed
102 * MediaPlayer object and the MediaPlayer object after {@link #reset()}
103 * is called. It is a programming error to invoke methods such
104 * as {@link #getCurrentPosition()},
105 * {@link #getDuration()}, {@link #getVideoHeight()},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 * {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
107 * {@link #setLooping(boolean)},
Nicolas Catania32f82772009-06-11 16:33:49 -0700108 * {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
109 * {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
110 * {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
111 * methods is called right after a MediaPlayer object is constructed,
112 * the user supplied callback method OnErrorListener.onError() won't be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 * called by the internal player engine and the object state remains
Nicolas Catania32f82772009-06-11 16:33:49 -0700114 * unchanged; but if these methods are called right after {@link #reset()},
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 * the user supplied callback method OnErrorListener.onError() will be
Nicolas Catania32f82772009-06-11 16:33:49 -0700116 * invoked by the internal player engine and the object will be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 * transfered to the <em>Error</em> state. </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700118 * <li>It is also recommended that once
119 * a MediaPlayer object is no longer being used, call {@link #release()} immediately
120 * so that resources used by the internal player engine associated with the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 * MediaPlayer object can be released immediately. Resource may include
Nicolas Catania32f82772009-06-11 16:33:49 -0700122 * singleton resources such as hardware acceleration components and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 * failure to call {@link #release()} may cause subsequent instances of
124 * MediaPlayer objects to fallback to software implementations or fail
125 * altogether. Once the MediaPlayer
Nicolas Catania32f82772009-06-11 16:33:49 -0700126 * object is in the <em>End</em> state, it can no longer be used and
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127 * there is no way to bring it back to any other state. </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700128 * <li>Furthermore,
129 * the MediaPlayer objects created using <code>new</code> is in the
130 * <em>Idle</em> state, while those created with one
131 * of the overloaded convenient <code>create</code> methods are <em>NOT</em>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 * in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
133 * state if the creation using <code>create</code> method is successful.
134 * </li>
135 * </ul>
136 * </li>
137 * <li>In general, some playback control operation may fail due to various
138 * reasons, such as unsupported audio/video format, poorly interleaved
139 * audio/video, resolution too high, streaming timeout, and the like.
140 * Thus, error reporting and recovery is an important concern under
Nicolas Catania32f82772009-06-11 16:33:49 -0700141 * these circumstances. Sometimes, due to programming errors, invoking a playback
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142 * control operation in an invalid state may also occur. Under all these
143 * error conditions, the internal player engine invokes a user supplied
144 * OnErrorListener.onError() method if an OnErrorListener has been
145 * registered beforehand via
146 * {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
147 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700148 * <li>It is important to note that once an error occurs, the
149 * MediaPlayer object enters the <em>Error</em> state (except as noted
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150 * above), even if an error listener has not been registered by the application.</li>
151 * <li>In order to reuse a MediaPlayer object that is in the <em>
Nicolas Catania32f82772009-06-11 16:33:49 -0700152 * Error</em> state and recover from the error,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 * {@link #reset()} can be called to restore the object to its <em>Idle</em>
154 * state.</li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700155 * <li>It is good programming practice to have your application
156 * register a OnErrorListener to look out for error notifications from
157 * the internal player engine.</li>
hugh kennedyc6f8ea42010-04-28 15:04:10 -0400158 * <li>IllegalStateException is
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 * thrown to prevent programming errors such as calling {@link #prepare()},
160 * {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
161 * </code> methods in an invalid state. </li>
162 * </ul>
163 * </li>
164 * <li>Calling
165 * {@link #setDataSource(FileDescriptor)}, or
166 * {@link #setDataSource(String)}, or
167 * {@link #setDataSource(Context, Uri)}, or
Nicolas Catania32f82772009-06-11 16:33:49 -0700168 * {@link #setDataSource(FileDescriptor, long, long)} transfers a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 * MediaPlayer object in the <em>Idle</em> state to the
170 * <em>Initialized</em> state.
171 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700172 * <li>An IllegalStateException is thrown if
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 * setDataSource() is called in any other state.</li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700174 * <li>It is good programming
175 * practice to always look out for <code>IllegalArgumentException</code>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 * and <code>IOException</code> that may be thrown from the overloaded
177 * <code>setDataSource</code> methods.</li>
178 * </ul>
179 * </li>
180 * <li>A MediaPlayer object must first enter the <em>Prepared</em> state
Nicolas Catania32f82772009-06-11 16:33:49 -0700181 * before playback can be started.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182 * <ul>
183 * <li>There are two ways (synchronous vs.
184 * asynchronous) that the <em>Prepared</em> state can be reached:
185 * either a call to {@link #prepare()} (synchronous) which
186 * transfers the object to the <em>Prepared</em> state once the method call
187 * returns, or a call to {@link #prepareAsync()} (asynchronous) which
Nicolas Catania32f82772009-06-11 16:33:49 -0700188 * first transfers the object to the <em>Preparing</em> state after the
189 * call returns (which occurs almost right way) while the internal
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190 * player engine continues working on the rest of preparation work
191 * until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
192 * the internal player engine then calls a user supplied callback method,
193 * onPrepared() of the OnPreparedListener interface, if an
194 * OnPreparedListener is registered beforehand via {@link
195 * #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
196 * <li>It is important to note that
197 * the <em>Preparing</em> state is a transient state, and the behavior
198 * of calling any method with side effect while a MediaPlayer object is
199 * in the <em>Preparing</em> state is undefined.</li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700200 * <li>An IllegalStateException is
201 * thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
202 * any other state.</li>
203 * <li>While in the <em>Prepared</em> state, properties
204 * such as audio/sound volume, screenOnWhilePlaying, looping can be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205 * adjusted by invoking the corresponding set methods.</li>
206 * </ul>
207 * </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700208 * <li>To start the playback, {@link #start()} must be called. After
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 * {@link #start()} returns successfully, the MediaPlayer object is in the
Nicolas Catania32f82772009-06-11 16:33:49 -0700210 * <em>Started</em> state. {@link #isPlaying()} can be called to test
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 * whether the MediaPlayer object is in the <em>Started</em> state.
212 * <ul>
213 * <li>While in the <em>Started</em> state, the internal player engine calls
214 * a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
Nicolas Catania32f82772009-06-11 16:33:49 -0700215 * method if a OnBufferingUpdateListener has been registered beforehand
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216 * via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
217 * This callback allows applications to keep track of the buffering status
218 * while streaming audio/video.</li>
219 * <li>Calling {@link #start()} has not effect
220 * on a MediaPlayer object that is already in the <em>Started</em> state.</li>
221 * </ul>
222 * </li>
223 * <li>Playback can be paused and stopped, and the current playback position
Nicolas Catania32f82772009-06-11 16:33:49 -0700224 * can be adjusted. Playback can be paused via {@link #pause()}. When the call to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 * {@link #pause()} returns, the MediaPlayer object enters the
Nicolas Catania32f82772009-06-11 16:33:49 -0700226 * <em>Paused</em> state. Note that the transition from the <em>Started</em>
227 * state to the <em>Paused</em> state and vice versa happens
228 * asynchronously in the player engine. It may take some time before
229 * the state is updated in calls to {@link #isPlaying()}, and it can be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230 * a number of seconds in the case of streamed content.
231 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700232 * <li>Calling {@link #start()} to resume playback for a paused
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 * MediaPlayer object, and the resumed playback
Nicolas Catania32f82772009-06-11 16:33:49 -0700234 * position is the same as where it was paused. When the call to
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 * {@link #start()} returns, the paused MediaPlayer object goes back to
236 * the <em>Started</em> state.</li>
237 * <li>Calling {@link #pause()} has no effect on
238 * a MediaPlayer object that is already in the <em>Paused</em> state.</li>
239 * </ul>
240 * </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700241 * <li>Calling {@link #stop()} stops playback and causes a
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 * MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
Nicolas Catania32f82772009-06-11 16:33:49 -0700243 * </em> or <em>PlaybackCompleted</em> state to enter the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 * <em>Stopped</em> state.
245 * <ul>
Nicolas Catania32f82772009-06-11 16:33:49 -0700246 * <li>Once in the <em>Stopped</em> state, playback cannot be started
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 * until {@link #prepare()} or {@link #prepareAsync()} are called to set
248 * the MediaPlayer object to the <em>Prepared</em> state again.</li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700249 * <li>Calling {@link #stop()} has no effect on a MediaPlayer
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 * object that is already in the <em>Stopped</em> state.</li>
251 * </ul>
252 * </li>
Nicolas Catania32f82772009-06-11 16:33:49 -0700253 * <li>The playback position can be adjusted with a call to
254 * {@link #seekTo(int)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 * <ul>
256 * <li>Although the asynchronuous {@link #seekTo(int)}
257 * call returns right way, the actual seek operation may take a while to
Nicolas Catania32f82772009-06-11 16:33:49 -0700258 * finish, especially for audio/video being streamed. When the actual
259 * seek operation completes, the internal player engine calls a user
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800260 * supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
Nicolas Catania32f82772009-06-11 16:33:49 -0700261 * has been registered beforehand via
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800262 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
263 * <li>Please
264 * note that {@link #seekTo(int)} can also be called in the other states,
265 * such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
266 * </em> state.</li>
267 * <li>Furthermore, the actual current playback position
268 * can be retrieved with a call to {@link #getCurrentPosition()}, which
Nicolas Catania32f82772009-06-11 16:33:49 -0700269 * is helpful for applications such as a Music player that need to keep
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800270 * track of the playback progress.</li>
271 * </ul>
272 * </li>
273 * <li>When the playback reaches the end of stream, the playback completes.
274 * <ul>
275 * <li>If the looping mode was being set to <var>true</var>with
276 * {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
277 * the <em>Started</em> state.</li>
278 * <li>If the looping mode was set to <var>false
279 * </var>, the player engine calls a user supplied callback method,
280 * OnCompletion.onCompletion(), if a OnCompletionListener is registered
281 * beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
282 * The invoke of the callback signals that the object is now in the <em>
283 * PlaybackCompleted</em> state.</li>
284 * <li>While in the <em>PlaybackCompleted</em>
285 * state, calling {@link #start()} can restart the playback from the
286 * beginning of the audio/video source.</li>
287 * </ul>
288 *
289 *
290 * <a name="Valid_and_Invalid_States"></a>
291 * <h3>Valid and invalid states</h3>
292 *
293 * <table border="0" cellspacing="0" cellpadding="0">
294 * <tr><td>Method Name </p></td>
295 * <td>Valid Sates </p></td>
296 * <td>Invalid States </p></td>
297 * <td>Comments </p></td></tr>
Eric Laurent17cb2802010-08-03 03:50:02 -0700298 * <tr><td>attachAuxEffect </p></td>
299 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
300 * <td>{Idle, Error} </p></td>
301 * <td>This method must be called after setDataSource.
302 * Calling it does not change the object state. </p></td></tr>
303 * <tr><td>getAudioSessionId </p></td>
304 * <td>any </p></td>
305 * <td>{} </p></td>
306 * <td>This method can be called in any state and calling it does not change
307 * the object state. </p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800308 * <tr><td>getCurrentPosition </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700309 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 * PlaybackCompleted} </p></td>
311 * <td>{Error}</p></td>
312 * <td>Successful invoke of this method in a valid state does not change the
313 * state. Calling this method in an invalid state transfers the object
314 * to the <em>Error</em> state. </p></td></tr>
315 * <tr><td>getDuration </p></td>
316 * <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
317 * <td>{Idle, Initialized, Error} </p></td>
318 * <td>Successful invoke of this method in a valid state does not change the
Nicolas Catania32f82772009-06-11 16:33:49 -0700319 * state. Calling this method in an invalid state transfers the object
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 * to the <em>Error</em> state. </p></td></tr>
321 * <tr><td>getVideoHeight </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700322 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 * PlaybackCompleted}</p></td>
324 * <td>{Error}</p></td>
325 * <td>Successful invoke of this method in a valid state does not change the
Nicolas Catania32f82772009-06-11 16:33:49 -0700326 * state. Calling this method in an invalid state transfers the object
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 * to the <em>Error</em> state. </p></td></tr>
328 * <tr><td>getVideoWidth </p></td>
329 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
330 * PlaybackCompleted}</p></td>
331 * <td>{Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700332 * <td>Successful invoke of this method in a valid state does not change
333 * the state. Calling this method in an invalid state transfers the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 * object to the <em>Error</em> state. </p></td></tr>
335 * <tr><td>isPlaying </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700336 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800337 * PlaybackCompleted}</p></td>
338 * <td>{Error}</p></td>
339 * <td>Successful invoke of this method in a valid state does not change
Nicolas Catania32f82772009-06-11 16:33:49 -0700340 * the state. Calling this method in an invalid state transfers the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 * object to the <em>Error</em> state. </p></td></tr>
342 * <tr><td>pause </p></td>
kmccormickb04c07f2013-03-29 15:48:45 -0700343 * <td>{Started, Paused, PlaybackCompleted}</p></td>
344 * <td>{Idle, Initialized, Prepared, Stopped, Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700345 * <td>Successful invoke of this method in a valid state transfers the
346 * object to the <em>Paused</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800347 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
348 * <tr><td>prepare </p></td>
349 * <td>{Initialized, Stopped} </p></td>
350 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700351 * <td>Successful invoke of this method in a valid state transfers the
352 * object to the <em>Prepared</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 * invalid state throws an IllegalStateException.</p></td></tr>
354 * <tr><td>prepareAsync </p></td>
355 * <td>{Initialized, Stopped} </p></td>
356 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700357 * <td>Successful invoke of this method in a valid state transfers the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 * object to the <em>Preparing</em> state. Calling this method in an
359 * invalid state throws an IllegalStateException.</p></td></tr>
360 * <tr><td>release </p></td>
361 * <td>any </p></td>
362 * <td>{} </p></td>
363 * <td>After {@link #release()}, the object is no longer available. </p></td></tr>
364 * <tr><td>reset </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700365 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800366 * PlaybackCompleted, Error}</p></td>
367 * <td>{}</p></td>
368 * <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
369 * <tr><td>seekTo </p></td>
370 * <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
371 * <td>{Idle, Initialized, Stopped, Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700372 * <td>Successful invoke of this method in a valid state does not change
373 * the state. Calling this method in an invalid state transfers the
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800374 * object to the <em>Error</em> state. </p></td></tr>
Eric Laurent17cb2802010-08-03 03:50:02 -0700375 * <tr><td>setAudioSessionId </p></td>
376 * <td>{Idle} </p></td>
377 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
378 * Error} </p></td>
379 * <td>This method must be called in idle state as the audio session ID must be known before
380 * calling setDataSource. Calling it does not change the object state. </p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800381 * <tr><td>setAudioStreamType </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700382 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800383 * PlaybackCompleted}</p></td>
384 * <td>{Error}</p></td>
James Dong9d963542010-06-03 10:36:04 -0700385 * <td>Successful invoke of this method does not change the state. In order for the
386 * target audio stream type to become effective, this method must be called before
387 * prepare() or prepareAsync().</p></td></tr>
Eric Laurent17cb2802010-08-03 03:50:02 -0700388 * <tr><td>setAuxEffectSendLevel </p></td>
389 * <td>any</p></td>
390 * <td>{} </p></td>
391 * <td>Calling this method does not change the object state. </p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 * <tr><td>setDataSource </p></td>
393 * <td>{Idle} </p></td>
394 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
395 * Error} </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700396 * <td>Successful invoke of this method in a valid state transfers the
397 * object to the <em>Initialized</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800398 * invalid state throws an IllegalStateException.</p></td></tr>
399 * <tr><td>setDisplay </p></td>
400 * <td>any </p></td>
401 * <td>{} </p></td>
402 * <td>This method can be called in any state and calling it does not change
403 * the object state. </p></td></tr>
Jamie Gennisb283dc62011-08-28 16:28:08 -0700404 * <tr><td>setSurface </p></td>
Glenn Kastencc562a32011-02-08 17:26:17 -0800405 * <td>any </p></td>
406 * <td>{} </p></td>
407 * <td>This method can be called in any state and calling it does not change
408 * the object state. </p></td></tr>
James Dong454014e2012-04-28 16:03:55 -0700409 * <tr><td>setVideoScalingMode </p></td>
410 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
411 * <td>{Idle, Error}</p></td>
412 * <td>Successful invoke of this method does not change the state.</p></td></tr>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800413 * <tr><td>setLooping </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700414 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800415 * PlaybackCompleted}</p></td>
416 * <td>{Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700417 * <td>Successful invoke of this method in a valid state does not change
418 * the state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
420 * <tr><td>isLooping </p></td>
421 * <td>any </p></td>
422 * <td>{} </p></td>
423 * <td>This method can be called in any state and calling it does not change
424 * the object state. </p></td></tr>
425 * <tr><td>setOnBufferingUpdateListener </p></td>
426 * <td>any </p></td>
427 * <td>{} </p></td>
428 * <td>This method can be called in any state and calling it does not change
429 * the object state. </p></td></tr>
430 * <tr><td>setOnCompletionListener </p></td>
431 * <td>any </p></td>
432 * <td>{} </p></td>
433 * <td>This method can be called in any state and calling it does not change
434 * the object state. </p></td></tr>
435 * <tr><td>setOnErrorListener </p></td>
436 * <td>any </p></td>
437 * <td>{} </p></td>
438 * <td>This method can be called in any state and calling it does not change
439 * the object state. </p></td></tr>
440 * <tr><td>setOnPreparedListener </p></td>
441 * <td>any </p></td>
442 * <td>{} </p></td>
443 * <td>This method can be called in any state and calling it does not change
444 * the object state. </p></td></tr>
445 * <tr><td>setOnSeekCompleteListener </p></td>
446 * <td>any </p></td>
447 * <td>{} </p></td>
448 * <td>This method can be called in any state and calling it does not change
449 * the object state. </p></td></tr>
450 * <tr><td>setScreenOnWhilePlaying</></td>
451 * <td>any </p></td>
452 * <td>{} </p></td>
453 * <td>This method can be called in any state and calling it does not change
454 * the object state. </p></td></tr>
455 * <tr><td>setVolume </p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700456 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 * PlaybackCompleted}</p></td>
458 * <td>{Error}</p></td>
459 * <td>Successful invoke of this method does not change the state.
460 * <tr><td>setWakeMode </p></td>
461 * <td>any </p></td>
462 * <td>{} </p></td>
463 * <td>This method can be called in any state and calling it does not change
464 * the object state.</p></td></tr>
465 * <tr><td>start </p></td>
466 * <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
467 * <td>{Idle, Initialized, Stopped, Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700468 * <td>Successful invoke of this method in a valid state transfers the
469 * object to the <em>Started</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
471 * <tr><td>stop </p></td>
472 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
473 * <td>{Idle, Initialized, Error}</p></td>
Nicolas Catania32f82772009-06-11 16:33:49 -0700474 * <td>Successful invoke of this method in a valid state transfers the
475 * object to the <em>Stopped</em> state. Calling this method in an
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800476 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
Insun Kang41f3f712012-02-16 20:28:27 +0900477 * <tr><td>getTrackInfo </p></td>
478 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
479 * <td>{Idle, Initialized, Error}</p></td>
480 * <td>Successful invoke of this method does not change the state.</p></td></tr>
James Dong7a9734d2012-04-19 13:30:20 -0700481 * <tr><td>addTimedTextSource </p></td>
Insun Kang41f3f712012-02-16 20:28:27 +0900482 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
483 * <td>{Idle, Initialized, Error}</p></td>
484 * <td>Successful invoke of this method does not change the state.</p></td></tr>
485 * <tr><td>selectTrack </p></td>
486 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
487 * <td>{Idle, Initialized, Error}</p></td>
488 * <td>Successful invoke of this method does not change the state.</p></td></tr>
James Dong7a9734d2012-04-19 13:30:20 -0700489 * <tr><td>deselectTrack </p></td>
Insun Kang41f3f712012-02-16 20:28:27 +0900490 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
491 * <td>{Idle, Initialized, Error}</p></td>
492 * <td>Successful invoke of this method does not change the state.</p></td></tr>
Eric Laurent619346f2010-06-21 09:27:30 -0700493 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800494 * </table>
495 *
496 * <a name="Permissions"></a>
497 * <h3>Permissions</h3>
498 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
499 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
500 * element.
501 *
Dave Burkefc301b02011-08-30 14:39:17 +0100502 * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
503 * when used with network-based content.
504 *
James Dong9ddb7882011-06-14 14:01:57 -0700505 * <a name="Callbacks"></a>
506 * <h3>Callbacks</h3>
507 * <p>Applications may want to register for informational and error
508 * events in order to be informed of some internal state update and
509 * possible runtime errors during playback or streaming. Registration for
510 * these events is done by properly setting the appropriate listeners (via calls
511 * to
512 * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
513 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
514 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
515 * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
James Dongd52ad9c2011-06-14 18:20:53 -0700516 * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
James Dong9ddb7882011-06-14 14:01:57 -0700517 * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
518 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
519 * In order to receive the respective callback
520 * associated with these listeners, applications are required to create
521 * MediaPlayer objects on a thread with its own Looper running (main UI
522 * thread by default has a Looper running).
523 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800524 */
Lajos Molnar484ff7a92013-08-15 11:37:47 -0700525public class MediaPlayer implements SubtitleController.Listener
Nicolas Catania32f82772009-06-11 16:33:49 -0700526{
Nicolas Catania9193e082009-07-06 12:43:36 -0700527 /**
528 Constant to retrieve only the new metadata since the last
529 call.
530 // FIXME: unhide.
531 // FIXME: add link to getMetadata(boolean, boolean)
532 {@hide}
533 */
534 public static final boolean METADATA_UPDATE_ONLY = true;
535
536 /**
537 Constant to retrieve all the metadata.
538 // FIXME: unhide.
539 // FIXME: add link to getMetadata(boolean, boolean)
540 {@hide}
541 */
542 public static final boolean METADATA_ALL = false;
543
544 /**
545 Constant to enable the metadata filter during retrieval.
546 // FIXME: unhide.
547 // FIXME: add link to getMetadata(boolean, boolean)
548 {@hide}
549 */
550 public static final boolean APPLY_METADATA_FILTER = true;
551
552 /**
553 Constant to disable the metadata filter during retrieval.
554 // FIXME: unhide.
555 // FIXME: add link to getMetadata(boolean, boolean)
556 {@hide}
557 */
558 public static final boolean BYPASS_METADATA_FILTER = false;
559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800560 static {
561 System.loadLibrary("media_jni");
Marco Nelissen4935d052009-08-03 11:12:58 -0700562 native_init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800563 }
Nicolas Catania32f82772009-06-11 16:33:49 -0700564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800565 private final static String TAG = "MediaPlayer";
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700566 // Name of the remote interface for the media player. Must be kept
567 // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
568 // macro invocation in IMediaPlayer.cpp
569 private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
Nicolas Catania32f82772009-06-11 16:33:49 -0700570
Ashok Bhat075e9a12014-01-06 13:45:09 +0000571 private long mNativeContext; // accessed by native methods
572 private long mNativeSurfaceTexture; // accessed by native methods
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800573 private int mListenerContext; // accessed by native methods
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700574 private SurfaceHolder mSurfaceHolder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 private EventHandler mEventHandler;
576 private PowerManager.WakeLock mWakeLock = null;
577 private boolean mScreenOnWhilePlaying;
578 private boolean mStayAwake;
Nicolas Catania32f82772009-06-11 16:33:49 -0700579
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 /**
Nicolas Catania32f82772009-06-11 16:33:49 -0700581 * Default constructor. Consider using one of the create() methods for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 * synchronously instantiating a MediaPlayer from a Uri or resource.
583 * <p>When done with the MediaPlayer, you should call {@link #release()},
584 * to free the resources. If not released, too many MediaPlayer instances may
585 * result in an exception.</p>
586 */
587 public MediaPlayer() {
Nicolas Catania32f82772009-06-11 16:33:49 -0700588
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800589 Looper looper;
590 if ((looper = Looper.myLooper()) != null) {
591 mEventHandler = new EventHandler(this, looper);
592 } else if ((looper = Looper.getMainLooper()) != null) {
593 mEventHandler = new EventHandler(this, looper);
594 } else {
595 mEventHandler = null;
596 }
597
Lajos Molnar3d998562013-08-15 17:05:05 -0700598 mTimeProvider = new TimeProvider(this);
Lajos Molnar484ff7a92013-08-15 11:37:47 -0700599 mOutOfBandSubtitleTracks = new Vector<SubtitleTrack>();
600 mOpenSubtitleSources = new Vector<InputStream>();
601 mInbandSubtitleTracks = new SubtitleTrack[0];
Lajos Molnar3d998562013-08-15 17:05:05 -0700602
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 /* Native setup requires a weak reference to our object.
604 * It's easier to create it here than in C++.
605 */
606 native_setup(new WeakReference<MediaPlayer>(this));
607 }
Dave Sparks8b0b1742009-05-29 09:01:20 -0700608
609 /*
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700610 * Update the MediaPlayer SurfaceTexture.
611 * Call after setting a new display surface.
Dave Sparks8b0b1742009-05-29 09:01:20 -0700612 */
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700613 private native void _setVideoSurface(Surface surface);
Nicolas Catania32f82772009-06-11 16:33:49 -0700614
Insun Kang41f3f712012-02-16 20:28:27 +0900615 /* Do not change these values (starting with INVOKE_ID) without updating
616 * their counterparts in include/media/mediaplayer.h!
617 */
618 private static final int INVOKE_ID_GET_TRACK_INFO = 1;
619 private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE = 2;
620 private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3;
621 private static final int INVOKE_ID_SELECT_TRACK = 4;
James Dong7a9734d2012-04-19 13:30:20 -0700622 private static final int INVOKE_ID_DESELECT_TRACK = 5;
James Dong454014e2012-04-28 16:03:55 -0700623 private static final int INVOKE_ID_SET_VIDEO_SCALE_MODE = 6;
Insun Kang41f3f712012-02-16 20:28:27 +0900624
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800625 /**
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700626 * Create a request parcel which can be routed to the native media
627 * player using {@link #invoke(Parcel, Parcel)}. The Parcel
628 * returned has the proper InterfaceToken set. The caller should
629 * not overwrite that token, i.e it can only append data to the
630 * Parcel.
631 *
632 * @return A parcel suitable to hold a request for the native
633 * player.
Marco Nelissen2d2cd322013-06-14 09:42:26 -0700634 * {@hide}
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700635 */
Marco Nelissen2d2cd322013-06-14 09:42:26 -0700636 public Parcel newRequest() {
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700637 Parcel parcel = Parcel.obtain();
638 parcel.writeInterfaceToken(IMEDIA_PLAYER);
639 return parcel;
640 }
641
642 /**
643 * Invoke a generic method on the native player using opaque
644 * parcels for the request and reply. Both payloads' format is a
645 * convention between the java caller and the native player.
646 * Must be called after setDataSource to make sure a native player
James Dong7a9734d2012-04-19 13:30:20 -0700647 * exists. On failure, a RuntimeException is thrown.
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700648 *
649 * @param request Parcel with the data for the extension. The
650 * caller must use {@link #newRequest()} to get one.
651 *
Dianne Hackborn4a51c202009-08-21 15:14:02 -0700652 * @param reply Output parcel with the data returned by the
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700653 * native player.
Marco Nelissen2d2cd322013-06-14 09:42:26 -0700654 * {@hide}
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700655 */
Marco Nelissen2d2cd322013-06-14 09:42:26 -0700656 public void invoke(Parcel request, Parcel reply) {
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700657 int retcode = native_invoke(request, reply);
658 reply.setDataPosition(0);
James Dong7a9734d2012-04-19 13:30:20 -0700659 if (retcode != 0) {
660 throw new RuntimeException("failure code: " + retcode);
661 }
Nicolas Catania20cb94e2009-05-12 23:25:55 -0700662 }
663
664 /**
Glenn Kastencc562a32011-02-08 17:26:17 -0800665 * Sets the {@link SurfaceHolder} to use for displaying the video
Gloria Wang91784c992011-08-09 15:29:34 -0700666 * portion of the media.
Nicolas Catania32f82772009-06-11 16:33:49 -0700667 *
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700668 * Either a surface holder or surface must be set if a display or video sink
Jamie Gennisb283dc62011-08-28 16:28:08 -0700669 * is needed. Not calling this method or {@link #setSurface(Surface)}
Glenn Kastencc562a32011-02-08 17:26:17 -0800670 * when playing back a video will result in only the audio track being played.
Gloria Wang91784c992011-08-09 15:29:34 -0700671 * A null surface holder or surface will result in only the audio track being
672 * played.
Glenn Kasten5c2faf32011-06-27 10:10:19 -0700673 *
674 * @param sh the SurfaceHolder to use for video display
Glenn Kastencc562a32011-02-08 17:26:17 -0800675 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800676 public void setDisplay(SurfaceHolder sh) {
677 mSurfaceHolder = sh;
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700678 Surface surface;
Dave Sparks8b0b1742009-05-29 09:01:20 -0700679 if (sh != null) {
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700680 surface = sh.getSurface();
Dave Sparks8b0b1742009-05-29 09:01:20 -0700681 } else {
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700682 surface = null;
Dave Sparks8b0b1742009-05-29 09:01:20 -0700683 }
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700684 _setVideoSurface(surface);
Glenn Kastencc562a32011-02-08 17:26:17 -0800685 updateSurfaceScreenOn();
686 }
687
688 /**
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700689 * Sets the {@link Surface} to be used as the sink for the video portion of
Jamie Gennisb283dc62011-08-28 16:28:08 -0700690 * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but
691 * does not support {@link #setScreenOnWhilePlaying(boolean)}. Setting a
692 * Surface will un-set any Surface or SurfaceHolder that was previously set.
Gloria Wang91784c992011-08-09 15:29:34 -0700693 * A null surface will result in only the audio track being played.
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700694 *
Jamie Gennisb283dc62011-08-28 16:28:08 -0700695 * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
696 * returned from {@link SurfaceTexture#getTimestamp()} will have an
697 * unspecified zero point. These timestamps cannot be directly compared
698 * between different media sources, different instances of the same media
699 * source, or multiple runs of the same program. The timestamp is normally
700 * monotonically increasing and is unaffected by time-of-day adjustments,
701 * but it is reset when the position is set.
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700702 *
Jamie Gennisb283dc62011-08-28 16:28:08 -0700703 * @param surface The {@link Surface} to be used for the video portion of
704 * the media.
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700705 */
706 public void setSurface(Surface surface) {
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700707 if (mScreenOnWhilePlaying && surface != null) {
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700708 Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
709 }
710 mSurfaceHolder = null;
Ted Bonkenburg1ee60112011-07-26 09:51:18 -0700711 _setVideoSurface(surface);
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700712 updateSurfaceScreenOn();
713 }
714
James Dong454014e2012-04-28 16:03:55 -0700715 /* Do not change these video scaling mode values below without updating
716 * their counterparts in system/window.h! Please do not forget to update
717 * {@link #isVideoScalingModeSupported} when new video scaling modes
718 * are added.
719 */
720 /**
721 * Specifies a video scaling mode. The content is stretched to the
722 * surface rendering area. When the surface has the same aspect ratio
723 * as the content, the aspect ratio of the content is maintained;
724 * otherwise, the aspect ratio of the content is not maintained when video
Jeff Smitha45746e2012-07-19 14:19:24 -0500725 * is being rendered. Unlike {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING},
James Dong454014e2012-04-28 16:03:55 -0700726 * there is no content cropping with this video scaling mode.
727 */
728 public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1;
729
730 /**
731 * Specifies a video scaling mode. The content is scaled, maintaining
732 * its aspect ratio. The whole surface area is always used. When the
733 * aspect ratio of the content is the same as the surface, no content
734 * is cropped; otherwise, content is cropped to fit the surface.
735 */
736 public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2;
737 /**
738 * Sets video scaling mode. To make the target video scaling mode
739 * effective during playback, this method must be called after
740 * data source is set. If not called, the default video
741 * scaling mode is {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}.
742 *
743 * <p> The supported video scaling modes are:
744 * <ul>
745 * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}
746 * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING}
747 * </ul>
748 *
749 * @param mode target video scaling mode. Most be one of the supported
750 * video scaling modes; otherwise, IllegalArgumentException will be thrown.
751 *
752 * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT
753 * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
754 */
755 public void setVideoScalingMode(int mode) {
Bryan Mawhinney79a9cd42012-05-18 00:15:56 +0100756 if (!isVideoScalingModeSupported(mode)) {
James Dong454014e2012-04-28 16:03:55 -0700757 final String msg = "Scaling mode " + mode + " is not supported";
758 throw new IllegalArgumentException(msg);
759 }
760 Parcel request = Parcel.obtain();
761 Parcel reply = Parcel.obtain();
Insun Kangbe0ea962012-05-04 20:52:57 +0900762 try {
763 request.writeInterfaceToken(IMEDIA_PLAYER);
764 request.writeInt(INVOKE_ID_SET_VIDEO_SCALE_MODE);
Bryan Mawhinneyc3a5cf92012-05-27 17:42:46 +0100765 request.writeInt(mode);
Insun Kangbe0ea962012-05-04 20:52:57 +0900766 invoke(request, reply);
767 } finally {
768 request.recycle();
769 reply.recycle();
770 }
James Dong454014e2012-04-28 16:03:55 -0700771 }
772
Ted Bonkenburg0de171b2011-07-15 15:10:10 -0700773 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 * Convenience method to create a MediaPlayer for a given Uri.
775 * On success, {@link #prepare()} will already have been called and must not be called again.
776 * <p>When done with the MediaPlayer, you should call {@link #release()},
777 * to free the resources. If not released, too many MediaPlayer instances will
778 * result in an exception.</p>
Nicolas Catania32f82772009-06-11 16:33:49 -0700779 *
780 * @param context the Context to use
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 * @param uri the Uri from which to get the datasource
782 * @return a MediaPlayer object, or null if creation failed
783 */
784 public static MediaPlayer create(Context context, Uri uri) {
785 return create (context, uri, null);
786 }
Nicolas Catania32f82772009-06-11 16:33:49 -0700787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 /**
789 * Convenience method to create a MediaPlayer for a given Uri.
790 * On success, {@link #prepare()} will already have been called and must not be called again.
791 * <p>When done with the MediaPlayer, you should call {@link #release()},
792 * to free the resources. If not released, too many MediaPlayer instances will
793 * result in an exception.</p>
Nicolas Catania32f82772009-06-11 16:33:49 -0700794 *
795 * @param context the Context to use
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 * @param uri the Uri from which to get the datasource
797 * @param holder the SurfaceHolder to use for displaying the video
798 * @return a MediaPlayer object, or null if creation failed
799 */
800 public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
Nicolas Catania32f82772009-06-11 16:33:49 -0700801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 try {
803 MediaPlayer mp = new MediaPlayer();
804 mp.setDataSource(context, uri);
805 if (holder != null) {
806 mp.setDisplay(holder);
807 }
808 mp.prepare();
809 return mp;
810 } catch (IOException ex) {
811 Log.d(TAG, "create failed:", ex);
812 // fall through
813 } catch (IllegalArgumentException ex) {
814 Log.d(TAG, "create failed:", ex);
815 // fall through
816 } catch (SecurityException ex) {
817 Log.d(TAG, "create failed:", ex);
818 // fall through
819 }
820
821 return null;
822 }
823
Glenn Kastencc562a32011-02-08 17:26:17 -0800824 // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
825
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 /**
827 * Convenience method to create a MediaPlayer for a given resource id.
828 * On success, {@link #prepare()} will already have been called and must not be called again.
829 * <p>When done with the MediaPlayer, you should call {@link #release()},
830 * to free the resources. If not released, too many MediaPlayer instances will
831 * result in an exception.</p>
Nicolas Catania32f82772009-06-11 16:33:49 -0700832 *
833 * @param context the Context to use
834 * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835 * the resource to use as the datasource
836 * @return a MediaPlayer object, or null if creation failed
837 */
838 public static MediaPlayer create(Context context, int resid) {
839 try {
840 AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
841 if (afd == null) return null;
842
843 MediaPlayer mp = new MediaPlayer();
844 mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
845 afd.close();
846 mp.prepare();
847 return mp;
848 } catch (IOException ex) {
849 Log.d(TAG, "create failed:", ex);
850 // fall through
851 } catch (IllegalArgumentException ex) {
852 Log.d(TAG, "create failed:", ex);
853 // fall through
854 } catch (SecurityException ex) {
855 Log.d(TAG, "create failed:", ex);
856 // fall through
857 }
858 return null;
859 }
Nicolas Catania32f82772009-06-11 16:33:49 -0700860
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 /**
862 * Sets the data source as a content Uri.
Nicolas Catania32f82772009-06-11 16:33:49 -0700863 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 * @param context the Context to use when resolving the Uri
865 * @param uri the Content URI of the data you want to play
866 * @throws IllegalStateException if it is called in an invalid state
867 */
868 public void setDataSource(Context context, Uri uri)
869 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
Andreas Huber25643002010-01-28 11:19:57 -0800870 setDataSource(context, uri, null);
871 }
872
873 /**
874 * Sets the data source as a content Uri.
875 *
876 * @param context the Context to use when resolving the Uri
877 * @param uri the Content URI of the data you want to play
878 * @param headers the headers to be sent together with the request for the data
879 * @throws IllegalStateException if it is called in an invalid state
Andreas Huber25643002010-01-28 11:19:57 -0800880 */
881 public void setDataSource(Context context, Uri uri, Map<String, String> headers)
882 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800883 String scheme = uri.getScheme();
884 if(scheme == null || scheme.equals("file")) {
885 setDataSource(uri.getPath());
886 return;
887 }
888
889 AssetFileDescriptor fd = null;
890 try {
891 ContentResolver resolver = context.getContentResolver();
892 fd = resolver.openAssetFileDescriptor(uri, "r");
893 if (fd == null) {
894 return;
895 }
896 // Note: using getDeclaredLength so that our behavior is the same
897 // as previous versions when the content provider is returning
898 // a full file.
899 if (fd.getDeclaredLength() < 0) {
900 setDataSource(fd.getFileDescriptor());
901 } else {
902 setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
903 }
904 return;
905 } catch (SecurityException ex) {
906 } catch (IOException ex) {
907 } finally {
908 if (fd != null) {
909 fd.close();
910 }
911 }
Dave Burkefc301b02011-08-30 14:39:17 +0100912
Marco Nelissena2df6052009-06-09 15:49:23 -0700913 Log.d(TAG, "Couldn't open file on client side, trying server side");
Andreas Huberd5f9fa52013-05-28 14:39:39 -0700914
Andreas Huber25643002010-01-28 11:19:57 -0800915 setDataSource(uri.toString(), headers);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800916 }
917
918 /**
919 * Sets the data source (file-path or http/rtsp URL) to use.
Nicolas Catania32f82772009-06-11 16:33:49 -0700920 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 * @param path the path of the file, or the http/rtsp URL of the stream you want to play
922 * @throws IllegalStateException if it is called in an invalid state
Glenn Kasten55d1eea2012-03-09 11:02:31 -0800923 *
924 * <p>When <code>path</code> refers to a local file, the file may actually be opened by a
925 * process other than the calling application. This implies that the pathname
926 * should be an absolute path (as any other process runs with unspecified current working
927 * directory), and that the pathname should reference a world-readable file.
928 * As an alternative, the application could first open the file for reading,
929 * and then use the file descriptor form {@link #setDataSource(FileDescriptor)}.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 */
James Donge00b6f32012-04-11 21:18:43 -0700931 public void setDataSource(String path)
932 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
933 setDataSource(path, null, null);
934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935
936 /**
Andreas Huber25643002010-01-28 11:19:57 -0800937 * Sets the data source (file-path or http/rtsp URL) to use.
938 *
939 * @param path the path of the file, or the http/rtsp URL of the stream you want to play
940 * @param headers the headers associated with the http request for the stream you want to play
941 * @throws IllegalStateException if it is called in an invalid state
942 * @hide pending API council
943 */
James Dong17524dc2011-05-04 13:41:58 -0700944 public void setDataSource(String path, Map<String, String> headers)
Dave Burkefc301b02011-08-30 14:39:17 +0100945 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException
James Dong17524dc2011-05-04 13:41:58 -0700946 {
Andreas Hubere4e7b482011-05-11 16:54:41 -0700947 String[] keys = null;
948 String[] values = null;
949
950 if (headers != null) {
951 keys = new String[headers.size()];
952 values = new String[headers.size()];
953
954 int i = 0;
955 for (Map.Entry<String, String> entry: headers.entrySet()) {
956 keys[i] = entry.getKey();
957 values[i] = entry.getValue();
958 ++i;
959 }
James Dong17524dc2011-05-04 13:41:58 -0700960 }
James Donge00b6f32012-04-11 21:18:43 -0700961 setDataSource(path, keys, values);
962 }
963
964 private void setDataSource(String path, String[] keys, String[] values)
965 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
Jeff Sharkeyc058a382013-02-19 14:44:41 -0800966 final Uri uri = Uri.parse(path);
967 if ("file".equals(uri.getScheme())) {
968 path = uri.getPath();
969 }
970
971 final File file = new File(path);
James Donge00b6f32012-04-11 21:18:43 -0700972 if (file.exists()) {
973 FileInputStream is = new FileInputStream(file);
974 FileDescriptor fd = is.getFD();
975 setDataSource(fd);
976 is.close();
977 } else {
978 _setDataSource(path, keys, values);
979 }
James Dong17524dc2011-05-04 13:41:58 -0700980 }
981
Andreas Huberd2506a52014-01-29 10:32:46 -0800982 private void _setDataSource(
James Dong17524dc2011-05-04 13:41:58 -0700983 String path, String[] keys, String[] values)
Andreas Huberd2506a52014-01-29 10:32:46 -0800984 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
985 nativeSetDataSource(
986 MediaHTTPService.createHttpServiceBinderIfNecessary(path),
987 path,
988 keys,
989 values);
990 }
991
992 private native void nativeSetDataSource(
993 IBinder httpServiceBinder, String path, String[] keys, String[] values)
Dave Burkefc301b02011-08-30 14:39:17 +0100994 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
Andreas Huber25643002010-01-28 11:19:57 -0800995
996 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
998 * to close the file descriptor. It is safe to do so as soon as this call returns.
Nicolas Catania32f82772009-06-11 16:33:49 -0700999 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 * @param fd the FileDescriptor for the file you want to play
1001 * @throws IllegalStateException if it is called in an invalid state
1002 */
Nicolas Catania32f82772009-06-11 16:33:49 -07001003 public void setDataSource(FileDescriptor fd)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 throws IOException, IllegalArgumentException, IllegalStateException {
1005 // intentionally less than LONG_MAX
1006 setDataSource(fd, 0, 0x7ffffffffffffffL);
1007 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001008
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009 /**
Kenny Root6ab180a2009-06-13 06:16:23 -05001010 * Sets the data source (FileDescriptor) to use. The FileDescriptor must be
1011 * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 * to close the file descriptor. It is safe to do so as soon as this call returns.
Nicolas Catania32f82772009-06-11 16:33:49 -07001013 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 * @param fd the FileDescriptor for the file you want to play
1015 * @param offset the offset into the file where the data to be played starts, in bytes
1016 * @param length the length in bytes of the data to be played
1017 * @throws IllegalStateException if it is called in an invalid state
1018 */
Andreas Huberd5f9fa52013-05-28 14:39:39 -07001019 public void setDataSource(FileDescriptor fd, long offset, long length)
1020 throws IOException, IllegalArgumentException, IllegalStateException {
Andreas Huberd5f9fa52013-05-28 14:39:39 -07001021 _setDataSource(fd, offset, length);
1022 }
1023
1024 private native void _setDataSource(FileDescriptor fd, long offset, long length)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 throws IOException, IllegalArgumentException, IllegalStateException;
1026
1027 /**
1028 * Prepares the player for playback, synchronously.
Nicolas Catania32f82772009-06-11 16:33:49 -07001029 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001030 * After setting the datasource and the display surface, you need to either
1031 * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
1032 * which blocks until MediaPlayer is ready for playback.
Nicolas Catania32f82772009-06-11 16:33:49 -07001033 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 * @throws IllegalStateException if it is called in an invalid state
1035 */
1036 public native void prepare() throws IOException, IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001037
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 /**
1039 * Prepares the player for playback, asynchronously.
Nicolas Catania32f82772009-06-11 16:33:49 -07001040 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001041 * After setting the datasource and the display surface, you need to either
1042 * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
1043 * which returns immediately, rather than blocking until enough data has been
1044 * buffered.
Nicolas Catania32f82772009-06-11 16:33:49 -07001045 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 * @throws IllegalStateException if it is called in an invalid state
1047 */
1048 public native void prepareAsync() throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001049
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 /**
1051 * Starts or resumes playback. If playback had previously been paused,
1052 * playback will continue from where it was paused. If playback had
1053 * been stopped, or never started before, playback will start at the
1054 * beginning.
Nicolas Catania32f82772009-06-11 16:33:49 -07001055 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 * @throws IllegalStateException if it is called in an invalid state
1057 */
1058 public void start() throws IllegalStateException {
1059 stayAwake(true);
1060 _start();
1061 }
1062
1063 private native void _start() throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001064
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 /**
Nicolas Catania32f82772009-06-11 16:33:49 -07001066 * Stops playback after playback has been stopped or paused.
1067 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 * @throws IllegalStateException if the internal player engine has not been
1069 * initialized.
1070 */
1071 public void stop() throws IllegalStateException {
1072 stayAwake(false);
1073 _stop();
1074 }
1075
1076 private native void _stop() throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 /**
1079 * Pauses playback. Call start() to resume.
Nicolas Catania32f82772009-06-11 16:33:49 -07001080 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 * @throws IllegalStateException if the internal player engine has not been
1082 * initialized.
1083 */
1084 public void pause() throws IllegalStateException {
1085 stayAwake(false);
1086 _pause();
1087 }
1088
1089 private native void _pause() throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001090
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001091 /**
1092 * Set the low-level power management behavior for this MediaPlayer. This
1093 * can be used when the MediaPlayer is not playing through a SurfaceHolder
1094 * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
1095 * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
Nicolas Catania32f82772009-06-11 16:33:49 -07001096 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001097 * <p>This function has the MediaPlayer access the low-level power manager
1098 * service to control the device's power usage while playing is occurring.
1099 * The parameter is a combination of {@link android.os.PowerManager} wake flags.
1100 * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
1101 * permission.
1102 * By default, no attempt is made to keep the device awake during playback.
Nicolas Catania32f82772009-06-11 16:33:49 -07001103 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 * @param context the Context to use
1105 * @param mode the power/wake mode to set
1106 * @see android.os.PowerManager
1107 */
1108 public void setWakeMode(Context context, int mode) {
1109 boolean washeld = false;
1110 if (mWakeLock != null) {
1111 if (mWakeLock.isHeld()) {
1112 washeld = true;
1113 mWakeLock.release();
1114 }
1115 mWakeLock = null;
1116 }
1117
1118 PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1119 mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
1120 mWakeLock.setReferenceCounted(false);
1121 if (washeld) {
1122 mWakeLock.acquire();
1123 }
1124 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 /**
1127 * Control whether we should use the attached SurfaceHolder to keep the
1128 * screen on while video playback is occurring. This is the preferred
1129 * method over {@link #setWakeMode} where possible, since it doesn't
1130 * require that the application have permission for low-level wake lock
1131 * access.
Nicolas Catania32f82772009-06-11 16:33:49 -07001132 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 * @param screenOn Supply true to keep the screen on, false to allow it
1134 * to turn off.
1135 */
1136 public void setScreenOnWhilePlaying(boolean screenOn) {
1137 if (mScreenOnWhilePlaying != screenOn) {
Ted Bonkenburg0de171b2011-07-15 15:10:10 -07001138 if (screenOn && mSurfaceHolder == null) {
1139 Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
Glenn Kasten817c1612011-04-13 08:11:47 -07001140 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 mScreenOnWhilePlaying = screenOn;
1142 updateSurfaceScreenOn();
1143 }
1144 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001146 private void stayAwake(boolean awake) {
1147 if (mWakeLock != null) {
1148 if (awake && !mWakeLock.isHeld()) {
1149 mWakeLock.acquire();
1150 } else if (!awake && mWakeLock.isHeld()) {
1151 mWakeLock.release();
1152 }
1153 }
1154 mStayAwake = awake;
1155 updateSurfaceScreenOn();
1156 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001157
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 private void updateSurfaceScreenOn() {
1159 if (mSurfaceHolder != null) {
1160 mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1161 }
1162 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 /**
1165 * Returns the width of the video.
Nicolas Catania32f82772009-06-11 16:33:49 -07001166 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 * @return the width of the video, or 0 if there is no video,
Jean-Baptiste Queruea5f7672009-09-16 15:06:25 -07001168 * no display surface was set, or the width has not been determined
1169 * yet. The OnVideoSizeChangedListener can be registered via
1170 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1171 * to provide a notification when the width is available.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 */
1173 public native int getVideoWidth();
Nicolas Catania32f82772009-06-11 16:33:49 -07001174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 /**
1176 * Returns the height of the video.
Nicolas Catania32f82772009-06-11 16:33:49 -07001177 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 * @return the height of the video, or 0 if there is no video,
Jean-Baptiste Queruea5f7672009-09-16 15:06:25 -07001179 * no display surface was set, or the height has not been determined
1180 * yet. The OnVideoSizeChangedListener can be registered via
1181 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1182 * to provide a notification when the height is available.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 */
1184 public native int getVideoHeight();
Nicolas Catania32f82772009-06-11 16:33:49 -07001185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 /**
1187 * Checks whether the MediaPlayer is playing.
Nicolas Catania32f82772009-06-11 16:33:49 -07001188 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 * @return true if currently playing, false otherwise
Scott Main099fd802012-07-03 16:32:11 -07001190 * @throws IllegalStateException if the internal player engine has not been
1191 * initialized or has been released.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 */
1193 public native boolean isPlaying();
Nicolas Catania32f82772009-06-11 16:33:49 -07001194
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 /**
1196 * Seeks to specified time position.
Nicolas Catania32f82772009-06-11 16:33:49 -07001197 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 * @param msec the offset in milliseconds from the start to seek to
1199 * @throws IllegalStateException if the internal player engine has not been
1200 * initialized
1201 */
1202 public native void seekTo(int msec) throws IllegalStateException;
Nicolas Catania32f82772009-06-11 16:33:49 -07001203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 /**
1205 * Gets the current playback position.
Nicolas Catania32f82772009-06-11 16:33:49 -07001206 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 * @return the current position in milliseconds
1208 */
1209 public native int getCurrentPosition();
Nicolas Catania32f82772009-06-11 16:33:49 -07001210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 /**
1212 * Gets the duration of the file.
Nicolas Catania32f82772009-06-11 16:33:49 -07001213 *
Andreas Huber7cd281c2013-04-11 11:07:03 -07001214 * @return the duration in milliseconds, if no duration is available
1215 * (for example, if streaming live content), -1 is returned.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 */
1217 public native int getDuration();
Nicolas Catania32f82772009-06-11 16:33:49 -07001218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 /**
Nicolas Catania9193e082009-07-06 12:43:36 -07001220 * Gets the media metadata.
1221 *
1222 * @param update_only controls whether the full set of available
1223 * metadata is returned or just the set that changed since the
1224 * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
1225 * #METADATA_ALL}.
1226 *
1227 * @param apply_filter if true only metadata that matches the
1228 * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
1229 * #BYPASS_METADATA_FILTER}.
1230 *
1231 * @return The metadata, possibly empty. null if an error occured.
1232 // FIXME: unhide.
1233 * {@hide}
1234 */
1235 public Metadata getMetadata(final boolean update_only,
1236 final boolean apply_filter) {
Nicolas Catania5d55c712009-07-09 09:21:33 -07001237 Parcel reply = Parcel.obtain();
1238 Metadata data = new Metadata();
1239
1240 if (!native_getMetadata(update_only, apply_filter, reply)) {
1241 reply.recycle();
1242 return null;
1243 }
1244
1245 // Metadata takes over the parcel, don't recycle it unless
1246 // there is an error.
1247 if (!data.parse(reply)) {
1248 reply.recycle();
1249 return null;
1250 }
1251 return data;
Nicolas Catania9193e082009-07-06 12:43:36 -07001252 }
1253
1254 /**
1255 * Set a filter for the metadata update notification and update
1256 * retrieval. The caller provides 2 set of metadata keys, allowed
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001257 * and blocked. The blocked set always takes precedence over the
1258 * allowed one.
Nicolas Catania9193e082009-07-06 12:43:36 -07001259 * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001260 * shorthands to allow/block all or no metadata.
Nicolas Catania9193e082009-07-06 12:43:36 -07001261 *
1262 * By default, there is no filter set.
1263 *
1264 * @param allow Is the set of metadata the client is interested
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001265 * in receiving new notifications for.
1266 * @param block Is the set of metadata the client is not interested
1267 * in receiving new notifications for.
Nicolas Catania9193e082009-07-06 12:43:36 -07001268 * @return The call status code.
1269 *
1270 // FIXME: unhide.
1271 * {@hide}
1272 */
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001273 public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
1274 // Do our serialization manually instead of calling
1275 // Parcel.writeArray since the sets are made of the same type
1276 // we avoid paying the price of calling writeValue (used by
1277 // writeArray) which burns an extra int per element to encode
1278 // the type.
1279 Parcel request = newRequest();
1280
1281 // The parcel starts already with an interface token. There
1282 // are 2 filters. Each one starts with a 4bytes number to
1283 // store the len followed by a number of int (4 bytes as well)
1284 // representing the metadata type.
1285 int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
1286
1287 if (request.dataCapacity() < capacity) {
1288 request.setDataCapacity(capacity);
1289 }
1290
1291 request.writeInt(allow.size());
1292 for(Integer t: allow) {
1293 request.writeInt(t);
1294 }
1295 request.writeInt(block.size());
1296 for(Integer t: block) {
1297 request.writeInt(t);
1298 }
1299 return native_setMetadataFilter(request);
Nicolas Catania9193e082009-07-06 12:43:36 -07001300 }
1301
1302 /**
Marco Nelissen84b83202012-02-28 16:07:44 -08001303 * Set the MediaPlayer to start when this MediaPlayer finishes playback
1304 * (i.e. reaches the end of the stream).
1305 * The media framework will attempt to transition from this player to
1306 * the next as seamlessly as possible. The next player can be set at
1307 * any time before completion. The next player must be prepared by the
1308 * app, and the application should not call start() on it.
1309 * The next MediaPlayer must be different from 'this'. An exception
1310 * will be thrown if next == this.
1311 * The application may call setNextMediaPlayer(null) to indicate no
1312 * next player should be started at the end of playback.
1313 * If the current player is looping, it will keep looping and the next
1314 * player will not be started.
1315 *
1316 * @param next the player to start after this one completes playback.
1317 *
Marco Nelissen84b83202012-02-28 16:07:44 -08001318 */
1319 public native void setNextMediaPlayer(MediaPlayer next);
1320
1321 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 * Releases resources associated with this MediaPlayer object.
1323 * It is considered good practice to call this method when you're
James Dong89ca6982011-11-14 19:01:26 -08001324 * done using the MediaPlayer. In particular, whenever an Activity
1325 * of an application is paused (its onPause() method is called),
1326 * or stopped (its onStop() method is called), this method should be
1327 * invoked to release the MediaPlayer object, unless the application
1328 * has a special need to keep the object around. In addition to
1329 * unnecessary resources (such as memory and instances of codecs)
1330 * being held, failure to call this method immediately if a
1331 * MediaPlayer object is no longer needed may also lead to
1332 * continuous battery consumption for mobile devices, and playback
1333 * failure for other applications if no multiple instances of the
1334 * same codec are supported on a device. Even if multiple instances
1335 * of the same codec are supported, some performance degradation
1336 * may be expected when unnecessary multiple instances are used
1337 * at the same time.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 */
1339 public void release() {
1340 stayAwake(false);
1341 updateSurfaceScreenOn();
1342 mOnPreparedListener = null;
1343 mOnBufferingUpdateListener = null;
1344 mOnCompletionListener = null;
1345 mOnSeekCompleteListener = null;
1346 mOnErrorListener = null;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07001347 mOnInfoListener = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 mOnVideoSizeChangedListener = null;
Gloria Wang162ee492011-04-11 17:23:27 -07001349 mOnTimedTextListener = null;
Lajos Molnara67a4432013-09-06 06:30:35 -07001350 if (mTimeProvider != null) {
1351 mTimeProvider.close();
1352 mTimeProvider = null;
1353 }
Chong Zhang83ddaf62013-08-06 09:43:22 -07001354 mOnSubtitleDataListener = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 _release();
1356 }
1357
1358 private native void _release();
Nicolas Catania32f82772009-06-11 16:33:49 -07001359
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 /**
1361 * Resets the MediaPlayer to its uninitialized state. After calling
1362 * this method, you will have to initialize it again by setting the
1363 * data source and calling prepare().
1364 */
1365 public void reset() {
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001366 mSelectedSubtitleTrackIndex = -1;
1367 synchronized(mOpenSubtitleSources) {
1368 for (final InputStream is: mOpenSubtitleSources) {
1369 try {
1370 is.close();
1371 } catch (IOException e) {
1372 }
1373 }
1374 mOpenSubtitleSources.clear();
1375 }
1376 mOutOfBandSubtitleTracks.clear();
1377 mInbandSubtitleTracks = new SubtitleTrack[0];
1378 if (mSubtitleController != null) {
1379 mSubtitleController.reset();
1380 }
Lajos Molnara67a4432013-09-06 06:30:35 -07001381 if (mTimeProvider != null) {
1382 mTimeProvider.close();
1383 mTimeProvider = null;
1384 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 stayAwake(false);
1387 _reset();
1388 // make sure none of the listeners get called anymore
Lajos Molnara67a4432013-09-06 06:30:35 -07001389 if (mEventHandler != null) {
1390 mEventHandler.removeCallbacksAndMessages(null);
1391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
Nicolas Catania32f82772009-06-11 16:33:49 -07001393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 private native void _reset();
Nicolas Catania32f82772009-06-11 16:33:49 -07001395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001396 /**
1397 * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
James Dong9d963542010-06-03 10:36:04 -07001398 * for a list of stream types. Must call this method before prepare() or
1399 * prepareAsync() in order for the target stream type to become effective
1400 * thereafter.
Nicolas Catania32f82772009-06-11 16:33:49 -07001401 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 * @param streamtype the audio stream type
1403 * @see android.media.AudioManager
1404 */
1405 public native void setAudioStreamType(int streamtype);
1406
1407 /**
1408 * Sets the player to be looping or non-looping.
Nicolas Catania32f82772009-06-11 16:33:49 -07001409 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 * @param looping whether to loop or not
1411 */
1412 public native void setLooping(boolean looping);
1413
1414 /**
1415 * Checks whether the MediaPlayer is looping or non-looping.
Nicolas Catania32f82772009-06-11 16:33:49 -07001416 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 * @return true if the MediaPlayer is currently looping, false otherwise
1418 */
1419 public native boolean isLooping();
1420
1421 /**
Nicolas Catania32f82772009-06-11 16:33:49 -07001422 * Sets the volume on this player.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 * This API is recommended for balancing the output of audio streams
1424 * within an application. Unless you are writing an application to
1425 * control user settings, this API should be used in preference to
1426 * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
Glenn Kasten068225d2012-02-27 16:21:04 -08001427 * a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 * UI controls should be scaled logarithmically.
1429 *
1430 * @param leftVolume left volume scalar
1431 * @param rightVolume right volume scalar
1432 */
Glenn Kasten068225d2012-02-27 16:21:04 -08001433 /*
1434 * FIXME: Merge this into javadoc comment above when setVolume(float) is not @hide.
1435 * The single parameter form below is preferred if the channel volumes don't need
1436 * to be set independently.
1437 */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 public native void setVolume(float leftVolume, float rightVolume);
1439
1440 /**
Glenn Kasten068225d2012-02-27 16:21:04 -08001441 * Similar, excepts sets volume of all channels to same value.
1442 * @hide
1443 */
1444 public void setVolume(float volume) {
1445 setVolume(volume, volume);
1446 }
1447
1448 /**
Eric Laurent619346f2010-06-21 09:27:30 -07001449 * Sets the audio session ID.
1450 *
Eric Laurent17cb2802010-08-03 03:50:02 -07001451 * @param sessionId the audio session ID.
Eric Laurent619346f2010-06-21 09:27:30 -07001452 * The audio session ID is a system wide unique identifier for the audio stream played by
1453 * this MediaPlayer instance.
1454 * The primary use of the audio session ID is to associate audio effects to a particular
1455 * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
1456 * this effect will be applied only to the audio content of media players within the same
1457 * audio session and not to the output mix.
1458 * When created, a MediaPlayer instance automatically generates its own audio session ID.
1459 * However, it is possible to force this player to be part of an already existing audio session
1460 * by calling this method.
1461 * This method must be called before one of the overloaded <code> setDataSource </code> methods.
1462 * @throws IllegalStateException if it is called in an invalid state
Eric Laurent619346f2010-06-21 09:27:30 -07001463 */
1464 public native void setAudioSessionId(int sessionId) throws IllegalArgumentException, IllegalStateException;
1465
1466 /**
1467 * Returns the audio session ID.
1468 *
Eric Laurent17cb2802010-08-03 03:50:02 -07001469 * @return the audio session ID. {@see #setAudioSessionId(int)}
Eric Laurent619346f2010-06-21 09:27:30 -07001470 * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
Eric Laurent619346f2010-06-21 09:27:30 -07001471 */
1472 public native int getAudioSessionId();
1473
1474 /**
Eric Laurent7070b362010-07-16 07:43:46 -07001475 * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1476 * effect which can be applied on any sound source that directs a certain amount of its
1477 * energy to this effect. This amount is defined by setAuxEffectSendLevel().
1478 * {@see #setAuxEffectSendLevel(float)}.
Eric Laurent1a5149e2010-09-21 18:18:20 -07001479 * <p>After creating an auxiliary effect (e.g.
1480 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1481 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1482 * to attach the player to the effect.
Eric Laurent7070b362010-07-16 07:43:46 -07001483 * <p>To detach the effect from the player, call this method with a null effect id.
1484 * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1485 * methods.
Eric Laurent7070b362010-07-16 07:43:46 -07001486 * @param effectId system wide unique id of the effect to attach
Eric Laurent7070b362010-07-16 07:43:46 -07001487 */
1488 public native void attachAuxEffect(int effectId);
1489
Gloria Wangd01ec6e2011-04-25 17:28:22 -07001490
1491 /**
Eric Laurent7070b362010-07-16 07:43:46 -07001492 * Sets the send level of the player to the attached auxiliary effect
1493 * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1494 * <p>By default the send level is 0, so even if an effect is attached to the player
1495 * this method must be called for the effect to be applied.
1496 * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1497 * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1498 * so an appropriate conversion from linear UI input x to level is:
1499 * x == 0 -> level = 0
1500 * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1501 * @param level send level scalar
Eric Laurent7070b362010-07-16 07:43:46 -07001502 */
1503 public native void setAuxEffectSendLevel(float level);
1504
Insun Kang41f3f712012-02-16 20:28:27 +09001505 /*
Nicolas Catania20cb94e2009-05-12 23:25:55 -07001506 * @param request Parcel destinated to the media player. The
1507 * Interface token must be set to the IMediaPlayer
1508 * one to be routed correctly through the system.
Nicolas Catania5d55c712009-07-09 09:21:33 -07001509 * @param reply[out] Parcel that will contain the reply.
Nicolas Catania20cb94e2009-05-12 23:25:55 -07001510 * @return The status code.
1511 */
1512 private native final int native_invoke(Parcel request, Parcel reply);
1513
Nicolas Catania5d55c712009-07-09 09:21:33 -07001514
Insun Kang41f3f712012-02-16 20:28:27 +09001515 /*
Nicolas Catania5d55c712009-07-09 09:21:33 -07001516 * @param update_only If true fetch only the set of metadata that have
1517 * changed since the last invocation of getMetadata.
1518 * The set is built using the unfiltered
1519 * notifications the native player sent to the
1520 * MediaPlayerService during that period of
1521 * time. If false, all the metadatas are considered.
1522 * @param apply_filter If true, once the metadata set has been built based on
1523 * the value update_only, the current filter is applied.
1524 * @param reply[out] On return contains the serialized
1525 * metadata. Valid only if the call was successful.
1526 * @return The status code.
1527 */
1528 private native final boolean native_getMetadata(boolean update_only,
1529 boolean apply_filter,
1530 Parcel reply);
1531
Insun Kang41f3f712012-02-16 20:28:27 +09001532 /*
Nicolas Cataniab2c69392009-07-08 08:57:42 -07001533 * @param request Parcel with the 2 serialized lists of allowed
1534 * metadata types followed by the one to be
1535 * dropped. Each list starts with an integer
1536 * indicating the number of metadata type elements.
1537 * @return The status code.
1538 */
1539 private native final int native_setMetadataFilter(Parcel request);
1540
Marco Nelissen4935d052009-08-03 11:12:58 -07001541 private static native final void native_init();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 private native final void native_setup(Object mediaplayer_this);
1543 private native final void native_finalize();
Nicolas Catania20cb94e2009-05-12 23:25:55 -07001544
Gloria Wangd211f412011-02-19 18:37:57 -08001545 /**
Insun Kang41f3f712012-02-16 20:28:27 +09001546 * Class for MediaPlayer to return each audio/video/subtitle track's metadata.
1547 *
James Dong7a9734d2012-04-19 13:30:20 -07001548 * @see android.media.MediaPlayer#getTrackInfo
Gloria Wangc6091dd2011-05-03 15:59:03 -07001549 */
Insun Kang41f3f712012-02-16 20:28:27 +09001550 static public class TrackInfo implements Parcelable {
1551 /**
1552 * Gets the track type.
1553 * @return TrackType which indicates if the track is video, audio, timed text.
1554 */
1555 public int getTrackType() {
1556 return mTrackType;
Gloria Wangc6091dd2011-05-03 15:59:03 -07001557 }
Insun Kang41f3f712012-02-16 20:28:27 +09001558
1559 /**
1560 * Gets the language code of the track.
1561 * @return a language code in either way of ISO-639-1 or ISO-639-2.
1562 * When the language is unknown or could not be determined,
1563 * ISO-639-2 language code, "und", is returned.
1564 */
1565 public String getLanguage() {
Lajos Molnar1c56a672013-08-15 12:05:52 -07001566 String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
1567 return language == null ? "und" : language;
1568 }
1569
1570 /**
1571 * Gets the {@link MediaFormat} of the track. If the format is
1572 * unknown or could not be determined, null is returned.
1573 */
1574 public MediaFormat getFormat() {
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001575 if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT
1576 || mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
Lajos Molnar1c56a672013-08-15 12:05:52 -07001577 return mFormat;
1578 }
1579 return null;
Insun Kang41f3f712012-02-16 20:28:27 +09001580 }
1581
1582 public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
1583 public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
1584 public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
1585 public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
Chong Zhang83ddaf62013-08-06 09:43:22 -07001586 /** @hide */
1587 public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
Insun Kang41f3f712012-02-16 20:28:27 +09001588
1589 final int mTrackType;
Lajos Molnar1c56a672013-08-15 12:05:52 -07001590 final MediaFormat mFormat;
Insun Kang41f3f712012-02-16 20:28:27 +09001591
1592 TrackInfo(Parcel in) {
1593 mTrackType = in.readInt();
Lajos Molnar1c56a672013-08-15 12:05:52 -07001594 // TODO: parcel in the full MediaFormat
1595 String language = in.readString();
1596
1597 if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1598 mFormat = MediaFormat.createSubtitleFormat(
1599 MEDIA_MIMETYPE_TEXT_SUBRIP, language);
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001600 } else if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
1601 mFormat = MediaFormat.createSubtitleFormat(
1602 MEDIA_MIMETYPE_TEXT_VTT, language);
Lajos Molnard486f962013-09-11 16:26:18 -07001603 mFormat.setInteger(MediaFormat.KEY_IS_AUTOSELECT, in.readInt());
1604 mFormat.setInteger(MediaFormat.KEY_IS_DEFAULT, in.readInt());
1605 mFormat.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.readInt());
Lajos Molnar1c56a672013-08-15 12:05:52 -07001606 } else {
1607 mFormat = new MediaFormat();
1608 mFormat.setString(MediaFormat.KEY_LANGUAGE, language);
1609 }
Insun Kang41f3f712012-02-16 20:28:27 +09001610 }
1611
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001612 /** @hide */
1613 TrackInfo(int type, MediaFormat format) {
1614 mTrackType = type;
1615 mFormat = format;
1616 }
1617
James Dong7a9734d2012-04-19 13:30:20 -07001618 /**
1619 * {@inheritDoc}
Insun Kang41f3f712012-02-16 20:28:27 +09001620 */
1621 @Override
1622 public int describeContents() {
1623 return 0;
1624 }
1625
James Dong7a9734d2012-04-19 13:30:20 -07001626 /**
1627 * {@inheritDoc}
Insun Kang41f3f712012-02-16 20:28:27 +09001628 */
1629 @Override
1630 public void writeToParcel(Parcel dest, int flags) {
1631 dest.writeInt(mTrackType);
Lajos Molnar1c56a672013-08-15 12:05:52 -07001632 dest.writeString(getLanguage());
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001633
1634 if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
Lajos Molnard486f962013-09-11 16:26:18 -07001635 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_AUTOSELECT));
1636 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_DEFAULT));
1637 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE));
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001638 }
Insun Kang41f3f712012-02-16 20:28:27 +09001639 }
1640
1641 /**
1642 * Used to read a TrackInfo from a Parcel.
1643 */
1644 static final Parcelable.Creator<TrackInfo> CREATOR
1645 = new Parcelable.Creator<TrackInfo>() {
1646 @Override
1647 public TrackInfo createFromParcel(Parcel in) {
1648 return new TrackInfo(in);
1649 }
1650
1651 @Override
1652 public TrackInfo[] newArray(int size) {
1653 return new TrackInfo[size];
1654 }
1655 };
1656
1657 };
1658
1659 /**
1660 * Returns an array of track information.
1661 *
James Dong831f0a92012-04-18 18:12:12 -07001662 * @return Array of track info. The total number of tracks is the array length.
James Dong7a9734d2012-04-19 13:30:20 -07001663 * Must be called again if an external timed text source has been added after any of the
1664 * addTimedTextSource methods are called.
1665 * @throws IllegalStateException if it is called in an invalid state.
Insun Kang41f3f712012-02-16 20:28:27 +09001666 */
James Dong7a9734d2012-04-19 13:30:20 -07001667 public TrackInfo[] getTrackInfo() throws IllegalStateException {
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001668 TrackInfo trackInfo[] = getInbandTrackInfo();
1669 // add out-of-band tracks
1670 TrackInfo allTrackInfo[] = new TrackInfo[trackInfo.length + mOutOfBandSubtitleTracks.size()];
1671 System.arraycopy(trackInfo, 0, allTrackInfo, 0, trackInfo.length);
1672 int i = trackInfo.length;
1673 for (SubtitleTrack track: mOutOfBandSubtitleTracks) {
1674 allTrackInfo[i] = new TrackInfo(TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE, track.getFormat());
1675 ++i;
1676 }
1677 return allTrackInfo;
1678 }
1679
1680 private TrackInfo[] getInbandTrackInfo() throws IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09001681 Parcel request = Parcel.obtain();
1682 Parcel reply = Parcel.obtain();
Insun Kangbe0ea962012-05-04 20:52:57 +09001683 try {
1684 request.writeInterfaceToken(IMEDIA_PLAYER);
1685 request.writeInt(INVOKE_ID_GET_TRACK_INFO);
1686 invoke(request, reply);
1687 TrackInfo trackInfo[] = reply.createTypedArray(TrackInfo.CREATOR);
1688 return trackInfo;
1689 } finally {
1690 request.recycle();
1691 reply.recycle();
1692 }
Insun Kang41f3f712012-02-16 20:28:27 +09001693 }
1694
James Dong831f0a92012-04-18 18:12:12 -07001695 /* Do not change these values without updating their counterparts
1696 * in include/media/stagefright/MediaDefs.h and media/libstagefright/MediaDefs.cpp!
1697 */
1698 /**
James Dong7a9734d2012-04-19 13:30:20 -07001699 * MIME type for SubRip (SRT) container. Used in addTimedTextSource APIs.
James Dong831f0a92012-04-18 18:12:12 -07001700 */
1701 public static final String MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
1702
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001703 /**
1704 * MIME type for WebVTT subtitle data.
1705 * @hide
1706 */
1707 public static final String MEDIA_MIMETYPE_TEXT_VTT = "text/vtt";
1708
Insun Kang41f3f712012-02-16 20:28:27 +09001709 /*
1710 * A helper function to check if the mime type is supported by media framework.
1711 */
James Dong831f0a92012-04-18 18:12:12 -07001712 private static boolean availableMimeTypeForExternalSource(String mimeType) {
Insun Kang41f3f712012-02-16 20:28:27 +09001713 if (mimeType == MEDIA_MIMETYPE_TEXT_SUBRIP) {
1714 return true;
1715 }
1716 return false;
1717 }
1718
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001719 private SubtitleController mSubtitleController;
1720
1721 /** @hide */
1722 public void setSubtitleAnchor(
1723 SubtitleController controller,
1724 SubtitleController.Anchor anchor) {
1725 // TODO: create SubtitleController in MediaPlayer
1726 mSubtitleController = controller;
1727 mSubtitleController.setAnchor(anchor);
1728 }
1729
1730 private SubtitleTrack[] mInbandSubtitleTracks;
1731 private int mSelectedSubtitleTrackIndex = -1;
1732 private Vector<SubtitleTrack> mOutOfBandSubtitleTracks;
1733 private Vector<InputStream> mOpenSubtitleSources;
1734
1735 private OnSubtitleDataListener mSubtitleDataListener = new OnSubtitleDataListener() {
1736 @Override
1737 public void onSubtitleData(MediaPlayer mp, SubtitleData data) {
1738 int index = data.getTrackIndex();
1739 if (index >= mInbandSubtitleTracks.length) {
1740 return;
1741 }
1742 SubtitleTrack track = mInbandSubtitleTracks[index];
1743 if (track != null) {
1744 try {
1745 long runID = data.getStartTimeUs() + 1;
1746 // TODO: move conversion into track
1747 track.onData(new String(data.getData(), "UTF-8"), true /* eos */, runID);
1748 track.setRunDiscardTimeMs(
1749 runID,
1750 (data.getStartTimeUs() + data.getDurationUs()) / 1000);
1751 } catch (java.io.UnsupportedEncodingException e) {
1752 Log.w(TAG, "subtitle data for track " + index + " is not UTF-8 encoded: " + e);
1753 }
1754 }
1755 }
1756 };
1757
1758 /** @hide */
1759 @Override
1760 public void onSubtitleTrackSelected(SubtitleTrack track) {
1761 if (mSelectedSubtitleTrackIndex >= 0) {
Lajos Molnard486f962013-09-11 16:26:18 -07001762 try {
1763 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, false);
1764 } catch (IllegalStateException e) {
1765 }
1766 mSelectedSubtitleTrackIndex = -1;
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001767 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001768 setOnSubtitleDataListener(null);
Lajos Molnar29f51832013-09-20 08:45:31 -07001769 if (track == null) {
1770 return;
1771 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001772 for (int i = 0; i < mInbandSubtitleTracks.length; i++) {
1773 if (mInbandSubtitleTracks[i] == track) {
1774 Log.v(TAG, "Selecting subtitle track " + i);
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001775 mSelectedSubtitleTrackIndex = i;
Lajos Molnard486f962013-09-11 16:26:18 -07001776 try {
1777 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, true);
1778 } catch (IllegalStateException e) {
1779 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001780 setOnSubtitleDataListener(mSubtitleDataListener);
1781 break;
1782 }
1783 }
1784 // no need to select out-of-band tracks
1785 }
1786
1787 /** @hide */
1788 public void addSubtitleSource(InputStream is, MediaFormat format)
1789 throws IllegalStateException
1790 {
1791 final InputStream fIs = is;
1792 final MediaFormat fFormat = format;
1793
1794 // Ensure all input streams are closed. It is also a handy
1795 // way to implement timeouts in the future.
1796 synchronized(mOpenSubtitleSources) {
1797 mOpenSubtitleSources.add(is);
1798 }
1799
1800 // process each subtitle in its own thread
1801 final HandlerThread thread = new HandlerThread("SubtitleReadThread",
1802 Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
1803 thread.start();
1804 Handler handler = new Handler(thread.getLooper());
1805 handler.post(new Runnable() {
1806 private int addTrack() {
1807 if (fIs == null || mSubtitleController == null) {
1808 return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
1809 }
1810
1811 SubtitleTrack track = mSubtitleController.addTrack(fFormat);
1812 if (track == null) {
1813 return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
1814 }
1815
1816 // TODO: do the conversion in the subtitle track
1817 Scanner scanner = new Scanner(fIs, "UTF-8");
1818 String contents = scanner.useDelimiter("\\A").next();
1819 synchronized(mOpenSubtitleSources) {
1820 mOpenSubtitleSources.remove(fIs);
1821 }
1822 scanner.close();
1823 mOutOfBandSubtitleTracks.add(track);
1824 track.onData(contents, true /* eos */, ~0 /* runID: keep forever */);
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001825 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
1826 }
1827
1828 public void run() {
1829 int res = addTrack();
1830 if (mEventHandler != null) {
1831 Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
1832 mEventHandler.sendMessage(m);
1833 }
1834 thread.getLooper().quitSafely();
1835 }
1836 });
1837 }
1838
1839 private void scanInternalSubtitleTracks() {
1840 if (mSubtitleController == null) {
1841 Log.e(TAG, "Should have subtitle controller already set");
1842 return;
1843 }
1844
1845 TrackInfo[] tracks = getInbandTrackInfo();
1846 SubtitleTrack[] inbandTracks = new SubtitleTrack[tracks.length];
1847 for (int i=0; i < tracks.length; i++) {
1848 if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
1849 if (i < mInbandSubtitleTracks.length) {
1850 inbandTracks[i] = mInbandSubtitleTracks[i];
1851 } else {
Chong Zhangf8ca13b2013-09-11 13:41:00 -07001852 SubtitleTrack track = mSubtitleController.addTrack(
1853 tracks[i].getFormat());
Lajos Molnar484ff7a92013-08-15 11:37:47 -07001854 inbandTracks[i] = track;
1855 }
1856 }
1857 }
1858 mInbandSubtitleTracks = inbandTracks;
1859 mSubtitleController.selectDefaultTrack();
1860 }
1861
Insun Kang41f3f712012-02-16 20:28:27 +09001862 /* TODO: Limit the total number of external timed text source to a reasonable number.
1863 */
1864 /**
James Dong7a9734d2012-04-19 13:30:20 -07001865 * Adds an external timed text source file.
Insun Kang41f3f712012-02-16 20:28:27 +09001866 *
1867 * Currently supported format is SubRip with the file extension .srt, case insensitive.
James Dong7a9734d2012-04-19 13:30:20 -07001868 * Note that a single external timed text source may contain multiple tracks in it.
Insun Kang41f3f712012-02-16 20:28:27 +09001869 * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1870 * additional tracks become available after this method call.
1871 *
James Dong7a9734d2012-04-19 13:30:20 -07001872 * @param path The file path of external timed text source file.
James Dong831f0a92012-04-18 18:12:12 -07001873 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1874 * @throws IOException if the file cannot be accessed or is corrupted.
1875 * @throws IllegalArgumentException if the mimeType is not supported.
James Dong7a9734d2012-04-19 13:30:20 -07001876 * @throws IllegalStateException if called in an invalid state.
Insun Kang41f3f712012-02-16 20:28:27 +09001877 */
James Dong7a9734d2012-04-19 13:30:20 -07001878 public void addTimedTextSource(String path, String mimeType)
1879 throws IOException, IllegalArgumentException, IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09001880 if (!availableMimeTypeForExternalSource(mimeType)) {
James Dong7a9734d2012-04-19 13:30:20 -07001881 final String msg = "Illegal mimeType for timed text source: " + mimeType;
James Dongc4c02842012-04-12 19:49:02 -07001882 throw new IllegalArgumentException(msg);
Insun Kang41f3f712012-02-16 20:28:27 +09001883 }
1884
James Dongc4c02842012-04-12 19:49:02 -07001885 File file = new File(path);
1886 if (file.exists()) {
1887 FileInputStream is = new FileInputStream(file);
1888 FileDescriptor fd = is.getFD();
James Dong7a9734d2012-04-19 13:30:20 -07001889 addTimedTextSource(fd, mimeType);
James Dongc4c02842012-04-12 19:49:02 -07001890 is.close();
1891 } else {
1892 // We do not support the case where the path is not a file.
1893 throw new IOException(path);
1894 }
Gloria Wangc6091dd2011-05-03 15:59:03 -07001895 }
1896
1897 /**
James Dong7a9734d2012-04-19 13:30:20 -07001898 * Adds an external timed text source file (Uri).
Insun Kang41f3f712012-02-16 20:28:27 +09001899 *
1900 * Currently supported format is SubRip with the file extension .srt, case insensitive.
James Dong7a9734d2012-04-19 13:30:20 -07001901 * Note that a single external timed text source may contain multiple tracks in it.
Insun Kang41f3f712012-02-16 20:28:27 +09001902 * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1903 * additional tracks become available after this method call.
1904 *
1905 * @param context the Context to use when resolving the Uri
1906 * @param uri the Content URI of the data you want to play
James Dong831f0a92012-04-18 18:12:12 -07001907 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1908 * @throws IOException if the file cannot be accessed or is corrupted.
1909 * @throws IllegalArgumentException if the mimeType is not supported.
James Dong7a9734d2012-04-19 13:30:20 -07001910 * @throws IllegalStateException if called in an invalid state.
Gloria Wangc6091dd2011-05-03 15:59:03 -07001911 */
James Dong7a9734d2012-04-19 13:30:20 -07001912 public void addTimedTextSource(Context context, Uri uri, String mimeType)
1913 throws IOException, IllegalArgumentException, IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09001914 String scheme = uri.getScheme();
1915 if(scheme == null || scheme.equals("file")) {
James Dong7a9734d2012-04-19 13:30:20 -07001916 addTimedTextSource(uri.getPath(), mimeType);
Insun Kang41f3f712012-02-16 20:28:27 +09001917 return;
1918 }
1919
1920 AssetFileDescriptor fd = null;
1921 try {
1922 ContentResolver resolver = context.getContentResolver();
1923 fd = resolver.openAssetFileDescriptor(uri, "r");
1924 if (fd == null) {
1925 return;
1926 }
James Dong7a9734d2012-04-19 13:30:20 -07001927 addTimedTextSource(fd.getFileDescriptor(), mimeType);
Insun Kang41f3f712012-02-16 20:28:27 +09001928 return;
1929 } catch (SecurityException ex) {
1930 } catch (IOException ex) {
1931 } finally {
1932 if (fd != null) {
1933 fd.close();
1934 }
1935 }
Insun Kang41f3f712012-02-16 20:28:27 +09001936 }
1937
Insun Kang41f3f712012-02-16 20:28:27 +09001938 /**
James Dong7a9734d2012-04-19 13:30:20 -07001939 * Adds an external timed text source file (FileDescriptor).
1940 *
Insun Kang41f3f712012-02-16 20:28:27 +09001941 * It is the caller's responsibility to close the file descriptor.
1942 * It is safe to do so as soon as this call returns.
1943 *
James Dong7a9734d2012-04-19 13:30:20 -07001944 * Currently supported format is SubRip. Note that a single external timed text source may
1945 * contain multiple tracks in it. One can find the total number of available tracks
1946 * using {@link #getTrackInfo()} to see what additional tracks become available
1947 * after this method call.
Insun Kang41f3f712012-02-16 20:28:27 +09001948 *
1949 * @param fd the FileDescriptor for the file you want to play
James Dong831f0a92012-04-18 18:12:12 -07001950 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1951 * @throws IllegalArgumentException if the mimeType is not supported.
James Dong7a9734d2012-04-19 13:30:20 -07001952 * @throws IllegalStateException if called in an invalid state.
Insun Kang41f3f712012-02-16 20:28:27 +09001953 */
James Dong7a9734d2012-04-19 13:30:20 -07001954 public void addTimedTextSource(FileDescriptor fd, String mimeType)
1955 throws IllegalArgumentException, IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09001956 // intentionally less than LONG_MAX
James Dong7a9734d2012-04-19 13:30:20 -07001957 addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
Gloria Wangc6091dd2011-05-03 15:59:03 -07001958 }
1959
1960 /**
Insun Kang41f3f712012-02-16 20:28:27 +09001961 * Adds an external timed text file (FileDescriptor).
James Dong7a9734d2012-04-19 13:30:20 -07001962 *
Insun Kang41f3f712012-02-16 20:28:27 +09001963 * It is the caller's responsibility to close the file descriptor.
1964 * It is safe to do so as soon as this call returns.
1965 *
James Dong7a9734d2012-04-19 13:30:20 -07001966 * Currently supported format is SubRip. Note that a single external timed text source may
1967 * contain multiple tracks in it. One can find the total number of available tracks
1968 * using {@link #getTrackInfo()} to see what additional tracks become available
1969 * after this method call.
Insun Kang41f3f712012-02-16 20:28:27 +09001970 *
1971 * @param fd the FileDescriptor for the file you want to play
1972 * @param offset the offset into the file where the data to be played starts, in bytes
1973 * @param length the length in bytes of the data to be played
James Dong831f0a92012-04-18 18:12:12 -07001974 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1975 * @throws IllegalArgumentException if the mimeType is not supported.
James Dong7a9734d2012-04-19 13:30:20 -07001976 * @throws IllegalStateException if called in an invalid state.
Gloria Wangc6091dd2011-05-03 15:59:03 -07001977 */
James Dong7a9734d2012-04-19 13:30:20 -07001978 public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mimeType)
1979 throws IllegalArgumentException, IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09001980 if (!availableMimeTypeForExternalSource(mimeType)) {
James Dong7a9734d2012-04-19 13:30:20 -07001981 throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mimeType);
Insun Kang41f3f712012-02-16 20:28:27 +09001982 }
James Dongc4c02842012-04-12 19:49:02 -07001983
Insun Kang41f3f712012-02-16 20:28:27 +09001984 Parcel request = Parcel.obtain();
1985 Parcel reply = Parcel.obtain();
Insun Kangbe0ea962012-05-04 20:52:57 +09001986 try {
1987 request.writeInterfaceToken(IMEDIA_PLAYER);
1988 request.writeInt(INVOKE_ID_ADD_EXTERNAL_SOURCE_FD);
1989 request.writeFileDescriptor(fd);
1990 request.writeLong(offset);
1991 request.writeLong(length);
1992 request.writeString(mimeType);
1993 invoke(request, reply);
1994 } finally {
1995 request.recycle();
1996 reply.recycle();
1997 }
Insun Kang41f3f712012-02-16 20:28:27 +09001998 }
1999
2000 /**
2001 * Selects a track.
2002 * <p>
James Dong831f0a92012-04-18 18:12:12 -07002003 * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
2004 * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
Insun Kang41f3f712012-02-16 20:28:27 +09002005 * If a MediaPlayer is not in Started state, it just marks the track to be played.
2006 * </p>
2007 * <p>
2008 * In any valid state, if it is called multiple times on the same type of track (ie. Video,
2009 * Audio, Timed Text), the most recent one will be chosen.
2010 * </p>
2011 * <p>
James Dong831f0a92012-04-18 18:12:12 -07002012 * The first audio and video tracks are selected by default if available, even though
2013 * this method is not called. However, no timed text track will be selected until
2014 * this function is called.
Insun Kang41f3f712012-02-16 20:28:27 +09002015 * </p>
James Dong831f0a92012-04-18 18:12:12 -07002016 * <p>
2017 * Currently, only timed text tracks or audio tracks can be selected via this method.
2018 * In addition, the support for selecting an audio track at runtime is pretty limited
2019 * in that an audio track can only be selected in the <em>Prepared</em> state.
2020 * </p>
2021 * @param index the index of the track to be selected. The valid range of the index
2022 * is 0..total number of track - 1. The total number of tracks as well as the type of
2023 * each individual track can be found by calling {@link #getTrackInfo()} method.
James Dong7a9734d2012-04-19 13:30:20 -07002024 * @throws IllegalStateException if called in an invalid state.
2025 *
2026 * @see android.media.MediaPlayer#getTrackInfo
Insun Kang41f3f712012-02-16 20:28:27 +09002027 */
James Dong7a9734d2012-04-19 13:30:20 -07002028 public void selectTrack(int index) throws IllegalStateException {
2029 selectOrDeselectTrack(index, true /* select */);
Insun Kang41f3f712012-02-16 20:28:27 +09002030 }
2031
2032 /**
James Dong7a9734d2012-04-19 13:30:20 -07002033 * Deselect a track.
James Dong831f0a92012-04-18 18:12:12 -07002034 * <p>
2035 * Currently, the track must be a timed text track and no audio or video tracks can be
James Dong7a9734d2012-04-19 13:30:20 -07002036 * deselected. If the timed text track identified by index has not been
James Dong831f0a92012-04-18 18:12:12 -07002037 * selected before, it throws an exception.
2038 * </p>
James Dong7a9734d2012-04-19 13:30:20 -07002039 * @param index the index of the track to be deselected. The valid range of the index
James Dong831f0a92012-04-18 18:12:12 -07002040 * is 0..total number of tracks - 1. The total number of tracks as well as the type of
2041 * each individual track can be found by calling {@link #getTrackInfo()} method.
James Dong7a9734d2012-04-19 13:30:20 -07002042 * @throws IllegalStateException if called in an invalid state.
James Dong831f0a92012-04-18 18:12:12 -07002043 *
James Dong7a9734d2012-04-19 13:30:20 -07002044 * @see android.media.MediaPlayer#getTrackInfo
Insun Kang41f3f712012-02-16 20:28:27 +09002045 */
James Dong7a9734d2012-04-19 13:30:20 -07002046 public void deselectTrack(int index) throws IllegalStateException {
2047 selectOrDeselectTrack(index, false /* select */);
James Dong831f0a92012-04-18 18:12:12 -07002048 }
2049
James Dong7a9734d2012-04-19 13:30:20 -07002050 private void selectOrDeselectTrack(int index, boolean select)
2051 throws IllegalStateException {
Lajos Molnard486f962013-09-11 16:26:18 -07002052 // handle subtitle track through subtitle controller
2053 SubtitleTrack track = null;
2054 if (index < mInbandSubtitleTracks.length) {
2055 track = mInbandSubtitleTracks[index];
2056 } else if (index < mInbandSubtitleTracks.length + mOutOfBandSubtitleTracks.size()) {
2057 track = mOutOfBandSubtitleTracks.get(index - mInbandSubtitleTracks.length);
2058 }
2059
2060 if (mSubtitleController != null && track != null) {
2061 if (select) {
2062 mSubtitleController.selectTrack(track);
2063 } else if (mSubtitleController.getSelectedTrack() == track) {
2064 mSubtitleController.selectTrack(null);
2065 } else {
2066 Log.w(TAG, "trying to deselect track that was not selected");
2067 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002068 return;
2069 }
2070
Lajos Molnard486f962013-09-11 16:26:18 -07002071 selectOrDeselectInbandTrack(index, select);
2072 }
2073
2074 private void selectOrDeselectInbandTrack(int index, boolean select)
2075 throws IllegalStateException {
Insun Kang41f3f712012-02-16 20:28:27 +09002076 Parcel request = Parcel.obtain();
2077 Parcel reply = Parcel.obtain();
Insun Kangbe0ea962012-05-04 20:52:57 +09002078 try {
2079 request.writeInterfaceToken(IMEDIA_PLAYER);
2080 request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
2081 request.writeInt(index);
2082 invoke(request, reply);
2083 } finally {
2084 request.recycle();
2085 reply.recycle();
2086 }
Gloria Wangc6091dd2011-05-03 15:59:03 -07002087 }
2088
James Dong831f0a92012-04-18 18:12:12 -07002089
Gloria Wangc6091dd2011-05-03 15:59:03 -07002090 /**
Gloria Wangd211f412011-02-19 18:37:57 -08002091 * @param reply Parcel with audio/video duration info for battery
2092 tracking usage
2093 * @return The status code.
2094 * {@hide}
2095 */
2096 public native static int native_pullBatteryData(Parcel reply);
2097
John Grossman720aa282012-02-22 15:38:35 -08002098 /**
2099 * Sets the target UDP re-transmit endpoint for the low level player.
2100 * Generally, the address portion of the endpoint is an IP multicast
2101 * address, although a unicast address would be equally valid. When a valid
2102 * retransmit endpoint has been set, the media player will not decode and
2103 * render the media presentation locally. Instead, the player will attempt
2104 * to re-multiplex its media data using the Android@Home RTP profile and
2105 * re-transmit to the target endpoint. Receiver devices (which may be
2106 * either the same as the transmitting device or different devices) may
2107 * instantiate, prepare, and start a receiver player using a setDataSource
2108 * URL of the form...
2109 *
2110 * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
2111 *
2112 * to receive, decode and render the re-transmitted content.
2113 *
2114 * setRetransmitEndpoint may only be called before setDataSource has been
2115 * called; while the player is in the Idle state.
2116 *
2117 * @param endpoint the address and UDP port of the re-transmission target or
2118 * null if no re-transmission is to be performed.
2119 * @throws IllegalStateException if it is called in an invalid state
2120 * @throws IllegalArgumentException if the retransmit endpoint is supplied,
2121 * but invalid.
2122 *
2123 * {@hide} pending API council
2124 */
2125 public void setRetransmitEndpoint(InetSocketAddress endpoint)
2126 throws IllegalStateException, IllegalArgumentException
2127 {
2128 String addrString = null;
2129 int port = 0;
2130
2131 if (null != endpoint) {
2132 addrString = endpoint.getAddress().getHostAddress();
2133 port = endpoint.getPort();
2134 }
2135
2136 int ret = native_setRetransmitEndpoint(addrString, port);
2137 if (ret != 0) {
2138 throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
2139 }
2140 }
2141
2142 private native final int native_setRetransmitEndpoint(String addrString, int port);
2143
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 @Override
2145 protected void finalize() { native_finalize(); }
2146
2147 /* Do not change these values without updating their counterparts
2148 * in include/media/mediaplayer.h!
2149 */
2150 private static final int MEDIA_NOP = 0; // interface test message
2151 private static final int MEDIA_PREPARED = 1;
2152 private static final int MEDIA_PLAYBACK_COMPLETE = 2;
2153 private static final int MEDIA_BUFFERING_UPDATE = 3;
2154 private static final int MEDIA_SEEK_COMPLETE = 4;
2155 private static final int MEDIA_SET_VIDEO_SIZE = 5;
Lajos Molnar3d998562013-08-15 17:05:05 -07002156 private static final int MEDIA_STARTED = 6;
2157 private static final int MEDIA_PAUSED = 7;
2158 private static final int MEDIA_STOPPED = 8;
Lajos Molnard58b1222013-09-24 18:04:23 -07002159 private static final int MEDIA_SKIPPED = 9;
Gloria Wang162ee492011-04-11 17:23:27 -07002160 private static final int MEDIA_TIMED_TEXT = 99;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002161 private static final int MEDIA_ERROR = 100;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002162 private static final int MEDIA_INFO = 200;
Chong Zhang83ddaf62013-08-06 09:43:22 -07002163 private static final int MEDIA_SUBTITLE_DATA = 201;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164
Lajos Molnar3d998562013-08-15 17:05:05 -07002165 private TimeProvider mTimeProvider;
2166
2167 /** @hide */
2168 public MediaTimeProvider getMediaTimeProvider() {
Lajos Molnara67a4432013-09-06 06:30:35 -07002169 if (mTimeProvider == null) {
2170 mTimeProvider = new TimeProvider(this);
2171 }
Lajos Molnar3d998562013-08-15 17:05:05 -07002172 return mTimeProvider;
2173 }
2174
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 private class EventHandler extends Handler
2176 {
2177 private MediaPlayer mMediaPlayer;
2178
2179 public EventHandler(MediaPlayer mp, Looper looper) {
2180 super(looper);
2181 mMediaPlayer = mp;
2182 }
2183
2184 @Override
2185 public void handleMessage(Message msg) {
2186 if (mMediaPlayer.mNativeContext == 0) {
2187 Log.w(TAG, "mediaplayer went away with unhandled events");
2188 return;
2189 }
2190 switch(msg.what) {
2191 case MEDIA_PREPARED:
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002192 scanInternalSubtitleTracks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 if (mOnPreparedListener != null)
2194 mOnPreparedListener.onPrepared(mMediaPlayer);
2195 return;
2196
2197 case MEDIA_PLAYBACK_COMPLETE:
2198 if (mOnCompletionListener != null)
2199 mOnCompletionListener.onCompletion(mMediaPlayer);
2200 stayAwake(false);
2201 return;
2202
Lajos Molnar3d998562013-08-15 17:05:05 -07002203 case MEDIA_STOPPED:
2204 if (mTimeProvider != null) {
2205 mTimeProvider.onStopped();
2206 }
2207 break;
2208
2209 case MEDIA_STARTED:
2210 case MEDIA_PAUSED:
2211 if (mTimeProvider != null) {
2212 mTimeProvider.onPaused(msg.what == MEDIA_PAUSED);
2213 }
2214 break;
2215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 case MEDIA_BUFFERING_UPDATE:
2217 if (mOnBufferingUpdateListener != null)
2218 mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
2219 return;
2220
2221 case MEDIA_SEEK_COMPLETE:
Lajos Molnar3d998562013-08-15 17:05:05 -07002222 if (mOnSeekCompleteListener != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
Lajos Molnar3d998562013-08-15 17:05:05 -07002224 }
Lajos Molnard58b1222013-09-24 18:04:23 -07002225 // fall through
2226
2227 case MEDIA_SKIPPED:
Lajos Molnar3d998562013-08-15 17:05:05 -07002228 if (mTimeProvider != null) {
2229 mTimeProvider.onSeekComplete(mMediaPlayer);
2230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 return;
2232
2233 case MEDIA_SET_VIDEO_SIZE:
2234 if (mOnVideoSizeChangedListener != null)
2235 mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
2236 return;
2237
2238 case MEDIA_ERROR:
2239 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
2240 boolean error_was_handled = false;
2241 if (mOnErrorListener != null) {
2242 error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
2243 }
2244 if (mOnCompletionListener != null && ! error_was_handled) {
2245 mOnCompletionListener.onCompletion(mMediaPlayer);
2246 }
2247 stayAwake(false);
2248 return;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002249
2250 case MEDIA_INFO:
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002251 switch (msg.arg1) {
2252 case MEDIA_INFO_VIDEO_TRACK_LAGGING:
Andreas Huber52c78322011-01-11 15:05:28 -08002253 Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002254 break;
2255 case MEDIA_INFO_METADATA_UPDATE:
2256 scanInternalSubtitleTracks();
Lajos Molnar9d480892013-09-11 22:10:01 -07002257 // fall through
2258
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002259 case MEDIA_INFO_EXTERNAL_METADATA_UPDATE:
2260 msg.arg1 = MEDIA_INFO_METADATA_UPDATE;
Lajos Molnar9d480892013-09-11 22:10:01 -07002261 // update default track selection
2262 mSubtitleController.selectDefaultTrack();
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002263 break;
Andreas Huber52c78322011-01-11 15:05:28 -08002264 }
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002265
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002266 if (mOnInfoListener != null) {
2267 mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
2268 }
2269 // No real default action so far.
2270 return;
Gloria Wang162ee492011-04-11 17:23:27 -07002271 case MEDIA_TIMED_TEXT:
Insun Kang41f3f712012-02-16 20:28:27 +09002272 if (mOnTimedTextListener == null)
2273 return;
2274 if (msg.obj == null) {
2275 mOnTimedTextListener.onTimedText(mMediaPlayer, null);
2276 } else {
Insun Kang89020972012-05-01 14:13:19 +09002277 if (msg.obj instanceof Parcel) {
2278 Parcel parcel = (Parcel)msg.obj;
2279 TimedText text = new TimedText(parcel);
Insun Kang333c0992012-07-10 12:47:03 +09002280 parcel.recycle();
Insun Kang41f3f712012-02-16 20:28:27 +09002281 mOnTimedTextListener.onTimedText(mMediaPlayer, text);
Gloria Wangeaa5d8f2011-05-31 16:08:47 -07002282 }
Gloria Wang162ee492011-04-11 17:23:27 -07002283 }
2284 return;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002285
Chong Zhang83ddaf62013-08-06 09:43:22 -07002286 case MEDIA_SUBTITLE_DATA:
2287 if (mOnSubtitleDataListener == null) {
2288 return;
2289 }
2290 if (msg.obj instanceof Parcel) {
2291 Parcel parcel = (Parcel) msg.obj;
2292 SubtitleData data = new SubtitleData(parcel);
2293 parcel.recycle();
2294 mOnSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
2295 }
2296 return;
2297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002298 case MEDIA_NOP: // interface test message - ignore
2299 break;
2300
2301 default:
2302 Log.e(TAG, "Unknown message type " + msg.what);
2303 return;
2304 }
2305 }
2306 }
2307
Insun Kang41f3f712012-02-16 20:28:27 +09002308 /*
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 * Called from native code when an interesting event happens. This method
2310 * just uses the EventHandler system to post the event back to the main app thread.
2311 * We use a weak reference to the original MediaPlayer object so that the native
2312 * code is safe from the object disappearing from underneath it. (This is
2313 * the cookie passed to native_setup().)
2314 */
2315 private static void postEventFromNative(Object mediaplayer_ref,
2316 int what, int arg1, int arg2, Object obj)
2317 {
2318 MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
2319 if (mp == null) {
2320 return;
2321 }
2322
Marco Nelissen84b83202012-02-28 16:07:44 -08002323 if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
2324 // this acquires the wakelock if needed, and sets the client side state
2325 mp.start();
2326 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 if (mp.mEventHandler != null) {
2328 Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
2329 mp.mEventHandler.sendMessage(m);
2330 }
2331 }
2332
2333 /**
2334 * Interface definition for a callback to be invoked when the media
2335 * source is ready for playback.
2336 */
2337 public interface OnPreparedListener
2338 {
2339 /**
2340 * Called when the media file is ready for playback.
Nicolas Catania32f82772009-06-11 16:33:49 -07002341 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002342 * @param mp the MediaPlayer that is ready for playback
2343 */
2344 void onPrepared(MediaPlayer mp);
2345 }
2346
2347 /**
2348 * Register a callback to be invoked when the media source is ready
2349 * for playback.
2350 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002351 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002352 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002353 public void setOnPreparedListener(OnPreparedListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002354 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002355 mOnPreparedListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 }
2357
2358 private OnPreparedListener mOnPreparedListener;
2359
2360 /**
2361 * Interface definition for a callback to be invoked when playback of
2362 * a media source has completed.
2363 */
2364 public interface OnCompletionListener
2365 {
2366 /**
2367 * Called when the end of a media source is reached during playback.
Nicolas Catania32f82772009-06-11 16:33:49 -07002368 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002369 * @param mp the MediaPlayer that reached the end of the file
2370 */
2371 void onCompletion(MediaPlayer mp);
2372 }
2373
2374 /**
2375 * Register a callback to be invoked when the end of a media source
2376 * has been reached during playback.
2377 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002378 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002380 public void setOnCompletionListener(OnCompletionListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002382 mOnCompletionListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002383 }
2384
2385 private OnCompletionListener mOnCompletionListener;
2386
2387 /**
2388 * Interface definition of a callback to be invoked indicating buffering
2389 * status of a media resource being streamed over the network.
2390 */
2391 public interface OnBufferingUpdateListener
2392 {
2393 /**
Jean-Michel Triviea763062011-04-06 10:34:09 -07002394 * Called to update status in buffering a media stream received through
2395 * progressive HTTP download. The received buffering percentage
2396 * indicates how much of the content has been buffered or played.
2397 * For example a buffering update of 80 percent when half the content
2398 * has already been played indicates that the next 30 percent of the
2399 * content to play has been buffered.
Nicolas Catania32f82772009-06-11 16:33:49 -07002400 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 * @param mp the MediaPlayer the update pertains to
Jean-Michel Triviea763062011-04-06 10:34:09 -07002402 * @param percent the percentage (0-100) of the content
2403 * that has been buffered or played thus far
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002404 */
2405 void onBufferingUpdate(MediaPlayer mp, int percent);
2406 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002407
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002408 /**
2409 * Register a callback to be invoked when the status of a network
2410 * stream's buffer has changed.
2411 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002412 * @param listener the callback that will be run.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002414 public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002416 mOnBufferingUpdateListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 }
2418
2419 private OnBufferingUpdateListener mOnBufferingUpdateListener;
Nicolas Catania32f82772009-06-11 16:33:49 -07002420
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002421 /**
2422 * Interface definition of a callback to be invoked indicating
2423 * the completion of a seek operation.
2424 */
2425 public interface OnSeekCompleteListener
2426 {
2427 /**
2428 * Called to indicate the completion of a seek operation.
Nicolas Catania32f82772009-06-11 16:33:49 -07002429 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 * @param mp the MediaPlayer that issued the seek operation
2431 */
2432 public void onSeekComplete(MediaPlayer mp);
2433 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 /**
2436 * Register a callback to be invoked when a seek operation has been
2437 * completed.
Nicolas Catania32f82772009-06-11 16:33:49 -07002438 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002439 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002441 public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002443 mOnSeekCompleteListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 private OnSeekCompleteListener mOnSeekCompleteListener;
2447
2448 /**
2449 * Interface definition of a callback to be invoked when the
2450 * video size is first known or updated
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 */
2452 public interface OnVideoSizeChangedListener
2453 {
2454 /**
2455 * Called to indicate the video size
Nicolas Catania32f82772009-06-11 16:33:49 -07002456 *
James Dongca402cd2011-12-06 17:55:38 -08002457 * The video size (width and height) could be 0 if there was no video,
2458 * no display surface was set, or the value was not determined yet.
2459 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 * @param mp the MediaPlayer associated with this callback
2461 * @param width the width of the video
2462 * @param height the height of the video
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 */
2464 public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
2465 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 /**
2468 * Register a callback to be invoked when the video size is
2469 * known or updated.
Nicolas Catania32f82772009-06-11 16:33:49 -07002470 *
The Android Open Source Project10592532009-03-18 17:39:46 -07002471 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 */
The Android Open Source Project10592532009-03-18 17:39:46 -07002473 public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 {
The Android Open Source Project10592532009-03-18 17:39:46 -07002475 mOnVideoSizeChangedListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
2479
Gloria Wang162ee492011-04-11 17:23:27 -07002480 /**
2481 * Interface definition of a callback to be invoked when a
2482 * timed text is available for display.
Gloria Wang162ee492011-04-11 17:23:27 -07002483 */
2484 public interface OnTimedTextListener
2485 {
2486 /**
Gloria Wangeaa5d8f2011-05-31 16:08:47 -07002487 * Called to indicate an avaliable timed text
Gloria Wang162ee492011-04-11 17:23:27 -07002488 *
2489 * @param mp the MediaPlayer associated with this callback
Gloria Wangeaa5d8f2011-05-31 16:08:47 -07002490 * @param text the timed text sample which contains the text
2491 * needed to be displayed and the display format.
Gloria Wang162ee492011-04-11 17:23:27 -07002492 */
Gloria Wangeaa5d8f2011-05-31 16:08:47 -07002493 public void onTimedText(MediaPlayer mp, TimedText text);
Gloria Wang162ee492011-04-11 17:23:27 -07002494 }
2495
2496 /**
2497 * Register a callback to be invoked when a timed text is available
2498 * for display.
2499 *
2500 * @param listener the callback that will be run
Gloria Wang162ee492011-04-11 17:23:27 -07002501 */
2502 public void setOnTimedTextListener(OnTimedTextListener listener)
2503 {
2504 mOnTimedTextListener = listener;
2505 }
2506
2507 private OnTimedTextListener mOnTimedTextListener;
2508
Chong Zhang83ddaf62013-08-06 09:43:22 -07002509 /**
2510 * Interface definition of a callback to be invoked when a
2511 * track has data available.
2512 *
2513 * @hide
2514 */
2515 public interface OnSubtitleDataListener
2516 {
2517 public void onSubtitleData(MediaPlayer mp, SubtitleData data);
2518 }
2519
2520 /**
2521 * Register a callback to be invoked when a track has data available.
2522 *
2523 * @param listener the callback that will be run
2524 *
2525 * @hide
2526 */
2527 public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
2528 {
2529 mOnSubtitleDataListener = listener;
2530 }
2531
2532 private OnSubtitleDataListener mOnSubtitleDataListener;
Gloria Wang162ee492011-04-11 17:23:27 -07002533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 /* Do not change these values without updating their counterparts
2535 * in include/media/mediaplayer.h!
2536 */
2537 /** Unspecified media player error.
2538 * @see android.media.MediaPlayer.OnErrorListener
2539 */
2540 public static final int MEDIA_ERROR_UNKNOWN = 1;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002541
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002542 /** Media server died. In this case, the application must release the
Nicolas Catania32f82772009-06-11 16:33:49 -07002543 * MediaPlayer object and instantiate a new one.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002544 * @see android.media.MediaPlayer.OnErrorListener
2545 */
2546 public static final int MEDIA_ERROR_SERVER_DIED = 100;
Nicolas Catania32f82772009-06-11 16:33:49 -07002547
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002548 /** The video is streamed and its container is not valid for progressive
2549 * playback i.e the video's index (e.g moov atom) is not at the start of the
2550 * file.
Niko Catania4a0029f2009-03-24 19:51:09 -07002551 * @see android.media.MediaPlayer.OnErrorListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002552 */
2553 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554
James Dong2adac492012-08-26 13:00:30 -07002555 /** File or network related operation errors. */
2556 public static final int MEDIA_ERROR_IO = -1004;
2557 /** Bitstream is not conforming to the related coding standard or file spec. */
2558 public static final int MEDIA_ERROR_MALFORMED = -1007;
2559 /** Bitstream is conforming to the related coding standard or file spec, but
2560 * the media framework does not support the feature. */
2561 public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
2562 /** Some operation takes too long to complete, usually more than 3-5 seconds. */
2563 public static final int MEDIA_ERROR_TIMED_OUT = -110;
2564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 /**
2566 * Interface definition of a callback to be invoked when there
2567 * has been an error during an asynchronous operation (other errors
2568 * will throw exceptions at method call time).
2569 */
2570 public interface OnErrorListener
2571 {
2572 /**
2573 * Called to indicate an error.
Nicolas Catania32f82772009-06-11 16:33:49 -07002574 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 * @param mp the MediaPlayer the error pertains to
2576 * @param what the type of error that has occurred:
2577 * <ul>
2578 * <li>{@link #MEDIA_ERROR_UNKNOWN}
2579 * <li>{@link #MEDIA_ERROR_SERVER_DIED}
2580 * </ul>
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002581 * @param extra an extra code, specific to the error. Typically
James Dongb10ec1f2012-07-30 15:43:14 -07002582 * implementation dependent.
James Dong2adac492012-08-26 13:00:30 -07002583 * <ul>
2584 * <li>{@link #MEDIA_ERROR_IO}
2585 * <li>{@link #MEDIA_ERROR_MALFORMED}
2586 * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
2587 * <li>{@link #MEDIA_ERROR_TIMED_OUT}
2588 * </ul>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589 * @return True if the method handled the error, false if it didn't.
2590 * Returning false, or not having an OnErrorListener at all, will
2591 * cause the OnCompletionListener to be called.
2592 */
2593 boolean onError(MediaPlayer mp, int what, int extra);
2594 }
Nicolas Catania32f82772009-06-11 16:33:49 -07002595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002596 /**
2597 * Register a callback to be invoked when an error has happened
2598 * during an asynchronous operation.
Nicolas Catania32f82772009-06-11 16:33:49 -07002599 *
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002600 * @param listener the callback that will be run
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 */
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002602 public void setOnErrorListener(OnErrorListener listener)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002603 {
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002604 mOnErrorListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 }
2606
2607 private OnErrorListener mOnErrorListener;
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002608
2609
2610 /* Do not change these values without updating their counterparts
2611 * in include/media/mediaplayer.h!
2612 */
2613 /** Unspecified media player info.
2614 * @see android.media.MediaPlayer.OnInfoListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002615 */
2616 public static final int MEDIA_INFO_UNKNOWN = 1;
2617
Marco Nelissen84b83202012-02-28 16:07:44 -08002618 /** The player was started because it was used as the next player for another
2619 * player, which just completed playback.
2620 * @see android.media.MediaPlayer.OnInfoListener
2621 * @hide
2622 */
2623 public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
2624
James Dong15a89e62012-07-23 15:00:37 -07002625 /** The player just pushed the very first video frame for rendering.
2626 * @see android.media.MediaPlayer.OnInfoListener
2627 */
2628 public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
2629
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002630 /** The video is too complex for the decoder: it can't decode frames fast
2631 * enough. Possibly only the audio plays fine at this stage.
2632 * @see android.media.MediaPlayer.OnInfoListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002633 */
2634 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
2635
Andreas Huber4d61f602010-06-10 11:17:50 -07002636 /** MediaPlayer is temporarily pausing playback internally in order to
2637 * buffer more data.
James Dongc36b3c62011-03-29 12:16:59 -07002638 * @see android.media.MediaPlayer.OnInfoListener
Andreas Huber4d61f602010-06-10 11:17:50 -07002639 */
2640 public static final int MEDIA_INFO_BUFFERING_START = 701;
2641
2642 /** MediaPlayer is resuming playback after filling buffers.
James Dongc36b3c62011-03-29 12:16:59 -07002643 * @see android.media.MediaPlayer.OnInfoListener
Andreas Huber4d61f602010-06-10 11:17:50 -07002644 */
2645 public static final int MEDIA_INFO_BUFFERING_END = 702;
2646
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002647 /** Bad interleaving means that a media has been improperly interleaved or
2648 * not interleaved at all, e.g has all the video samples first then all the
2649 * audio ones. Video is playing but a lot of disk seeks may be happening.
2650 * @see android.media.MediaPlayer.OnInfoListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002651 */
2652 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
2653
2654 /** The media cannot be seeked (e.g live stream)
2655 * @see android.media.MediaPlayer.OnInfoListener
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002656 */
2657 public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
2658
Nicolas Catania9193e082009-07-06 12:43:36 -07002659 /** A new set of metadata is available.
2660 * @see android.media.MediaPlayer.OnInfoListener
2661 */
2662 public static final int MEDIA_INFO_METADATA_UPDATE = 802;
2663
Lajos Molnar484ff7a92013-08-15 11:37:47 -07002664 /** A new set of external-only metadata is available. Used by
2665 * JAVA framework to avoid triggering track scanning.
2666 * @hide
2667 */
2668 public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
2669
Insun Kang41f3f712012-02-16 20:28:27 +09002670 /** Failed to handle timed text track properly.
2671 * @see android.media.MediaPlayer.OnInfoListener
2672 *
2673 * {@hide}
2674 */
2675 public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
2676
Lajos Molnaraf3098242013-08-15 20:56:53 -07002677 /** Subtitle track was not supported by the media framework.
2678 * @see android.media.MediaPlayer.OnInfoListener
2679 */
2680 public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
2681
2682 /** Reading the subtitle track takes too long.
2683 * @see android.media.MediaPlayer.OnInfoListener
2684 */
2685 public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
2686
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002687 /**
2688 * Interface definition of a callback to be invoked to communicate some
2689 * info and/or warning about the media or its playback.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002690 */
2691 public interface OnInfoListener
2692 {
2693 /**
2694 * Called to indicate an info or a warning.
Nicolas Catania32f82772009-06-11 16:33:49 -07002695 *
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002696 * @param mp the MediaPlayer the info pertains to.
2697 * @param what the type of info or warning.
2698 * <ul>
2699 * <li>{@link #MEDIA_INFO_UNKNOWN}
2700 * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
James Dong15a89e62012-07-23 15:00:37 -07002701 * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
James Dongc36b3c62011-03-29 12:16:59 -07002702 * <li>{@link #MEDIA_INFO_BUFFERING_START}
2703 * <li>{@link #MEDIA_INFO_BUFFERING_END}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002704 * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
2705 * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
Nicolas Catania9193e082009-07-06 12:43:36 -07002706 * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
Lajos Molnaraf3098242013-08-15 20:56:53 -07002707 * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE}
2708 * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT}
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002709 * </ul>
2710 * @param extra an extra code, specific to the info. Typically
James Dongb10ec1f2012-07-30 15:43:14 -07002711 * implementation dependent.
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002712 * @return True if the method handled the info, false if it didn't.
2713 * Returning false, or not having an OnErrorListener at all, will
2714 * cause the info to be discarded.
2715 */
2716 boolean onInfo(MediaPlayer mp, int what, int extra);
2717 }
2718
2719 /**
2720 * Register a callback to be invoked when an info/warning is available.
Nicolas Catania32f82772009-06-11 16:33:49 -07002721 *
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002722 * @param listener the callback that will be run
The Android Open Source Projectc39a6e02009-03-11 12:11:56 -07002723 */
2724 public void setOnInfoListener(OnInfoListener listener)
2725 {
2726 mOnInfoListener = listener;
2727 }
2728
2729 private OnInfoListener mOnInfoListener;
Marco Nelissenc39d2e32009-09-20 10:42:13 -07002730
James Dong454014e2012-04-28 16:03:55 -07002731 /*
2732 * Test whether a given video scaling mode is supported.
2733 */
2734 private boolean isVideoScalingModeSupported(int mode) {
2735 return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
2736 mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
2737 }
Andreas Huberd5f9fa52013-05-28 14:39:39 -07002738
Lajos Molnar3d998562013-08-15 17:05:05 -07002739 /** @hide */
2740 static class TimeProvider implements MediaPlayer.OnSeekCompleteListener,
2741 MediaTimeProvider {
2742 private static final String TAG = "MTP";
2743 private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L;
2744 private static final long MAX_EARLY_CALLBACK_US = 1000;
2745 private static final long TIME_ADJUSTMENT_RATE = 2; /* meaning 1/2 */
2746 private long mLastTimeUs = 0;
2747 private MediaPlayer mPlayer;
2748 private boolean mPaused = true;
2749 private boolean mStopped = true;
2750 private long mLastReportedTime;
2751 private long mTimeAdjustment;
2752 // since we are expecting only a handful listeners per stream, there is
2753 // no need for log(N) search performance
2754 private MediaTimeProvider.OnMediaTimeListener mListeners[];
2755 private long mTimes[];
2756 private long mLastNanoTime;
2757 private Handler mEventHandler;
2758 private boolean mRefresh = false;
2759 private boolean mPausing = false;
Lajos Molnard58b1222013-09-24 18:04:23 -07002760 private boolean mSeeking = false;
Lajos Molnar3d998562013-08-15 17:05:05 -07002761 private static final int NOTIFY = 1;
2762 private static final int NOTIFY_TIME = 0;
2763 private static final int REFRESH_AND_NOTIFY_TIME = 1;
2764 private static final int NOTIFY_STOP = 2;
2765 private static final int NOTIFY_SEEK = 3;
Lajos Molnara67a4432013-09-06 06:30:35 -07002766 private HandlerThread mHandlerThread;
Lajos Molnar3d998562013-08-15 17:05:05 -07002767
2768 /** @hide */
2769 public boolean DEBUG = false;
2770
2771 public TimeProvider(MediaPlayer mp) {
2772 mPlayer = mp;
2773 try {
2774 getCurrentTimeUs(true, false);
2775 } catch (IllegalStateException e) {
2776 // we assume starting position
2777 mRefresh = true;
2778 }
Lajos Molnara67a4432013-09-06 06:30:35 -07002779
2780 Looper looper;
2781 if ((looper = Looper.myLooper()) == null &&
2782 (looper = Looper.getMainLooper()) == null) {
2783 // Create our own looper here in case MP was created without one
2784 mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread",
2785 Process.THREAD_PRIORITY_FOREGROUND);
2786 mHandlerThread.start();
2787 looper = mHandlerThread.getLooper();
2788 }
2789 mEventHandler = new EventHandler(looper);
2790
Lajos Molnar3d998562013-08-15 17:05:05 -07002791 mListeners = new MediaTimeProvider.OnMediaTimeListener[0];
2792 mTimes = new long[0];
2793 mLastTimeUs = 0;
2794 mTimeAdjustment = 0;
2795 }
2796
2797 private void scheduleNotification(int type, long delayUs) {
Lajos Molnard58b1222013-09-24 18:04:23 -07002798 // ignore time notifications until seek is handled
2799 if (mSeeking &&
2800 (type == NOTIFY_TIME || type == REFRESH_AND_NOTIFY_TIME)) {
2801 return;
2802 }
2803
Lajos Molnar3d998562013-08-15 17:05:05 -07002804 if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs);
2805 mEventHandler.removeMessages(NOTIFY);
2806 Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0);
2807 mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000));
2808 }
2809
2810 /** @hide */
2811 public void close() {
2812 mEventHandler.removeMessages(NOTIFY);
Lajos Molnara67a4432013-09-06 06:30:35 -07002813 if (mHandlerThread != null) {
2814 mHandlerThread.quitSafely();
2815 mHandlerThread = null;
2816 }
2817 }
2818
2819 /** @hide */
2820 protected void finalize() {
2821 if (mHandlerThread != null) {
2822 mHandlerThread.quitSafely();
2823 }
Lajos Molnar3d998562013-08-15 17:05:05 -07002824 }
2825
2826 /** @hide */
2827 public void onPaused(boolean paused) {
2828 synchronized(this) {
2829 if (DEBUG) Log.d(TAG, "onPaused: " + paused);
2830 if (mStopped) { // handle as seek if we were stopped
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07002831 mStopped = false;
2832 mSeeking = true;
Lajos Molnar3d998562013-08-15 17:05:05 -07002833 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2834 } else {
2835 mPausing = paused; // special handling if player disappeared
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07002836 mSeeking = false;
Lajos Molnar3d998562013-08-15 17:05:05 -07002837 scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
2838 }
2839 }
2840 }
2841
2842 /** @hide */
2843 public void onStopped() {
2844 synchronized(this) {
2845 if (DEBUG) Log.d(TAG, "onStopped");
2846 mPaused = true;
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07002847 mStopped = true;
2848 mSeeking = false;
Lajos Molnar3d998562013-08-15 17:05:05 -07002849 scheduleNotification(NOTIFY_STOP, 0 /* delay */);
2850 }
2851 }
2852
2853 /** @hide */
2854 @Override
2855 public void onSeekComplete(MediaPlayer mp) {
2856 synchronized(this) {
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07002857 mStopped = false;
2858 mSeeking = true;
Lajos Molnar3d998562013-08-15 17:05:05 -07002859 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2860 }
2861 }
2862
2863 /** @hide */
2864 public void onNewPlayer() {
2865 if (mRefresh) {
2866 synchronized(this) {
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07002867 mStopped = false;
2868 mSeeking = true;
Lajos Molnar3d998562013-08-15 17:05:05 -07002869 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2870 }
2871 }
2872 }
2873
2874 private synchronized void notifySeek() {
Lajos Molnard58b1222013-09-24 18:04:23 -07002875 mSeeking = false;
Lajos Molnar3d998562013-08-15 17:05:05 -07002876 try {
2877 long timeUs = getCurrentTimeUs(true, false);
2878 if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs);
2879
2880 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
2881 if (listener == null) {
2882 break;
2883 }
2884 listener.onSeek(timeUs);
2885 }
2886 } catch (IllegalStateException e) {
2887 // we should not be there, but at least signal pause
2888 if (DEBUG) Log.d(TAG, "onSeekComplete but no player");
2889 mPausing = true; // special handling if player disappeared
2890 notifyTimedEvent(false /* refreshTime */);
2891 }
2892 }
2893
2894 private synchronized void notifyStop() {
2895 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
2896 if (listener == null) {
2897 break;
2898 }
2899 listener.onStop();
2900 }
2901 }
2902
2903 private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) {
2904 int i = 0;
2905 for (; i < mListeners.length; i++) {
2906 if (mListeners[i] == listener || mListeners[i] == null) {
2907 break;
2908 }
2909 }
2910
2911 // new listener
2912 if (i >= mListeners.length) {
2913 MediaTimeProvider.OnMediaTimeListener[] newListeners =
2914 new MediaTimeProvider.OnMediaTimeListener[i + 1];
2915 long[] newTimes = new long[i + 1];
2916 System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length);
2917 System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length);
2918 mListeners = newListeners;
2919 mTimes = newTimes;
2920 }
2921
2922 if (mListeners[i] == null) {
2923 mListeners[i] = listener;
2924 mTimes[i] = MediaTimeProvider.NO_TIME;
2925 }
2926 return i;
2927 }
2928
2929 public void notifyAt(
2930 long timeUs, MediaTimeProvider.OnMediaTimeListener listener) {
2931 synchronized(this) {
2932 if (DEBUG) Log.d(TAG, "notifyAt " + timeUs);
2933 mTimes[registerListener(listener)] = timeUs;
2934 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2935 }
2936 }
2937
2938 public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) {
2939 synchronized(this) {
2940 if (DEBUG) Log.d(TAG, "scheduleUpdate");
2941 int i = registerListener(listener);
2942
2943 if (mStopped) {
2944 scheduleNotification(NOTIFY_STOP, 0 /* delay */);
2945 } else {
2946 mTimes[i] = 0;
2947 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2948 }
2949 }
2950 }
2951
2952 public void cancelNotifications(
2953 MediaTimeProvider.OnMediaTimeListener listener) {
2954 synchronized(this) {
2955 int i = 0;
2956 for (; i < mListeners.length; i++) {
2957 if (mListeners[i] == listener) {
2958 System.arraycopy(mListeners, i + 1,
2959 mListeners, i, mListeners.length - i - 1);
2960 System.arraycopy(mTimes, i + 1,
2961 mTimes, i, mTimes.length - i - 1);
2962 mListeners[mListeners.length - 1] = null;
2963 mTimes[mTimes.length - 1] = NO_TIME;
2964 break;
2965 } else if (mListeners[i] == null) {
2966 break;
2967 }
2968 }
2969
2970 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2971 }
2972 }
2973
2974 private synchronized void notifyTimedEvent(boolean refreshTime) {
2975 // figure out next callback
2976 long nowUs;
2977 try {
2978 nowUs = getCurrentTimeUs(refreshTime, true);
2979 } catch (IllegalStateException e) {
2980 // assume we paused until new player arrives
2981 mRefresh = true;
2982 mPausing = true; // this ensures that call succeeds
2983 nowUs = getCurrentTimeUs(refreshTime, true);
2984 }
2985 long nextTimeUs = nowUs;
2986
Lajos Molnard58b1222013-09-24 18:04:23 -07002987 if (mSeeking) {
2988 // skip timed-event notifications until seek is complete
2989 return;
2990 }
2991
Lajos Molnar3d998562013-08-15 17:05:05 -07002992 if (DEBUG) {
2993 StringBuilder sb = new StringBuilder();
2994 sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ")
2995 .append(nowUs).append(") from {");
2996 boolean first = true;
2997 for (long time: mTimes) {
2998 if (time == NO_TIME) {
2999 continue;
3000 }
3001 if (!first) sb.append(", ");
3002 sb.append(time);
3003 first = false;
3004 }
3005 sb.append("}");
3006 Log.d(TAG, sb.toString());
3007 }
3008
3009 Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners =
3010 new Vector<MediaTimeProvider.OnMediaTimeListener>();
3011 for (int ix = 0; ix < mTimes.length; ix++) {
3012 if (mListeners[ix] == null) {
3013 break;
3014 }
3015 if (mTimes[ix] <= NO_TIME) {
3016 // ignore, unless we were stopped
3017 } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) {
3018 activatedListeners.add(mListeners[ix]);
3019 if (DEBUG) Log.d(TAG, "removed");
3020 mTimes[ix] = NO_TIME;
3021 } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) {
3022 nextTimeUs = mTimes[ix];
3023 }
3024 }
3025
3026 if (nextTimeUs > nowUs && !mPaused) {
3027 // schedule callback at nextTimeUs
3028 if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs);
3029 scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs);
3030 } else {
3031 mEventHandler.removeMessages(NOTIFY);
3032 // no more callbacks
3033 }
3034
3035 for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) {
3036 listener.onTimedEvent(nowUs);
3037 }
3038 }
3039
3040 private long getEstimatedTime(long nanoTime, boolean monotonic) {
3041 if (mPaused) {
3042 mLastReportedTime = mLastTimeUs + mTimeAdjustment;
3043 } else {
3044 long timeSinceRead = (nanoTime - mLastNanoTime) / 1000;
3045 mLastReportedTime = mLastTimeUs + timeSinceRead;
3046 if (mTimeAdjustment > 0) {
3047 long adjustment =
3048 mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE;
3049 if (adjustment <= 0) {
3050 mTimeAdjustment = 0;
3051 } else {
3052 mLastReportedTime += adjustment;
3053 }
3054 }
3055 }
3056 return mLastReportedTime;
3057 }
3058
3059 public long getCurrentTimeUs(boolean refreshTime, boolean monotonic)
3060 throws IllegalStateException {
3061 synchronized (this) {
3062 // we always refresh the time when the paused-state changes, because
3063 // we expect to have received the pause-change event delayed.
3064 if (mPaused && !refreshTime) {
3065 return mLastReportedTime;
3066 }
3067
3068 long nanoTime = System.nanoTime();
3069 if (refreshTime ||
3070 nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) {
3071 try {
3072 mLastTimeUs = mPlayer.getCurrentPosition() * 1000;
3073 mPaused = !mPlayer.isPlaying();
3074 if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs);
3075 } catch (IllegalStateException e) {
3076 if (mPausing) {
3077 // if we were pausing, get last estimated timestamp
3078 mPausing = false;
3079 getEstimatedTime(nanoTime, monotonic);
3080 mPaused = true;
3081 if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime);
3082 return mLastReportedTime;
3083 }
3084 // TODO get time when prepared
3085 throw e;
3086 }
3087 mLastNanoTime = nanoTime;
3088 if (monotonic && mLastTimeUs < mLastReportedTime) {
3089 /* have to adjust time */
3090 mTimeAdjustment = mLastReportedTime - mLastTimeUs;
Lajos Molnard58b1222013-09-24 18:04:23 -07003091 if (mTimeAdjustment > 1000000) {
3092 // schedule seeked event if time jumped significantly
3093 // TODO: do this properly by introducing an exception
Lajos Molnar4de8e7c2013-10-28 07:16:41 -07003094 mStopped = false;
3095 mSeeking = true;
Lajos Molnard58b1222013-09-24 18:04:23 -07003096 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
3097 }
Lajos Molnar3d998562013-08-15 17:05:05 -07003098 } else {
3099 mTimeAdjustment = 0;
3100 }
3101 }
3102
3103 return getEstimatedTime(nanoTime, monotonic);
3104 }
3105 }
3106
3107 private class EventHandler extends Handler {
Lajos Molnara67a4432013-09-06 06:30:35 -07003108 public EventHandler(Looper looper) {
3109 super(looper);
3110 }
3111
Lajos Molnar3d998562013-08-15 17:05:05 -07003112 @Override
3113 public void handleMessage(Message msg) {
3114 if (msg.what == NOTIFY) {
3115 switch (msg.arg1) {
3116 case NOTIFY_TIME:
3117 notifyTimedEvent(false /* refreshTime */);
3118 break;
3119 case REFRESH_AND_NOTIFY_TIME:
3120 notifyTimedEvent(true /* refreshTime */);
3121 break;
3122 case NOTIFY_STOP:
3123 notifyStop();
3124 break;
3125 case NOTIFY_SEEK:
3126 notifySeek();
3127 break;
3128 }
3129 }
3130 }
3131 }
Lajos Molnar3d998562013-08-15 17:05:05 -07003132 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133}