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