MediaPlayer.java revision 1c1d1e7ed7ed2673b22642c6701659146ceaa602
1/*
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
19import android.content.ContentResolver;
20import android.content.Context;
21import android.content.res.AssetFileDescriptor;
22import android.net.Uri;
23import android.os.Handler;
24import android.os.Looper;
25import android.os.Message;
26import android.os.Parcel;
27import android.os.ParcelFileDescriptor;
28import android.os.PowerManager;
29import android.util.Log;
30import android.view.Surface;
31import android.view.SurfaceHolder;
32import android.graphics.Bitmap;
33import android.graphics.SurfaceTexture;
34import android.media.AudioManager;
35
36import java.io.FileDescriptor;
37import java.io.IOException;
38import java.net.InetSocketAddress;
39import java.util.Map;
40import java.util.Set;
41import java.lang.ref.WeakReference;
42
43/**
44 * MediaPlayer class can be used to control playback
45 * of audio/video files and streams. An example on how to use the methods in
46 * this class can be found in {@link android.widget.VideoView}.
47 *
48 * <p>Topics covered here are:
49 * <ol>
50 * <li><a href="#StateDiagram">State Diagram</a>
51 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
52 * <li><a href="#Permissions">Permissions</a>
53 * <li><a href="#Callbacks">Register informational and error callbacks</a>
54 * </ol>
55 *
56 * <div class="special reference">
57 * <h3>Developer Guides</h3>
58 * <p>For more information about how to use MediaPlayer, read the
59 * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p>
60 * </div>
61 *
62 * <a name="StateDiagram"></a>
63 * <h3>State Diagram</h3>
64 *
65 * <p>Playback control of audio/video files and streams is managed as a state
66 * machine. The following diagram shows the life cycle and the states of a
67 * MediaPlayer object driven by the supported playback control operations.
68 * The ovals represent the states a MediaPlayer object may reside
69 * in. The arcs represent the playback control operations that drive the object
70 * state transition. There are two types of arcs. The arcs with a single arrow
71 * head represent synchronous method calls, while those with
72 * a double arrow head represent asynchronous method calls.</p>
73 *
74 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
75 *         alt="MediaPlayer State diagram"
76 *         border="0" /></p>
77 *
78 * <p>From this state diagram, one can see that a MediaPlayer object has the
79 *    following states:</p>
80 * <ul>
81 *     <li>When a MediaPlayer object is just created using <code>new</code> or
82 *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
83 *         {@link #release()} is called, it is in the <em>End</em> state. Between these
84 *         two states is the life cycle of the MediaPlayer object.
85 *         <ul>
86 *         <li>There is a subtle but important difference between a newly constructed
87 *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
88 *         is called. It is a programming error to invoke methods such
89 *         as {@link #getCurrentPosition()},
90 *         {@link #getDuration()}, {@link #getVideoHeight()},
91 *         {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
92 *         {@link #setLooping(boolean)},
93 *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
94 *         {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
95 *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
96 *         methods is called right after a MediaPlayer object is constructed,
97 *         the user supplied callback method OnErrorListener.onError() won't be
98 *         called by the internal player engine and the object state remains
99 *         unchanged; but if these methods are called right after {@link #reset()},
100 *         the user supplied callback method OnErrorListener.onError() will be
101 *         invoked by the internal player engine and the object will be
102 *         transfered to the <em>Error</em> state. </li>
103 *         <li>It is also recommended that once
104 *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
105 *         so that resources used by the internal player engine associated with the
106 *         MediaPlayer object can be released immediately. Resource may include
107 *         singleton resources such as hardware acceleration components and
108 *         failure to call {@link #release()} may cause subsequent instances of
109 *         MediaPlayer objects to fallback to software implementations or fail
110 *         altogether. Once the MediaPlayer
111 *         object is in the <em>End</em> state, it can no longer be used and
112 *         there is no way to bring it back to any other state. </li>
113 *         <li>Furthermore,
114 *         the MediaPlayer objects created using <code>new</code> is in the
115 *         <em>Idle</em> state, while those created with one
116 *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
117 *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
118 *         state if the creation using <code>create</code> method is successful.
119 *         </li>
120 *         </ul>
121 *         </li>
122 *     <li>In general, some playback control operation may fail due to various
123 *         reasons, such as unsupported audio/video format, poorly interleaved
124 *         audio/video, resolution too high, streaming timeout, and the like.
125 *         Thus, error reporting and recovery is an important concern under
126 *         these circumstances. Sometimes, due to programming errors, invoking a playback
127 *         control operation in an invalid state may also occur. Under all these
128 *         error conditions, the internal player engine invokes a user supplied
129 *         OnErrorListener.onError() method if an OnErrorListener has been
130 *         registered beforehand via
131 *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
132 *         <ul>
133 *         <li>It is important to note that once an error occurs, the
134 *         MediaPlayer object enters the <em>Error</em> state (except as noted
135 *         above), even if an error listener has not been registered by the application.</li>
136 *         <li>In order to reuse a MediaPlayer object that is in the <em>
137 *         Error</em> state and recover from the error,
138 *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
139 *         state.</li>
140 *         <li>It is good programming practice to have your application
141 *         register a OnErrorListener to look out for error notifications from
142 *         the internal player engine.</li>
143 *         <li>IllegalStateException is
144 *         thrown to prevent programming errors such as calling {@link #prepare()},
145 *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
146 *         </code> methods in an invalid state. </li>
147 *         </ul>
148 *         </li>
149 *     <li>Calling
150 *         {@link #setDataSource(FileDescriptor)}, or
151 *         {@link #setDataSource(String)}, or
152 *         {@link #setDataSource(Context, Uri)}, or
153 *         {@link #setDataSource(FileDescriptor, long, long)} transfers a
154 *         MediaPlayer object in the <em>Idle</em> state to the
155 *         <em>Initialized</em> state.
156 *         <ul>
157 *         <li>An IllegalStateException is thrown if
158 *         setDataSource() is called in any other state.</li>
159 *         <li>It is good programming
160 *         practice to always look out for <code>IllegalArgumentException</code>
161 *         and <code>IOException</code> that may be thrown from the overloaded
162 *         <code>setDataSource</code> methods.</li>
163 *         </ul>
164 *         </li>
165 *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
166 *         before playback can be started.
167 *         <ul>
168 *         <li>There are two ways (synchronous vs.
169 *         asynchronous) that the <em>Prepared</em> state can be reached:
170 *         either a call to {@link #prepare()} (synchronous) which
171 *         transfers the object to the <em>Prepared</em> state once the method call
172 *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
173 *         first transfers the object to the <em>Preparing</em> state after the
174 *         call returns (which occurs almost right way) while the internal
175 *         player engine continues working on the rest of preparation work
176 *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
177 *         the internal player engine then calls a user supplied callback method,
178 *         onPrepared() of the OnPreparedListener interface, if an
179 *         OnPreparedListener is registered beforehand via {@link
180 *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
181 *         <li>It is important to note that
182 *         the <em>Preparing</em> state is a transient state, and the behavior
183 *         of calling any method with side effect while a MediaPlayer object is
184 *         in the <em>Preparing</em> state is undefined.</li>
185 *         <li>An IllegalStateException is
186 *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
187 *         any other state.</li>
188 *         <li>While in the <em>Prepared</em> state, properties
189 *         such as audio/sound volume, screenOnWhilePlaying, looping can be
190 *         adjusted by invoking the corresponding set methods.</li>
191 *         </ul>
192 *         </li>
193 *     <li>To start the playback, {@link #start()} must be called. After
194 *         {@link #start()} returns successfully, the MediaPlayer object is in the
195 *         <em>Started</em> state. {@link #isPlaying()} can be called to test
196 *         whether the MediaPlayer object is in the <em>Started</em> state.
197 *         <ul>
198 *         <li>While in the <em>Started</em> state, the internal player engine calls
199 *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
200 *         method if a OnBufferingUpdateListener has been registered beforehand
201 *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
202 *         This callback allows applications to keep track of the buffering status
203 *         while streaming audio/video.</li>
204 *         <li>Calling {@link #start()} has not effect
205 *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
206 *         </ul>
207 *         </li>
208 *     <li>Playback can be paused and stopped, and the current playback position
209 *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
210 *         {@link #pause()} returns, the MediaPlayer object enters the
211 *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
212 *         state to the <em>Paused</em> state and vice versa happens
213 *         asynchronously in the player engine. It may take some time before
214 *         the state is updated in calls to {@link #isPlaying()}, and it can be
215 *         a number of seconds in the case of streamed content.
216 *         <ul>
217 *         <li>Calling {@link #start()} to resume playback for a paused
218 *         MediaPlayer object, and the resumed playback
219 *         position is the same as where it was paused. When the call to
220 *         {@link #start()} returns, the paused MediaPlayer object goes back to
221 *         the <em>Started</em> state.</li>
222 *         <li>Calling {@link #pause()} has no effect on
223 *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
224 *         </ul>
225 *         </li>
226 *     <li>Calling  {@link #stop()} stops playback and causes a
227 *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
228 *         </em> or <em>PlaybackCompleted</em> state to enter the
229 *         <em>Stopped</em> state.
230 *         <ul>
231 *         <li>Once in the <em>Stopped</em> state, playback cannot be started
232 *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
233 *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
234 *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
235 *         object that is already in the <em>Stopped</em> state.</li>
236 *         </ul>
237 *         </li>
238 *     <li>The playback position can be adjusted with a call to
239 *         {@link #seekTo(int)}.
240 *         <ul>
241 *         <li>Although the asynchronuous {@link #seekTo(int)}
242 *         call returns right way, the actual seek operation may take a while to
243 *         finish, especially for audio/video being streamed. When the actual
244 *         seek operation completes, the internal player engine calls a user
245 *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
246 *         has been registered beforehand via
247 *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
248 *         <li>Please
249 *         note that {@link #seekTo(int)} can also be called in the other states,
250 *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
251 *         </em> state.</li>
252 *         <li>Furthermore, the actual current playback position
253 *         can be retrieved with a call to {@link #getCurrentPosition()}, which
254 *         is helpful for applications such as a Music player that need to keep
255 *         track of the playback progress.</li>
256 *         </ul>
257 *         </li>
258 *     <li>When the playback reaches the end of stream, the playback completes.
259 *         <ul>
260 *         <li>If the looping mode was being set to <var>true</var>with
261 *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
262 *         the <em>Started</em> state.</li>
263 *         <li>If the looping mode was set to <var>false
264 *         </var>, the player engine calls a user supplied callback method,
265 *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
266 *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
267 *         The invoke of the callback signals that the object is now in the <em>
268 *         PlaybackCompleted</em> state.</li>
269 *         <li>While in the <em>PlaybackCompleted</em>
270 *         state, calling {@link #start()} can restart the playback from the
271 *         beginning of the audio/video source.</li>
272 * </ul>
273 *
274 *
275 * <a name="Valid_and_Invalid_States"></a>
276 * <h3>Valid and invalid states</h3>
277 *
278 * <table border="0" cellspacing="0" cellpadding="0">
279 * <tr><td>Method Name </p></td>
280 *     <td>Valid Sates </p></td>
281 *     <td>Invalid States </p></td>
282 *     <td>Comments </p></td></tr>
283 * <tr><td>attachAuxEffect </p></td>
284 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
285 *     <td>{Idle, Error} </p></td>
286 *     <td>This method must be called after setDataSource.
287 *     Calling it does not change the object state. </p></td></tr>
288 * <tr><td>getAudioSessionId </p></td>
289 *     <td>any </p></td>
290 *     <td>{} </p></td>
291 *     <td>This method can be called in any state and calling it does not change
292 *         the object state. </p></td></tr>
293 * <tr><td>getCurrentPosition </p></td>
294 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
295 *         PlaybackCompleted} </p></td>
296 *     <td>{Error}</p></td>
297 *     <td>Successful invoke of this method in a valid state does not change the
298 *         state. Calling this method in an invalid state transfers the object
299 *         to the <em>Error</em> state. </p></td></tr>
300 * <tr><td>getDuration </p></td>
301 *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
302 *     <td>{Idle, Initialized, Error} </p></td>
303 *     <td>Successful invoke of this method in a valid state does not change the
304 *         state. Calling this method in an invalid state transfers the object
305 *         to the <em>Error</em> state. </p></td></tr>
306 * <tr><td>getVideoHeight </p></td>
307 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
308 *         PlaybackCompleted}</p></td>
309 *     <td>{Error}</p></td>
310 *     <td>Successful invoke of this method in a valid state does not change the
311 *         state. Calling this method in an invalid state transfers the object
312 *         to the <em>Error</em> state.  </p></td></tr>
313 * <tr><td>getVideoWidth </p></td>
314 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
315 *         PlaybackCompleted}</p></td>
316 *     <td>{Error}</p></td>
317 *     <td>Successful invoke of this method in a valid state does not change
318 *         the state. Calling this method in an invalid state transfers the
319 *         object to the <em>Error</em> state. </p></td></tr>
320 * <tr><td>isPlaying </p></td>
321 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
322 *          PlaybackCompleted}</p></td>
323 *     <td>{Error}</p></td>
324 *     <td>Successful invoke of this method in a valid state does not change
325 *         the state. Calling this method in an invalid state transfers the
326 *         object to the <em>Error</em> state. </p></td></tr>
327 * <tr><td>pause </p></td>
328 *     <td>{Started, Paused}</p></td>
329 *     <td>{Idle, Initialized, Prepared, Stopped, PlaybackCompleted, Error}</p></td>
330 *     <td>Successful invoke of this method in a valid state transfers the
331 *         object to the <em>Paused</em> state. Calling this method in an
332 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
333 * <tr><td>prepare </p></td>
334 *     <td>{Initialized, Stopped} </p></td>
335 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
336 *     <td>Successful invoke of this method in a valid state transfers the
337 *         object to the <em>Prepared</em> state. Calling this method in an
338 *         invalid state throws an IllegalStateException.</p></td></tr>
339 * <tr><td>prepareAsync </p></td>
340 *     <td>{Initialized, Stopped} </p></td>
341 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
342 *     <td>Successful invoke of this method in a valid state transfers the
343 *         object to the <em>Preparing</em> state. Calling this method in an
344 *         invalid state throws an IllegalStateException.</p></td></tr>
345 * <tr><td>release </p></td>
346 *     <td>any </p></td>
347 *     <td>{} </p></td>
348 *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
349 * <tr><td>reset </p></td>
350 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
351 *         PlaybackCompleted, Error}</p></td>
352 *     <td>{}</p></td>
353 *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
354 * <tr><td>seekTo </p></td>
355 *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
356 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
357 *     <td>Successful invoke of this method in a valid state does not change
358 *         the state. Calling this method in an invalid state transfers the
359 *         object to the <em>Error</em> state. </p></td></tr>
360 * <tr><td>setAudioSessionId </p></td>
361 *     <td>{Idle} </p></td>
362 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
363 *          Error} </p></td>
364 *     <td>This method must be called in idle state as the audio session ID must be known before
365 *         calling setDataSource. Calling it does not change the object state. </p></td></tr>
366 * <tr><td>setAudioStreamType </p></td>
367 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
368 *          PlaybackCompleted}</p></td>
369 *     <td>{Error}</p></td>
370 *     <td>Successful invoke of this method does not change the state. In order for the
371 *         target audio stream type to become effective, this method must be called before
372 *         prepare() or prepareAsync().</p></td></tr>
373 * <tr><td>setAuxEffectSendLevel </p></td>
374 *     <td>any</p></td>
375 *     <td>{} </p></td>
376 *     <td>Calling this method does not change the object state. </p></td></tr>
377 * <tr><td>setDataSource </p></td>
378 *     <td>{Idle} </p></td>
379 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
380 *          Error} </p></td>
381 *     <td>Successful invoke of this method in a valid state transfers the
382 *         object to the <em>Initialized</em> state. Calling this method in an
383 *         invalid state throws an IllegalStateException.</p></td></tr>
384 * <tr><td>setDisplay </p></td>
385 *     <td>any </p></td>
386 *     <td>{} </p></td>
387 *     <td>This method can be called in any state and calling it does not change
388 *         the object state. </p></td></tr>
389 * <tr><td>setSurface </p></td>
390 *     <td>any </p></td>
391 *     <td>{} </p></td>
392 *     <td>This method can be called in any state and calling it does not change
393 *         the object state. </p></td></tr>
394 * <tr><td>setLooping </p></td>
395 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
396 *         PlaybackCompleted}</p></td>
397 *     <td>{Error}</p></td>
398 *     <td>Successful invoke of this method in a valid state does not change
399 *         the state. Calling this method in an
400 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
401 * <tr><td>isLooping </p></td>
402 *     <td>any </p></td>
403 *     <td>{} </p></td>
404 *     <td>This method can be called in any state and calling it does not change
405 *         the object state. </p></td></tr>
406 * <tr><td>setOnBufferingUpdateListener </p></td>
407 *     <td>any </p></td>
408 *     <td>{} </p></td>
409 *     <td>This method can be called in any state and calling it does not change
410 *         the object state. </p></td></tr>
411 * <tr><td>setOnCompletionListener </p></td>
412 *     <td>any </p></td>
413 *     <td>{} </p></td>
414 *     <td>This method can be called in any state and calling it does not change
415 *         the object state. </p></td></tr>
416 * <tr><td>setOnErrorListener </p></td>
417 *     <td>any </p></td>
418 *     <td>{} </p></td>
419 *     <td>This method can be called in any state and calling it does not change
420 *         the object state. </p></td></tr>
421 * <tr><td>setOnPreparedListener </p></td>
422 *     <td>any </p></td>
423 *     <td>{} </p></td>
424 *     <td>This method can be called in any state and calling it does not change
425 *         the object state. </p></td></tr>
426 * <tr><td>setOnSeekCompleteListener </p></td>
427 *     <td>any </p></td>
428 *     <td>{} </p></td>
429 *     <td>This method can be called in any state and calling it does not change
430 *         the object state. </p></td></tr>
431 * <tr><td>setScreenOnWhilePlaying</></td>
432 *     <td>any </p></td>
433 *     <td>{} </p></td>
434 *     <td>This method can be called in any state and calling it does not change
435 *         the object state.  </p></td></tr>
436 * <tr><td>setVolume </p></td>
437 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
438 *          PlaybackCompleted}</p></td>
439 *     <td>{Error}</p></td>
440 *     <td>Successful invoke of this method does not change the state.
441 * <tr><td>setWakeMode </p></td>
442 *     <td>any </p></td>
443 *     <td>{} </p></td>
444 *     <td>This method can be called in any state and calling it does not change
445 *         the object state.</p></td></tr>
446 * <tr><td>start </p></td>
447 *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
448 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
449 *     <td>Successful invoke of this method in a valid state transfers the
450 *         object to the <em>Started</em> state. Calling this method in an
451 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
452 * <tr><td>stop </p></td>
453 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
454 *     <td>{Idle, Initialized, Error}</p></td>
455 *     <td>Successful invoke of this method in a valid state transfers the
456 *         object to the <em>Stopped</em> state. Calling this method in an
457 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
458 *
459 * </table>
460 *
461 * <a name="Permissions"></a>
462 * <h3>Permissions</h3>
463 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
464 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
465 * element.
466 *
467 * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
468 * when used with network-based content.
469 *
470 * <a name="Callbacks"></a>
471 * <h3>Callbacks</h3>
472 * <p>Applications may want to register for informational and error
473 * events in order to be informed of some internal state update and
474 * possible runtime errors during playback or streaming. Registration for
475 * these events is done by properly setting the appropriate listeners (via calls
476 * to
477 * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
478 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
479 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
480 * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
481 * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
482 * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
483 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
484 * In order to receive the respective callback
485 * associated with these listeners, applications are required to create
486 * MediaPlayer objects on a thread with its own Looper running (main UI
487 * thread by default has a Looper running).
488 *
489 */
490public class MediaPlayer
491{
492    /**
493       Constant to retrieve only the new metadata since the last
494       call.
495       // FIXME: unhide.
496       // FIXME: add link to getMetadata(boolean, boolean)
497       {@hide}
498     */
499    public static final boolean METADATA_UPDATE_ONLY = true;
500
501    /**
502       Constant to retrieve all the metadata.
503       // FIXME: unhide.
504       // FIXME: add link to getMetadata(boolean, boolean)
505       {@hide}
506     */
507    public static final boolean METADATA_ALL = false;
508
509    /**
510       Constant to enable the metadata filter during retrieval.
511       // FIXME: unhide.
512       // FIXME: add link to getMetadata(boolean, boolean)
513       {@hide}
514     */
515    public static final boolean APPLY_METADATA_FILTER = true;
516
517    /**
518       Constant to disable the metadata filter during retrieval.
519       // FIXME: unhide.
520       // FIXME: add link to getMetadata(boolean, boolean)
521       {@hide}
522     */
523    public static final boolean BYPASS_METADATA_FILTER = false;
524
525    static {
526        System.loadLibrary("media_jni");
527        native_init();
528    }
529
530    private final static String TAG = "MediaPlayer";
531    // Name of the remote interface for the media player. Must be kept
532    // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
533    // macro invocation in IMediaPlayer.cpp
534    private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
535
536    private int mNativeContext; // accessed by native methods
537    private int mNativeSurfaceTexture;  // accessed by native methods
538    private int mListenerContext; // accessed by native methods
539    private SurfaceHolder mSurfaceHolder;
540    private EventHandler mEventHandler;
541    private PowerManager.WakeLock mWakeLock = null;
542    private boolean mScreenOnWhilePlaying;
543    private boolean mStayAwake;
544
545    /**
546     * Default constructor. Consider using one of the create() methods for
547     * synchronously instantiating a MediaPlayer from a Uri or resource.
548     * <p>When done with the MediaPlayer, you should call  {@link #release()},
549     * to free the resources. If not released, too many MediaPlayer instances may
550     * result in an exception.</p>
551     */
552    public MediaPlayer() {
553
554        Looper looper;
555        if ((looper = Looper.myLooper()) != null) {
556            mEventHandler = new EventHandler(this, looper);
557        } else if ((looper = Looper.getMainLooper()) != null) {
558            mEventHandler = new EventHandler(this, looper);
559        } else {
560            mEventHandler = null;
561        }
562
563        /* Native setup requires a weak reference to our object.
564         * It's easier to create it here than in C++.
565         */
566        native_setup(new WeakReference<MediaPlayer>(this));
567    }
568
569    /*
570     * Update the MediaPlayer SurfaceTexture.
571     * Call after setting a new display surface.
572     */
573    private native void _setVideoSurface(Surface surface);
574
575    /**
576     * Create a request parcel which can be routed to the native media
577     * player using {@link #invoke(Parcel, Parcel)}. The Parcel
578     * returned has the proper InterfaceToken set. The caller should
579     * not overwrite that token, i.e it can only append data to the
580     * Parcel.
581     *
582     * @return A parcel suitable to hold a request for the native
583     * player.
584     * {@hide}
585     */
586    public Parcel newRequest() {
587        Parcel parcel = Parcel.obtain();
588        parcel.writeInterfaceToken(IMEDIA_PLAYER);
589        return parcel;
590    }
591
592    /**
593     * Invoke a generic method on the native player using opaque
594     * parcels for the request and reply. Both payloads' format is a
595     * convention between the java caller and the native player.
596     * Must be called after setDataSource to make sure a native player
597     * exists.
598     *
599     * @param request Parcel with the data for the extension. The
600     * caller must use {@link #newRequest()} to get one.
601     *
602     * @param reply Output parcel with the data returned by the
603     * native player.
604     *
605     * @return The status code see utils/Errors.h
606     * {@hide}
607     */
608    public int invoke(Parcel request, Parcel reply) {
609        int retcode = native_invoke(request, reply);
610        reply.setDataPosition(0);
611        return retcode;
612    }
613
614    /**
615     * Sets the {@link SurfaceHolder} to use for displaying the video
616     * portion of the media.
617     *
618     * Either a surface holder or surface must be set if a display or video sink
619     * is needed.  Not calling this method or {@link #setSurface(Surface)}
620     * when playing back a video will result in only the audio track being played.
621     * A null surface holder or surface will result in only the audio track being
622     * played.
623     *
624     * @param sh the SurfaceHolder to use for video display
625     */
626    public void setDisplay(SurfaceHolder sh) {
627        mSurfaceHolder = sh;
628        Surface surface;
629        if (sh != null) {
630            surface = sh.getSurface();
631        } else {
632            surface = null;
633        }
634        _setVideoSurface(surface);
635        updateSurfaceScreenOn();
636    }
637
638    /**
639     * Sets the {@link Surface} to be used as the sink for the video portion of
640     * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but
641     * does not support {@link #setScreenOnWhilePlaying(boolean)}.  Setting a
642     * Surface will un-set any Surface or SurfaceHolder that was previously set.
643     * A null surface will result in only the audio track being played.
644     *
645     * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
646     * returned from {@link SurfaceTexture#getTimestamp()} will have an
647     * unspecified zero point.  These timestamps cannot be directly compared
648     * between different media sources, different instances of the same media
649     * source, or multiple runs of the same program.  The timestamp is normally
650     * monotonically increasing and is unaffected by time-of-day adjustments,
651     * but it is reset when the position is set.
652     *
653     * @param surface The {@link Surface} to be used for the video portion of
654     * the media.
655     */
656    public void setSurface(Surface surface) {
657        if (mScreenOnWhilePlaying && surface != null) {
658            Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
659        }
660        mSurfaceHolder = null;
661        _setVideoSurface(surface);
662        updateSurfaceScreenOn();
663    }
664
665    /**
666     * Convenience method to create a MediaPlayer for a given Uri.
667     * On success, {@link #prepare()} will already have been called and must not be called again.
668     * <p>When done with the MediaPlayer, you should call  {@link #release()},
669     * to free the resources. If not released, too many MediaPlayer instances will
670     * result in an exception.</p>
671     *
672     * @param context the Context to use
673     * @param uri the Uri from which to get the datasource
674     * @return a MediaPlayer object, or null if creation failed
675     */
676    public static MediaPlayer create(Context context, Uri uri) {
677        return create (context, uri, null);
678    }
679
680    /**
681     * Convenience method to create a MediaPlayer for a given Uri.
682     * On success, {@link #prepare()} will already have been called and must not be called again.
683     * <p>When done with the MediaPlayer, you should call  {@link #release()},
684     * to free the resources. If not released, too many MediaPlayer instances will
685     * result in an exception.</p>
686     *
687     * @param context the Context to use
688     * @param uri the Uri from which to get the datasource
689     * @param holder the SurfaceHolder to use for displaying the video
690     * @return a MediaPlayer object, or null if creation failed
691     */
692    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
693
694        try {
695            MediaPlayer mp = new MediaPlayer();
696            mp.setDataSource(context, uri);
697            if (holder != null) {
698                mp.setDisplay(holder);
699            }
700            mp.prepare();
701            return mp;
702        } catch (IOException ex) {
703            Log.d(TAG, "create failed:", ex);
704            // fall through
705        } catch (IllegalArgumentException ex) {
706            Log.d(TAG, "create failed:", ex);
707            // fall through
708        } catch (SecurityException ex) {
709            Log.d(TAG, "create failed:", ex);
710            // fall through
711        }
712
713        return null;
714    }
715
716    // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
717
718    /**
719     * Convenience method to create a MediaPlayer for a given resource id.
720     * On success, {@link #prepare()} will already have been called and must not be called again.
721     * <p>When done with the MediaPlayer, you should call  {@link #release()},
722     * to free the resources. If not released, too many MediaPlayer instances will
723     * result in an exception.</p>
724     *
725     * @param context the Context to use
726     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
727     *              the resource to use as the datasource
728     * @return a MediaPlayer object, or null if creation failed
729     */
730    public static MediaPlayer create(Context context, int resid) {
731        try {
732            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
733            if (afd == null) return null;
734
735            MediaPlayer mp = new MediaPlayer();
736            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
737            afd.close();
738            mp.prepare();
739            return mp;
740        } catch (IOException ex) {
741            Log.d(TAG, "create failed:", ex);
742            // fall through
743        } catch (IllegalArgumentException ex) {
744            Log.d(TAG, "create failed:", ex);
745           // fall through
746        } catch (SecurityException ex) {
747            Log.d(TAG, "create failed:", ex);
748            // fall through
749        }
750        return null;
751    }
752
753    /**
754     * Sets the data source as a content Uri.
755     *
756     * @param context the Context to use when resolving the Uri
757     * @param uri the Content URI of the data you want to play
758     * @throws IllegalStateException if it is called in an invalid state
759     */
760    public void setDataSource(Context context, Uri uri)
761        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
762        setDataSource(context, uri, null);
763    }
764
765    /**
766     * Sets the data source as a content Uri.
767     *
768     * @param context the Context to use when resolving the Uri
769     * @param uri the Content URI of the data you want to play
770     * @param headers the headers to be sent together with the request for the data
771     * @throws IllegalStateException if it is called in an invalid state
772     */
773    public void setDataSource(Context context, Uri uri, Map<String, String> headers)
774        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
775
776        String scheme = uri.getScheme();
777        if(scheme == null || scheme.equals("file")) {
778            setDataSource(uri.getPath());
779            return;
780        }
781
782        AssetFileDescriptor fd = null;
783        try {
784            ContentResolver resolver = context.getContentResolver();
785            fd = resolver.openAssetFileDescriptor(uri, "r");
786            if (fd == null) {
787                return;
788            }
789            // Note: using getDeclaredLength so that our behavior is the same
790            // as previous versions when the content provider is returning
791            // a full file.
792            if (fd.getDeclaredLength() < 0) {
793                setDataSource(fd.getFileDescriptor());
794            } else {
795                setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
796            }
797            return;
798        } catch (SecurityException ex) {
799        } catch (IOException ex) {
800        } finally {
801            if (fd != null) {
802                fd.close();
803            }
804        }
805
806        Log.d(TAG, "Couldn't open file on client side, trying server side");
807        setDataSource(uri.toString(), headers);
808        return;
809    }
810
811    /**
812     * Sets the data source (file-path or http/rtsp URL) to use.
813     *
814     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
815     * @throws IllegalStateException if it is called in an invalid state
816     *
817     * <p>When <code>path</code> refers to a local file, the file may actually be opened by a
818     * process other than the calling application.  This implies that the pathname
819     * should be an absolute path (as any other process runs with unspecified current working
820     * directory), and that the pathname should reference a world-readable file.
821     * As an alternative, the application could first open the file for reading,
822     * and then use the file descriptor form {@link #setDataSource(FileDescriptor)}.
823     */
824    public native void setDataSource(String path)
825            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
826
827    /**
828     * Sets the data source (file-path or http/rtsp URL) to use.
829     *
830     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
831     * @param headers the headers associated with the http request for the stream you want to play
832     * @throws IllegalStateException if it is called in an invalid state
833     * @hide pending API council
834     */
835    public void setDataSource(String path, Map<String, String> headers)
836            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException
837    {
838        String[] keys = null;
839        String[] values = null;
840
841        if (headers != null) {
842            keys = new String[headers.size()];
843            values = new String[headers.size()];
844
845            int i = 0;
846            for (Map.Entry<String, String> entry: headers.entrySet()) {
847                keys[i] = entry.getKey();
848                values[i] = entry.getValue();
849                ++i;
850            }
851        }
852        _setDataSource(path, keys, values);
853    }
854
855    private native void _setDataSource(
856        String path, String[] keys, String[] values)
857        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
858
859    /**
860     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
861     * to close the file descriptor. It is safe to do so as soon as this call returns.
862     *
863     * @param fd the FileDescriptor for the file you want to play
864     * @throws IllegalStateException if it is called in an invalid state
865     */
866    public void setDataSource(FileDescriptor fd)
867            throws IOException, IllegalArgumentException, IllegalStateException {
868        // intentionally less than LONG_MAX
869        setDataSource(fd, 0, 0x7ffffffffffffffL);
870    }
871
872    /**
873     * Sets the data source (FileDescriptor) to use.  The FileDescriptor must be
874     * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
875     * to close the file descriptor. It is safe to do so as soon as this call returns.
876     *
877     * @param fd the FileDescriptor for the file you want to play
878     * @param offset the offset into the file where the data to be played starts, in bytes
879     * @param length the length in bytes of the data to be played
880     * @throws IllegalStateException if it is called in an invalid state
881     */
882    public native void setDataSource(FileDescriptor fd, long offset, long length)
883            throws IOException, IllegalArgumentException, IllegalStateException;
884
885    /**
886     * Prepares the player for playback, synchronously.
887     *
888     * After setting the datasource and the display surface, you need to either
889     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
890     * which blocks until MediaPlayer is ready for playback.
891     *
892     * @throws IllegalStateException if it is called in an invalid state
893     */
894    public native void prepare() throws IOException, IllegalStateException;
895
896    /**
897     * Prepares the player for playback, asynchronously.
898     *
899     * After setting the datasource and the display surface, you need to either
900     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
901     * which returns immediately, rather than blocking until enough data has been
902     * buffered.
903     *
904     * @throws IllegalStateException if it is called in an invalid state
905     */
906    public native void prepareAsync() throws IllegalStateException;
907
908    /**
909     * Starts or resumes playback. If playback had previously been paused,
910     * playback will continue from where it was paused. If playback had
911     * been stopped, or never started before, playback will start at the
912     * beginning.
913     *
914     * @throws IllegalStateException if it is called in an invalid state
915     */
916    public  void start() throws IllegalStateException {
917        stayAwake(true);
918        _start();
919    }
920
921    private native void _start() throws IllegalStateException;
922
923    /**
924     * Stops playback after playback has been stopped or paused.
925     *
926     * @throws IllegalStateException if the internal player engine has not been
927     * initialized.
928     */
929    public void stop() throws IllegalStateException {
930        stayAwake(false);
931        _stop();
932    }
933
934    private native void _stop() throws IllegalStateException;
935
936    /**
937     * Pauses playback. Call start() to resume.
938     *
939     * @throws IllegalStateException if the internal player engine has not been
940     * initialized.
941     */
942    public void pause() throws IllegalStateException {
943        stayAwake(false);
944        _pause();
945    }
946
947    private native void _pause() throws IllegalStateException;
948
949    /**
950     * Set the low-level power management behavior for this MediaPlayer.  This
951     * can be used when the MediaPlayer is not playing through a SurfaceHolder
952     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
953     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
954     *
955     * <p>This function has the MediaPlayer access the low-level power manager
956     * service to control the device's power usage while playing is occurring.
957     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
958     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
959     * permission.
960     * By default, no attempt is made to keep the device awake during playback.
961     *
962     * @param context the Context to use
963     * @param mode    the power/wake mode to set
964     * @see android.os.PowerManager
965     */
966    public void setWakeMode(Context context, int mode) {
967        boolean washeld = false;
968        if (mWakeLock != null) {
969            if (mWakeLock.isHeld()) {
970                washeld = true;
971                mWakeLock.release();
972            }
973            mWakeLock = null;
974        }
975
976        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
977        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
978        mWakeLock.setReferenceCounted(false);
979        if (washeld) {
980            mWakeLock.acquire();
981        }
982    }
983
984    /**
985     * Control whether we should use the attached SurfaceHolder to keep the
986     * screen on while video playback is occurring.  This is the preferred
987     * method over {@link #setWakeMode} where possible, since it doesn't
988     * require that the application have permission for low-level wake lock
989     * access.
990     *
991     * @param screenOn Supply true to keep the screen on, false to allow it
992     * to turn off.
993     */
994    public void setScreenOnWhilePlaying(boolean screenOn) {
995        if (mScreenOnWhilePlaying != screenOn) {
996            if (screenOn && mSurfaceHolder == null) {
997                Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
998            }
999            mScreenOnWhilePlaying = screenOn;
1000            updateSurfaceScreenOn();
1001        }
1002    }
1003
1004    private void stayAwake(boolean awake) {
1005        if (mWakeLock != null) {
1006            if (awake && !mWakeLock.isHeld()) {
1007                mWakeLock.acquire();
1008            } else if (!awake && mWakeLock.isHeld()) {
1009                mWakeLock.release();
1010            }
1011        }
1012        mStayAwake = awake;
1013        updateSurfaceScreenOn();
1014    }
1015
1016    private void updateSurfaceScreenOn() {
1017        if (mSurfaceHolder != null) {
1018            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1019        }
1020    }
1021
1022    /**
1023     * Returns the width of the video.
1024     *
1025     * @return the width of the video, or 0 if there is no video,
1026     * no display surface was set, or the width has not been determined
1027     * yet. The OnVideoSizeChangedListener can be registered via
1028     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1029     * to provide a notification when the width is available.
1030     */
1031    public native int getVideoWidth();
1032
1033    /**
1034     * Returns the height of the video.
1035     *
1036     * @return the height of the video, or 0 if there is no video,
1037     * no display surface was set, or the height has not been determined
1038     * yet. The OnVideoSizeChangedListener can be registered via
1039     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1040     * to provide a notification when the height is available.
1041     */
1042    public native int getVideoHeight();
1043
1044    /**
1045     * Checks whether the MediaPlayer is playing.
1046     *
1047     * @return true if currently playing, false otherwise
1048     */
1049    public native boolean isPlaying();
1050
1051    /**
1052     * Seeks to specified time position.
1053     *
1054     * @param msec the offset in milliseconds from the start to seek to
1055     * @throws IllegalStateException if the internal player engine has not been
1056     * initialized
1057     */
1058    public native void seekTo(int msec) throws IllegalStateException;
1059
1060    /**
1061     * Gets the current playback position.
1062     *
1063     * @return the current position in milliseconds
1064     */
1065    public native int getCurrentPosition();
1066
1067    /**
1068     * Gets the duration of the file.
1069     *
1070     * @return the duration in milliseconds
1071     */
1072    public native int getDuration();
1073
1074    /**
1075     * Gets the media metadata.
1076     *
1077     * @param update_only controls whether the full set of available
1078     * metadata is returned or just the set that changed since the
1079     * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
1080     * #METADATA_ALL}.
1081     *
1082     * @param apply_filter if true only metadata that matches the
1083     * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
1084     * #BYPASS_METADATA_FILTER}.
1085     *
1086     * @return The metadata, possibly empty. null if an error occured.
1087     // FIXME: unhide.
1088     * {@hide}
1089     */
1090    public Metadata getMetadata(final boolean update_only,
1091                                final boolean apply_filter) {
1092        Parcel reply = Parcel.obtain();
1093        Metadata data = new Metadata();
1094
1095        if (!native_getMetadata(update_only, apply_filter, reply)) {
1096            reply.recycle();
1097            return null;
1098        }
1099
1100        // Metadata takes over the parcel, don't recycle it unless
1101        // there is an error.
1102        if (!data.parse(reply)) {
1103            reply.recycle();
1104            return null;
1105        }
1106        return data;
1107    }
1108
1109    /**
1110     * Set a filter for the metadata update notification and update
1111     * retrieval. The caller provides 2 set of metadata keys, allowed
1112     * and blocked. The blocked set always takes precedence over the
1113     * allowed one.
1114     * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
1115     * shorthands to allow/block all or no metadata.
1116     *
1117     * By default, there is no filter set.
1118     *
1119     * @param allow Is the set of metadata the client is interested
1120     *              in receiving new notifications for.
1121     * @param block Is the set of metadata the client is not interested
1122     *              in receiving new notifications for.
1123     * @return The call status code.
1124     *
1125     // FIXME: unhide.
1126     * {@hide}
1127     */
1128    public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
1129        // Do our serialization manually instead of calling
1130        // Parcel.writeArray since the sets are made of the same type
1131        // we avoid paying the price of calling writeValue (used by
1132        // writeArray) which burns an extra int per element to encode
1133        // the type.
1134        Parcel request =  newRequest();
1135
1136        // The parcel starts already with an interface token. There
1137        // are 2 filters. Each one starts with a 4bytes number to
1138        // store the len followed by a number of int (4 bytes as well)
1139        // representing the metadata type.
1140        int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
1141
1142        if (request.dataCapacity() < capacity) {
1143            request.setDataCapacity(capacity);
1144        }
1145
1146        request.writeInt(allow.size());
1147        for(Integer t: allow) {
1148            request.writeInt(t);
1149        }
1150        request.writeInt(block.size());
1151        for(Integer t: block) {
1152            request.writeInt(t);
1153        }
1154        return native_setMetadataFilter(request);
1155    }
1156
1157    /**
1158     * Set the MediaPlayer to start when this MediaPlayer finishes playback
1159     * (i.e. reaches the end of the stream).
1160     * The media framework will attempt to transition from this player to
1161     * the next as seamlessly as possible. The next player can be set at
1162     * any time before completion. The next player must be prepared by the
1163     * app, and the application should not call start() on it.
1164     * The next MediaPlayer must be different from 'this'. An exception
1165     * will be thrown if next == this.
1166     * The application may call setNextMediaPlayer(null) to indicate no
1167     * next player should be started at the end of playback.
1168     * If the current player is looping, it will keep looping and the next
1169     * player will not be started.
1170     *
1171     * @param next the player to start after this one completes playback.
1172     *
1173     * @hide
1174     */
1175    public native void setNextMediaPlayer(MediaPlayer next);
1176
1177    /**
1178     * Releases resources associated with this MediaPlayer object.
1179     * It is considered good practice to call this method when you're
1180     * done using the MediaPlayer. In particular, whenever an Activity
1181     * of an application is paused (its onPause() method is called),
1182     * or stopped (its onStop() method is called), this method should be
1183     * invoked to release the MediaPlayer object, unless the application
1184     * has a special need to keep the object around. In addition to
1185     * unnecessary resources (such as memory and instances of codecs)
1186     * being held, failure to call this method immediately if a
1187     * MediaPlayer object is no longer needed may also lead to
1188     * continuous battery consumption for mobile devices, and playback
1189     * failure for other applications if no multiple instances of the
1190     * same codec are supported on a device. Even if multiple instances
1191     * of the same codec are supported, some performance degradation
1192     * may be expected when unnecessary multiple instances are used
1193     * at the same time.
1194     */
1195    public void release() {
1196        stayAwake(false);
1197        updateSurfaceScreenOn();
1198        mOnPreparedListener = null;
1199        mOnBufferingUpdateListener = null;
1200        mOnCompletionListener = null;
1201        mOnSeekCompleteListener = null;
1202        mOnErrorListener = null;
1203        mOnInfoListener = null;
1204        mOnVideoSizeChangedListener = null;
1205        mOnTimedTextListener = null;
1206        _release();
1207    }
1208
1209    private native void _release();
1210
1211    /**
1212     * Resets the MediaPlayer to its uninitialized state. After calling
1213     * this method, you will have to initialize it again by setting the
1214     * data source and calling prepare().
1215     */
1216    public void reset() {
1217        stayAwake(false);
1218        _reset();
1219        // make sure none of the listeners get called anymore
1220        mEventHandler.removeCallbacksAndMessages(null);
1221    }
1222
1223    private native void _reset();
1224
1225    /**
1226     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
1227     * for a list of stream types. Must call this method before prepare() or
1228     * prepareAsync() in order for the target stream type to become effective
1229     * thereafter.
1230     *
1231     * @param streamtype the audio stream type
1232     * @see android.media.AudioManager
1233     */
1234    public native void setAudioStreamType(int streamtype);
1235
1236    /**
1237     * Sets the player to be looping or non-looping.
1238     *
1239     * @param looping whether to loop or not
1240     */
1241    public native void setLooping(boolean looping);
1242
1243    /**
1244     * Checks whether the MediaPlayer is looping or non-looping.
1245     *
1246     * @return true if the MediaPlayer is currently looping, false otherwise
1247     */
1248    public native boolean isLooping();
1249
1250    /**
1251     * Sets the volume on this player.
1252     * This API is recommended for balancing the output of audio streams
1253     * within an application. Unless you are writing an application to
1254     * control user settings, this API should be used in preference to
1255     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
1256     * a particular type. Note that the passed volume values are raw scalars.
1257     * UI controls should be scaled logarithmically.
1258     *
1259     * @param leftVolume left volume scalar
1260     * @param rightVolume right volume scalar
1261     */
1262    public native void setVolume(float leftVolume, float rightVolume);
1263
1264    /**
1265     * Currently not implemented, returns null.
1266     * @deprecated
1267     * @hide
1268     */
1269    public native Bitmap getFrameAt(int msec) throws IllegalStateException;
1270
1271    /**
1272     * Sets the audio session ID.
1273     *
1274     * @param sessionId the audio session ID.
1275     * The audio session ID is a system wide unique identifier for the audio stream played by
1276     * this MediaPlayer instance.
1277     * The primary use of the audio session ID  is to associate audio effects to a particular
1278     * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
1279     * this effect will be applied only to the audio content of media players within the same
1280     * audio session and not to the output mix.
1281     * When created, a MediaPlayer instance automatically generates its own audio session ID.
1282     * However, it is possible to force this player to be part of an already existing audio session
1283     * by calling this method.
1284     * This method must be called before one of the overloaded <code> setDataSource </code> methods.
1285     * @throws IllegalStateException if it is called in an invalid state
1286     */
1287    public native void setAudioSessionId(int sessionId)  throws IllegalArgumentException, IllegalStateException;
1288
1289    /**
1290     * Returns the audio session ID.
1291     *
1292     * @return the audio session ID. {@see #setAudioSessionId(int)}
1293     * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
1294     */
1295    public native int getAudioSessionId();
1296
1297    /**
1298     * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1299     * effect which can be applied on any sound source that directs a certain amount of its
1300     * energy to this effect. This amount is defined by setAuxEffectSendLevel().
1301     * {@see #setAuxEffectSendLevel(float)}.
1302     * <p>After creating an auxiliary effect (e.g.
1303     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1304     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1305     * to attach the player to the effect.
1306     * <p>To detach the effect from the player, call this method with a null effect id.
1307     * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1308     * methods.
1309     * @param effectId system wide unique id of the effect to attach
1310     */
1311    public native void attachAuxEffect(int effectId);
1312
1313    /* Do not change these values (starting with KEY_PARAMETER) without updating
1314     * their counterparts in include/media/mediaplayer.h!
1315     */
1316    /*
1317     * Key used in setParameter method.
1318     * Indicates the index of the timed text track to be enabled/disabled.
1319     * The index includes both the in-band and out-of-band timed text.
1320     * The index should start from in-band text if any. Application can retrieve the number
1321     * of in-band text tracks by using MediaMetadataRetriever::extractMetadata().
1322     * Note it might take a few hundred ms to scan an out-of-band text file
1323     * before displaying it.
1324     */
1325    private static final int KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX = 1000;
1326    /*
1327     * Key used in setParameter method.
1328     * Used to add out-of-band timed text source path.
1329     * Application can add multiple text sources by calling setParameter() with
1330     * KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE multiple times.
1331     */
1332    private static final int KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE = 1001;
1333
1334    // There are currently no defined keys usable from Java with get*Parameter.
1335    // But if any keys are defined, the order must be kept in sync with include/media/mediaplayer.h.
1336    // private static final int KEY_PARAMETER_... = ...;
1337
1338    /**
1339     * Sets the parameter indicated by key.
1340     * @param key key indicates the parameter to be set.
1341     * @param value value of the parameter to be set.
1342     * @return true if the parameter is set successfully, false otherwise
1343     * {@hide}
1344     */
1345    public native boolean setParameter(int key, Parcel value);
1346
1347    /**
1348     * Sets the parameter indicated by key.
1349     * @param key key indicates the parameter to be set.
1350     * @param value value of the parameter to be set.
1351     * @return true if the parameter is set successfully, false otherwise
1352     * {@hide}
1353     */
1354    public boolean setParameter(int key, String value) {
1355        Parcel p = Parcel.obtain();
1356        p.writeString(value);
1357        boolean ret = setParameter(key, p);
1358        p.recycle();
1359        return ret;
1360    }
1361
1362    /**
1363     * Sets the parameter indicated by key.
1364     * @param key key indicates the parameter to be set.
1365     * @param value value of the parameter to be set.
1366     * @return true if the parameter is set successfully, false otherwise
1367     * {@hide}
1368     */
1369    public boolean setParameter(int key, int value) {
1370        Parcel p = Parcel.obtain();
1371        p.writeInt(value);
1372        boolean ret = setParameter(key, p);
1373        p.recycle();
1374        return ret;
1375    }
1376
1377    /**
1378     * Gets the value of the parameter indicated by key.
1379     * @param key key indicates the parameter to get.
1380     * @param reply value of the parameter to get.
1381     */
1382    private native void getParameter(int key, Parcel reply);
1383
1384    /**
1385     * Gets the value of the parameter indicated by key.
1386     * The caller is responsible for recycling the returned parcel.
1387     * @param key key indicates the parameter to get.
1388     * @return value of the parameter.
1389     * {@hide}
1390     */
1391    public Parcel getParcelParameter(int key) {
1392        Parcel p = Parcel.obtain();
1393        getParameter(key, p);
1394        return p;
1395    }
1396
1397    /**
1398     * Gets the value of the parameter indicated by key.
1399     * @param key key indicates the parameter to get.
1400     * @return value of the parameter.
1401     * {@hide}
1402     */
1403    public String getStringParameter(int key) {
1404        Parcel p = Parcel.obtain();
1405        getParameter(key, p);
1406        String ret = p.readString();
1407        p.recycle();
1408        return ret;
1409    }
1410
1411    /**
1412     * Gets the value of the parameter indicated by key.
1413     * @param key key indicates the parameter to get.
1414     * @return value of the parameter.
1415     * {@hide}
1416     */
1417    public int getIntParameter(int key) {
1418        Parcel p = Parcel.obtain();
1419        getParameter(key, p);
1420        int ret = p.readInt();
1421        p.recycle();
1422        return ret;
1423    }
1424
1425    /**
1426     * Sets the send level of the player to the attached auxiliary effect
1427     * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1428     * <p>By default the send level is 0, so even if an effect is attached to the player
1429     * this method must be called for the effect to be applied.
1430     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1431     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1432     * so an appropriate conversion from linear UI input x to level is:
1433     * x == 0 -> level = 0
1434     * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1435     * @param level send level scalar
1436     */
1437    public native void setAuxEffectSendLevel(float level);
1438
1439    /**
1440     * @param request Parcel destinated to the media player. The
1441     *                Interface token must be set to the IMediaPlayer
1442     *                one to be routed correctly through the system.
1443     * @param reply[out] Parcel that will contain the reply.
1444     * @return The status code.
1445     */
1446    private native final int native_invoke(Parcel request, Parcel reply);
1447
1448
1449    /**
1450     * @param update_only If true fetch only the set of metadata that have
1451     *                    changed since the last invocation of getMetadata.
1452     *                    The set is built using the unfiltered
1453     *                    notifications the native player sent to the
1454     *                    MediaPlayerService during that period of
1455     *                    time. If false, all the metadatas are considered.
1456     * @param apply_filter  If true, once the metadata set has been built based on
1457     *                     the value update_only, the current filter is applied.
1458     * @param reply[out] On return contains the serialized
1459     *                   metadata. Valid only if the call was successful.
1460     * @return The status code.
1461     */
1462    private native final boolean native_getMetadata(boolean update_only,
1463                                                    boolean apply_filter,
1464                                                    Parcel reply);
1465
1466    /**
1467     * @param request Parcel with the 2 serialized lists of allowed
1468     *                metadata types followed by the one to be
1469     *                dropped. Each list starts with an integer
1470     *                indicating the number of metadata type elements.
1471     * @return The status code.
1472     */
1473    private native final int native_setMetadataFilter(Parcel request);
1474
1475    private static native final void native_init();
1476    private native final void native_setup(Object mediaplayer_this);
1477    private native final void native_finalize();
1478
1479    /**
1480     * @param index The index of the text track to be turned on.
1481     * @return true if the text track is enabled successfully.
1482     * {@hide}
1483     */
1484    public boolean enableTimedTextTrackIndex(int index) {
1485        if (index < 0) {
1486            return false;
1487        }
1488        return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, index);
1489    }
1490
1491    /**
1492     * Enables the first timed text track if any.
1493     * @return true if the text track is enabled successfully
1494     * {@hide}
1495     */
1496    public boolean enableTimedText() {
1497        return enableTimedTextTrackIndex(0);
1498    }
1499
1500    /**
1501     * Disables timed text display.
1502     * @return true if the text track is disabled successfully.
1503     * {@hide}
1504     */
1505    public boolean disableTimedText() {
1506        return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, -1);
1507    }
1508
1509    /**
1510     * @param reply Parcel with audio/video duration info for battery
1511                    tracking usage
1512     * @return The status code.
1513     * {@hide}
1514     */
1515    public native static int native_pullBatteryData(Parcel reply);
1516
1517    /**
1518     * Sets the target UDP re-transmit endpoint for the low level player.
1519     * Generally, the address portion of the endpoint is an IP multicast
1520     * address, although a unicast address would be equally valid.  When a valid
1521     * retransmit endpoint has been set, the media player will not decode and
1522     * render the media presentation locally.  Instead, the player will attempt
1523     * to re-multiplex its media data using the Android@Home RTP profile and
1524     * re-transmit to the target endpoint.  Receiver devices (which may be
1525     * either the same as the transmitting device or different devices) may
1526     * instantiate, prepare, and start a receiver player using a setDataSource
1527     * URL of the form...
1528     *
1529     * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
1530     *
1531     * to receive, decode and render the re-transmitted content.
1532     *
1533     * setRetransmitEndpoint may only be called before setDataSource has been
1534     * called; while the player is in the Idle state.
1535     *
1536     * @param endpoint the address and UDP port of the re-transmission target or
1537     * null if no re-transmission is to be performed.
1538     * @throws IllegalStateException if it is called in an invalid state
1539     * @throws IllegalArgumentException if the retransmit endpoint is supplied,
1540     * but invalid.
1541     *
1542     * {@hide} pending API council
1543     */
1544    public void setRetransmitEndpoint(InetSocketAddress endpoint)
1545            throws IllegalStateException, IllegalArgumentException
1546    {
1547        String addrString = null;
1548        int port = 0;
1549
1550        if (null != endpoint) {
1551            addrString = endpoint.getAddress().getHostAddress();
1552            port = endpoint.getPort();
1553        }
1554
1555        int ret = native_setRetransmitEndpoint(addrString, port);
1556        if (ret != 0) {
1557            throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
1558        }
1559    }
1560
1561    private native final int native_setRetransmitEndpoint(String addrString, int port);
1562
1563    @Override
1564    protected void finalize() { native_finalize(); }
1565
1566    /* Do not change these values without updating their counterparts
1567     * in include/media/mediaplayer.h!
1568     */
1569    private static final int MEDIA_NOP = 0; // interface test message
1570    private static final int MEDIA_PREPARED = 1;
1571    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
1572    private static final int MEDIA_BUFFERING_UPDATE = 3;
1573    private static final int MEDIA_SEEK_COMPLETE = 4;
1574    private static final int MEDIA_SET_VIDEO_SIZE = 5;
1575    private static final int MEDIA_TIMED_TEXT = 99;
1576    private static final int MEDIA_ERROR = 100;
1577    private static final int MEDIA_INFO = 200;
1578
1579    private class EventHandler extends Handler
1580    {
1581        private MediaPlayer mMediaPlayer;
1582
1583        public EventHandler(MediaPlayer mp, Looper looper) {
1584            super(looper);
1585            mMediaPlayer = mp;
1586        }
1587
1588        @Override
1589        public void handleMessage(Message msg) {
1590            if (mMediaPlayer.mNativeContext == 0) {
1591                Log.w(TAG, "mediaplayer went away with unhandled events");
1592                return;
1593            }
1594            switch(msg.what) {
1595            case MEDIA_PREPARED:
1596                if (mOnPreparedListener != null)
1597                    mOnPreparedListener.onPrepared(mMediaPlayer);
1598                return;
1599
1600            case MEDIA_PLAYBACK_COMPLETE:
1601                if (mOnCompletionListener != null)
1602                    mOnCompletionListener.onCompletion(mMediaPlayer);
1603                stayAwake(false);
1604                return;
1605
1606            case MEDIA_BUFFERING_UPDATE:
1607                if (mOnBufferingUpdateListener != null)
1608                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
1609                return;
1610
1611            case MEDIA_SEEK_COMPLETE:
1612              if (mOnSeekCompleteListener != null)
1613                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
1614              return;
1615
1616            case MEDIA_SET_VIDEO_SIZE:
1617              if (mOnVideoSizeChangedListener != null)
1618                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
1619              return;
1620
1621            case MEDIA_ERROR:
1622                // For PV specific error values (msg.arg2) look in
1623                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
1624                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
1625                boolean error_was_handled = false;
1626                if (mOnErrorListener != null) {
1627                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
1628                }
1629                if (mOnCompletionListener != null && ! error_was_handled) {
1630                    mOnCompletionListener.onCompletion(mMediaPlayer);
1631                }
1632                stayAwake(false);
1633                return;
1634
1635            case MEDIA_INFO:
1636                if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) {
1637                    Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
1638                }
1639                if (mOnInfoListener != null) {
1640                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
1641                }
1642                // No real default action so far.
1643                return;
1644            case MEDIA_TIMED_TEXT:
1645                if (mOnTimedTextListener != null) {
1646                    if (msg.obj == null) {
1647                        mOnTimedTextListener.onTimedText(mMediaPlayer, null);
1648                    } else {
1649                        if (msg.obj instanceof byte[]) {
1650                            TimedText text = new TimedText((byte[])(msg.obj));
1651                            mOnTimedTextListener.onTimedText(mMediaPlayer, text);
1652                        }
1653                    }
1654                }
1655                return;
1656
1657            case MEDIA_NOP: // interface test message - ignore
1658                break;
1659
1660            default:
1661                Log.e(TAG, "Unknown message type " + msg.what);
1662                return;
1663            }
1664        }
1665    }
1666
1667    /**
1668     * Called from native code when an interesting event happens.  This method
1669     * just uses the EventHandler system to post the event back to the main app thread.
1670     * We use a weak reference to the original MediaPlayer object so that the native
1671     * code is safe from the object disappearing from underneath it.  (This is
1672     * the cookie passed to native_setup().)
1673     */
1674    private static void postEventFromNative(Object mediaplayer_ref,
1675                                            int what, int arg1, int arg2, Object obj)
1676    {
1677        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
1678        if (mp == null) {
1679            return;
1680        }
1681
1682        if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
1683            // this acquires the wakelock if needed, and sets the client side state
1684            mp.start();
1685        }
1686        if (mp.mEventHandler != null) {
1687            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1688            mp.mEventHandler.sendMessage(m);
1689        }
1690    }
1691
1692    /**
1693     * Interface definition for a callback to be invoked when the media
1694     * source is ready for playback.
1695     */
1696    public interface OnPreparedListener
1697    {
1698        /**
1699         * Called when the media file is ready for playback.
1700         *
1701         * @param mp the MediaPlayer that is ready for playback
1702         */
1703        void onPrepared(MediaPlayer mp);
1704    }
1705
1706    /**
1707     * Register a callback to be invoked when the media source is ready
1708     * for playback.
1709     *
1710     * @param listener the callback that will be run
1711     */
1712    public void setOnPreparedListener(OnPreparedListener listener)
1713    {
1714        mOnPreparedListener = listener;
1715    }
1716
1717    private OnPreparedListener mOnPreparedListener;
1718
1719    /**
1720     * Interface definition for a callback to be invoked when playback of
1721     * a media source has completed.
1722     */
1723    public interface OnCompletionListener
1724    {
1725        /**
1726         * Called when the end of a media source is reached during playback.
1727         *
1728         * @param mp the MediaPlayer that reached the end of the file
1729         */
1730        void onCompletion(MediaPlayer mp);
1731    }
1732
1733    /**
1734     * Register a callback to be invoked when the end of a media source
1735     * has been reached during playback.
1736     *
1737     * @param listener the callback that will be run
1738     */
1739    public void setOnCompletionListener(OnCompletionListener listener)
1740    {
1741        mOnCompletionListener = listener;
1742    }
1743
1744    private OnCompletionListener mOnCompletionListener;
1745
1746    /**
1747     * Interface definition of a callback to be invoked indicating buffering
1748     * status of a media resource being streamed over the network.
1749     */
1750    public interface OnBufferingUpdateListener
1751    {
1752        /**
1753         * Called to update status in buffering a media stream received through
1754         * progressive HTTP download. The received buffering percentage
1755         * indicates how much of the content has been buffered or played.
1756         * For example a buffering update of 80 percent when half the content
1757         * has already been played indicates that the next 30 percent of the
1758         * content to play has been buffered.
1759         *
1760         * @param mp      the MediaPlayer the update pertains to
1761         * @param percent the percentage (0-100) of the content
1762         *                that has been buffered or played thus far
1763         */
1764        void onBufferingUpdate(MediaPlayer mp, int percent);
1765    }
1766
1767    /**
1768     * Register a callback to be invoked when the status of a network
1769     * stream's buffer has changed.
1770     *
1771     * @param listener the callback that will be run.
1772     */
1773    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
1774    {
1775        mOnBufferingUpdateListener = listener;
1776    }
1777
1778    private OnBufferingUpdateListener mOnBufferingUpdateListener;
1779
1780    /**
1781     * Interface definition of a callback to be invoked indicating
1782     * the completion of a seek operation.
1783     */
1784    public interface OnSeekCompleteListener
1785    {
1786        /**
1787         * Called to indicate the completion of a seek operation.
1788         *
1789         * @param mp the MediaPlayer that issued the seek operation
1790         */
1791        public void onSeekComplete(MediaPlayer mp);
1792    }
1793
1794    /**
1795     * Register a callback to be invoked when a seek operation has been
1796     * completed.
1797     *
1798     * @param listener the callback that will be run
1799     */
1800    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
1801    {
1802        mOnSeekCompleteListener = listener;
1803    }
1804
1805    private OnSeekCompleteListener mOnSeekCompleteListener;
1806
1807    /**
1808     * Interface definition of a callback to be invoked when the
1809     * video size is first known or updated
1810     */
1811    public interface OnVideoSizeChangedListener
1812    {
1813        /**
1814         * Called to indicate the video size
1815         *
1816         * The video size (width and height) could be 0 if there was no video,
1817         * no display surface was set, or the value was not determined yet.
1818         *
1819         * @param mp        the MediaPlayer associated with this callback
1820         * @param width     the width of the video
1821         * @param height    the height of the video
1822         */
1823        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
1824    }
1825
1826    /**
1827     * Register a callback to be invoked when the video size is
1828     * known or updated.
1829     *
1830     * @param listener the callback that will be run
1831     */
1832    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
1833    {
1834        mOnVideoSizeChangedListener = listener;
1835    }
1836
1837    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
1838
1839    /**
1840     * Interface definition of a callback to be invoked when a
1841     * timed text is available for display.
1842     * {@hide}
1843     */
1844    public interface OnTimedTextListener
1845    {
1846        /**
1847         * Called to indicate an avaliable timed text
1848         *
1849         * @param mp             the MediaPlayer associated with this callback
1850         * @param text           the timed text sample which contains the text
1851         *                       needed to be displayed and the display format.
1852         * {@hide}
1853         */
1854        public void onTimedText(MediaPlayer mp, TimedText text);
1855    }
1856
1857    /**
1858     * Register a callback to be invoked when a timed text is available
1859     * for display.
1860     *
1861     * @param listener the callback that will be run
1862     * {@hide}
1863     */
1864    public void setOnTimedTextListener(OnTimedTextListener listener)
1865    {
1866        mOnTimedTextListener = listener;
1867    }
1868
1869    private OnTimedTextListener mOnTimedTextListener;
1870
1871
1872    /* Do not change these values without updating their counterparts
1873     * in include/media/mediaplayer.h!
1874     */
1875    /** Unspecified media player error.
1876     * @see android.media.MediaPlayer.OnErrorListener
1877     */
1878    public static final int MEDIA_ERROR_UNKNOWN = 1;
1879
1880    /** Media server died. In this case, the application must release the
1881     * MediaPlayer object and instantiate a new one.
1882     * @see android.media.MediaPlayer.OnErrorListener
1883     */
1884    public static final int MEDIA_ERROR_SERVER_DIED = 100;
1885
1886    /** The video is streamed and its container is not valid for progressive
1887     * playback i.e the video's index (e.g moov atom) is not at the start of the
1888     * file.
1889     * @see android.media.MediaPlayer.OnErrorListener
1890     */
1891    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
1892
1893    /**
1894     * Interface definition of a callback to be invoked when there
1895     * has been an error during an asynchronous operation (other errors
1896     * will throw exceptions at method call time).
1897     */
1898    public interface OnErrorListener
1899    {
1900        /**
1901         * Called to indicate an error.
1902         *
1903         * @param mp      the MediaPlayer the error pertains to
1904         * @param what    the type of error that has occurred:
1905         * <ul>
1906         * <li>{@link #MEDIA_ERROR_UNKNOWN}
1907         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1908         * </ul>
1909         * @param extra an extra code, specific to the error. Typically
1910         * implementation dependant.
1911         * @return True if the method handled the error, false if it didn't.
1912         * Returning false, or not having an OnErrorListener at all, will
1913         * cause the OnCompletionListener to be called.
1914         */
1915        boolean onError(MediaPlayer mp, int what, int extra);
1916    }
1917
1918    /**
1919     * Register a callback to be invoked when an error has happened
1920     * during an asynchronous operation.
1921     *
1922     * @param listener the callback that will be run
1923     */
1924    public void setOnErrorListener(OnErrorListener listener)
1925    {
1926        mOnErrorListener = listener;
1927    }
1928
1929    private OnErrorListener mOnErrorListener;
1930
1931
1932    /* Do not change these values without updating their counterparts
1933     * in include/media/mediaplayer.h!
1934     */
1935    /** Unspecified media player info.
1936     * @see android.media.MediaPlayer.OnInfoListener
1937     */
1938    public static final int MEDIA_INFO_UNKNOWN = 1;
1939
1940    /** The player was started because it was used as the next player for another
1941     * player, which just completed playback.
1942     * @see android.media.MediaPlayer.OnInfoListener
1943     * @hide
1944     */
1945    public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
1946
1947    /** The video is too complex for the decoder: it can't decode frames fast
1948     *  enough. Possibly only the audio plays fine at this stage.
1949     * @see android.media.MediaPlayer.OnInfoListener
1950     */
1951    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
1952
1953    /** MediaPlayer is temporarily pausing playback internally in order to
1954     * buffer more data.
1955     * @see android.media.MediaPlayer.OnInfoListener
1956     */
1957    public static final int MEDIA_INFO_BUFFERING_START = 701;
1958
1959    /** MediaPlayer is resuming playback after filling buffers.
1960     * @see android.media.MediaPlayer.OnInfoListener
1961     */
1962    public static final int MEDIA_INFO_BUFFERING_END = 702;
1963
1964    /** Bad interleaving means that a media has been improperly interleaved or
1965     * not interleaved at all, e.g has all the video samples first then all the
1966     * audio ones. Video is playing but a lot of disk seeks may be happening.
1967     * @see android.media.MediaPlayer.OnInfoListener
1968     */
1969    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
1970
1971    /** The media cannot be seeked (e.g live stream)
1972     * @see android.media.MediaPlayer.OnInfoListener
1973     */
1974    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
1975
1976    /** A new set of metadata is available.
1977     * @see android.media.MediaPlayer.OnInfoListener
1978     */
1979    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
1980
1981    /**
1982     * Interface definition of a callback to be invoked to communicate some
1983     * info and/or warning about the media or its playback.
1984     */
1985    public interface OnInfoListener
1986    {
1987        /**
1988         * Called to indicate an info or a warning.
1989         *
1990         * @param mp      the MediaPlayer the info pertains to.
1991         * @param what    the type of info or warning.
1992         * <ul>
1993         * <li>{@link #MEDIA_INFO_UNKNOWN}
1994         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
1995         * <li>{@link #MEDIA_INFO_BUFFERING_START}
1996         * <li>{@link #MEDIA_INFO_BUFFERING_END}
1997         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
1998         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
1999         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
2000         * </ul>
2001         * @param extra an extra code, specific to the info. Typically
2002         * implementation dependant.
2003         * @return True if the method handled the info, false if it didn't.
2004         * Returning false, or not having an OnErrorListener at all, will
2005         * cause the info to be discarded.
2006         */
2007        boolean onInfo(MediaPlayer mp, int what, int extra);
2008    }
2009
2010    /**
2011     * Register a callback to be invoked when an info/warning is available.
2012     *
2013     * @param listener the callback that will be run
2014     */
2015    public void setOnInfoListener(OnInfoListener listener)
2016    {
2017        mOnInfoListener = listener;
2018    }
2019
2020    private OnInfoListener mOnInfoListener;
2021
2022}
2023