MediaPlayer.java revision 91784c996f95483e3041169215c0d6635e27ffcc
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 #setOnInfoListener(OnInfoListener)}setOnInfoListener,
476 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
477 * In order to receive the respective callback
478 * associated with these listeners, applications are required to create
479 * MediaPlayer objects on a thread with its own Looper running (main UI
480 * thread by default has a Looper running).
481 *
482 */
483public class MediaPlayer
484{
485    /**
486       Constant to retrieve only the new metadata since the last
487       call.
488       // FIXME: unhide.
489       // FIXME: add link to getMetadata(boolean, boolean)
490       {@hide}
491     */
492    public static final boolean METADATA_UPDATE_ONLY = true;
493
494    /**
495       Constant to retrieve all the metadata.
496       // FIXME: unhide.
497       // FIXME: add link to getMetadata(boolean, boolean)
498       {@hide}
499     */
500    public static final boolean METADATA_ALL = false;
501
502    /**
503       Constant to enable the metadata filter during retrieval.
504       // FIXME: unhide.
505       // FIXME: add link to getMetadata(boolean, boolean)
506       {@hide}
507     */
508    public static final boolean APPLY_METADATA_FILTER = true;
509
510    /**
511       Constant to disable the metadata filter during retrieval.
512       // FIXME: unhide.
513       // FIXME: add link to getMetadata(boolean, boolean)
514       {@hide}
515     */
516    public static final boolean BYPASS_METADATA_FILTER = false;
517
518    static {
519        System.loadLibrary("media_jni");
520        native_init();
521    }
522
523    private final static String TAG = "MediaPlayer";
524    // Name of the remote interface for the media player. Must be kept
525    // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
526    // macro invocation in IMediaPlayer.cpp
527    private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
528
529    private int mNativeContext; // accessed by native methods
530    private int mListenerContext; // accessed by native methods
531    private Surface mSurface; // accessed by native methods
532    private SurfaceHolder  mSurfaceHolder;
533    private ParcelSurfaceTexture mParcelSurfaceTexture; // accessed by native methods
534    private EventHandler mEventHandler;
535    private PowerManager.WakeLock mWakeLock = null;
536    private boolean mScreenOnWhilePlaying;
537    private boolean mStayAwake;
538
539    /**
540     * Default constructor. Consider using one of the create() methods for
541     * synchronously instantiating a MediaPlayer from a Uri or resource.
542     * <p>When done with the MediaPlayer, you should call  {@link #release()},
543     * to free the resources. If not released, too many MediaPlayer instances may
544     * result in an exception.</p>
545     */
546    public MediaPlayer() {
547
548        Looper looper;
549        if ((looper = Looper.myLooper()) != null) {
550            mEventHandler = new EventHandler(this, looper);
551        } else if ((looper = Looper.getMainLooper()) != null) {
552            mEventHandler = new EventHandler(this, looper);
553        } else {
554            mEventHandler = null;
555        }
556
557        /* Native setup requires a weak reference to our object.
558         * It's easier to create it here than in C++.
559         */
560        native_setup(new WeakReference<MediaPlayer>(this));
561    }
562
563    /*
564     * Update the MediaPlayer ISurface and ISurfaceTexture.
565     * Call after updating mSurface and/or mParcelSurfaceTexture.
566     */
567    private native void _setVideoSurfaceOrSurfaceTexture();
568
569    /**
570     * Create a request parcel which can be routed to the native media
571     * player using {@link #invoke(Parcel, Parcel)}. The Parcel
572     * returned has the proper InterfaceToken set. The caller should
573     * not overwrite that token, i.e it can only append data to the
574     * Parcel.
575     *
576     * @return A parcel suitable to hold a request for the native
577     * player.
578     * {@hide}
579     */
580    public Parcel newRequest() {
581        Parcel parcel = Parcel.obtain();
582        parcel.writeInterfaceToken(IMEDIA_PLAYER);
583        return parcel;
584    }
585
586    /**
587     * Invoke a generic method on the native player using opaque
588     * parcels for the request and reply. Both payloads' format is a
589     * convention between the java caller and the native player.
590     * Must be called after setDataSource to make sure a native player
591     * exists.
592     *
593     * @param request Parcel with the data for the extension. The
594     * caller must use {@link #newRequest()} to get one.
595     *
596     * @param reply Output parcel with the data returned by the
597     * native player.
598     *
599     * @return The status code see utils/Errors.h
600     * {@hide}
601     */
602    public int invoke(Parcel request, Parcel reply) {
603        int retcode = native_invoke(request, reply);
604        reply.setDataPosition(0);
605        return retcode;
606    }
607
608    /**
609     * Sets the {@link SurfaceHolder} to use for displaying the video
610     * portion of the media.
611     *
612     * Either a surface holder or surface must be set if a display or video sink
613     * is needed.  Not calling this method or {@link #setTexture(SurfaceTexture)}
614     * when playing back a video will result in only the audio track being played.
615     * A null surface holder or surface will result in only the audio track being
616     * played.
617     *
618     * @param sh the SurfaceHolder to use for video display
619     */
620    public void setDisplay(SurfaceHolder sh) {
621        mSurfaceHolder = sh;
622        if (sh != null) {
623            mSurface = sh.getSurface();
624        } else {
625            mSurface = null;
626        }
627        mParcelSurfaceTexture = null;
628        _setVideoSurfaceOrSurfaceTexture();
629        updateSurfaceScreenOn();
630    }
631
632    /**
633     * Sets the {@link Surface} to be used as the sink for the video portion of
634     * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but does not
635     * support {@link #setScreenOnWhilePlaying(boolean)} or {@link #updateSurfaceScreenOn()}.
636     * Setting a Surface will un-set any Surface or SurfaceHolder that was previously set.
637     * A null surface will result in only the audio track being played.
638     *
639     * @param surface The {@link Surface} to be used for the video portion of the media.
640     *
641     * @hide Pending review by API council.
642     */
643    public void setSurface(Surface surface) {
644        if (mScreenOnWhilePlaying && surface != null && mSurface != null) {
645            Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
646        }
647        mSurfaceHolder = null;
648        mSurface = surface;
649        mParcelSurfaceTexture = null;  // TODO(tedbo): Remove.
650        _setVideoSurfaceOrSurfaceTexture();
651        updateSurfaceScreenOn();
652    }
653
654    /**
655     * Sets the {@link SurfaceTexture} to be used as the sink for the
656     * video portion of the media. Either a surface or surface texture
657     * must be set if a video sink is needed.  The same surface texture
658     * can be re-set without harm. Setting a surface texture will un-set
659     * any surface that was set via {@link #setDisplay(SurfaceHolder)}.
660     * Not calling this method or {@link #setDisplay(SurfaceHolder)}
661     * when playing back a video will result in only the audio track
662     * being played. Note that if a SurfaceTexture is used, the value
663     * set via setScreenOnWhilePlaying has no effect.
664     *
665     * The timestamps provided by {@link SurfaceTexture#getTimestamp()} for a
666     * SurfaceTexture set as the video sink have an unspecified zero point,
667     * and cannot be directly compared between different media sources or different
668     * instances of the same media source, or across multiple runs of the same
669     * program.  The timestamp is normally monotonically increasing and unaffected
670     * by time-of-day adjustments, but is reset when the position is set.
671     */
672    public void setTexture(SurfaceTexture st) {
673        ParcelSurfaceTexture pst = null;
674        if (st != null) {
675            pst = ParcelSurfaceTexture.fromSurfaceTexture(st);
676        }
677        setParcelSurfaceTexture(pst);
678    }
679
680    /**
681     * Sets the {@link ParcelSurfaceTexture} to be used as the sink for the video portion of
682     * the media. This is similar to {@link #setTexture(SurfaceTexture)}, but supports using
683     * a {@link ParcelSurfaceTexture} to transport the texture to be used via Binder. Setting
684     * a parceled surface texture will un-set any surface or surface texture that was previously
685     * set. See {@link #setTexture(SurfaceTexture)} for more details.
686     *
687     * @param pst The {@link ParcelSurfaceTexture} to be used as the sink for
688     * the video portion of the media.
689     *
690     * @hide Pending removal when there are no more callers.
691     */
692    public void setParcelSurfaceTexture(ParcelSurfaceTexture pst) {
693        if (mScreenOnWhilePlaying && pst != null && mParcelSurfaceTexture == null) {
694            Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for SurfaceTexture");
695        }
696        mSurfaceHolder = null;
697        mSurface = null;
698        mParcelSurfaceTexture = pst;
699        _setVideoSurfaceOrSurfaceTexture();
700        updateSurfaceScreenOn();
701    }
702
703    /**
704     * Convenience method to create a MediaPlayer for a given Uri.
705     * On success, {@link #prepare()} will already have been called and must not be called again.
706     * <p>When done with the MediaPlayer, you should call  {@link #release()},
707     * to free the resources. If not released, too many MediaPlayer instances will
708     * result in an exception.</p>
709     *
710     * @param context the Context to use
711     * @param uri the Uri from which to get the datasource
712     * @return a MediaPlayer object, or null if creation failed
713     */
714    public static MediaPlayer create(Context context, Uri uri) {
715        return create (context, uri, null);
716    }
717
718    /**
719     * Convenience method to create a MediaPlayer for a given Uri.
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 uri the Uri from which to get the datasource
727     * @param holder the SurfaceHolder to use for displaying the video
728     * @return a MediaPlayer object, or null if creation failed
729     */
730    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
731
732        try {
733            MediaPlayer mp = new MediaPlayer();
734            mp.setDataSource(context, uri);
735            if (holder != null) {
736                mp.setDisplay(holder);
737            }
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
751        return null;
752    }
753
754    // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
755
756    /**
757     * Convenience method to create a MediaPlayer for a given resource id.
758     * On success, {@link #prepare()} will already have been called and must not be called again.
759     * <p>When done with the MediaPlayer, you should call  {@link #release()},
760     * to free the resources. If not released, too many MediaPlayer instances will
761     * result in an exception.</p>
762     *
763     * @param context the Context to use
764     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
765     *              the resource to use as the datasource
766     * @return a MediaPlayer object, or null if creation failed
767     */
768    public static MediaPlayer create(Context context, int resid) {
769        try {
770            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
771            if (afd == null) return null;
772
773            MediaPlayer mp = new MediaPlayer();
774            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
775            afd.close();
776            mp.prepare();
777            return mp;
778        } catch (IOException ex) {
779            Log.d(TAG, "create failed:", ex);
780            // fall through
781        } catch (IllegalArgumentException ex) {
782            Log.d(TAG, "create failed:", ex);
783           // fall through
784        } catch (SecurityException ex) {
785            Log.d(TAG, "create failed:", ex);
786            // fall through
787        }
788        return null;
789    }
790
791    /**
792     * Sets the data source as a content Uri.
793     *
794     * @param context the Context to use when resolving the Uri
795     * @param uri the Content URI of the data you want to play
796     * @throws IllegalStateException if it is called in an invalid state
797     */
798    public void setDataSource(Context context, Uri uri)
799        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
800        setDataSource(context, uri, null);
801    }
802
803    /**
804     * Sets the data source as a content Uri.
805     *
806     * @param context the Context to use when resolving the Uri
807     * @param uri the Content URI of the data you want to play
808     * @param headers the headers to be sent together with the request for the data
809     * @throws IllegalStateException if it is called in an invalid state
810     */
811    public void setDataSource(Context context, Uri uri, Map<String, String> headers)
812        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
813
814        String scheme = uri.getScheme();
815        if(scheme == null || scheme.equals("file")) {
816            setDataSource(uri.getPath());
817            return;
818        }
819
820        AssetFileDescriptor fd = null;
821        try {
822            ContentResolver resolver = context.getContentResolver();
823            fd = resolver.openAssetFileDescriptor(uri, "r");
824            if (fd == null) {
825                return;
826            }
827            // Note: using getDeclaredLength so that our behavior is the same
828            // as previous versions when the content provider is returning
829            // a full file.
830            if (fd.getDeclaredLength() < 0) {
831                setDataSource(fd.getFileDescriptor());
832            } else {
833                setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
834            }
835            return;
836        } catch (SecurityException ex) {
837        } catch (IOException ex) {
838        } finally {
839            if (fd != null) {
840                fd.close();
841            }
842        }
843        Log.d(TAG, "Couldn't open file on client side, trying server side");
844        setDataSource(uri.toString(), headers);
845        return;
846    }
847
848    /**
849     * Sets the data source (file-path or http/rtsp URL) to use.
850     *
851     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
852     * @throws IllegalStateException if it is called in an invalid state
853     */
854    public native void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException;
855
856    /**
857     * Sets the data source (file-path or http/rtsp URL) to use.
858     *
859     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
860     * @param headers the headers associated with the http request for the stream you want to play
861     * @throws IllegalStateException if it is called in an invalid state
862     * @hide pending API council
863     */
864    public void setDataSource(String path, Map<String, String> headers)
865            throws IOException, IllegalArgumentException, IllegalStateException
866    {
867        String[] keys = null;
868        String[] values = null;
869
870        if (headers != null) {
871            keys = new String[headers.size()];
872            values = new String[headers.size()];
873
874            int i = 0;
875            for (Map.Entry<String, String> entry: headers.entrySet()) {
876                keys[i] = entry.getKey();
877                values[i] = entry.getValue();
878                ++i;
879            }
880        }
881        _setDataSource(path, keys, values);
882    }
883
884    private native void _setDataSource(
885        String path, String[] keys, String[] values)
886        throws IOException, IllegalArgumentException, IllegalStateException;
887
888    /**
889     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
890     * to close the file descriptor. It is safe to do so as soon as this call returns.
891     *
892     * @param fd the FileDescriptor for the file you want to play
893     * @throws IllegalStateException if it is called in an invalid state
894     */
895    public void setDataSource(FileDescriptor fd)
896            throws IOException, IllegalArgumentException, IllegalStateException {
897        // intentionally less than LONG_MAX
898        setDataSource(fd, 0, 0x7ffffffffffffffL);
899    }
900
901    /**
902     * Sets the data source (FileDescriptor) to use.  The FileDescriptor must be
903     * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
904     * to close the file descriptor. It is safe to do so as soon as this call returns.
905     *
906     * @param fd the FileDescriptor for the file you want to play
907     * @param offset the offset into the file where the data to be played starts, in bytes
908     * @param length the length in bytes of the data to be played
909     * @throws IllegalStateException if it is called in an invalid state
910     */
911    public native void setDataSource(FileDescriptor fd, long offset, long length)
912            throws IOException, IllegalArgumentException, IllegalStateException;
913
914    /**
915     * Prepares the player for playback, synchronously.
916     *
917     * After setting the datasource and the display surface, you need to either
918     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
919     * which blocks until MediaPlayer is ready for playback.
920     *
921     * @throws IllegalStateException if it is called in an invalid state
922     */
923    public native void prepare() throws IOException, IllegalStateException;
924
925    /**
926     * Prepares the player for playback, asynchronously.
927     *
928     * After setting the datasource and the display surface, you need to either
929     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
930     * which returns immediately, rather than blocking until enough data has been
931     * buffered.
932     *
933     * @throws IllegalStateException if it is called in an invalid state
934     */
935    public native void prepareAsync() throws IllegalStateException;
936
937    /**
938     * Starts or resumes playback. If playback had previously been paused,
939     * playback will continue from where it was paused. If playback had
940     * been stopped, or never started before, playback will start at the
941     * beginning.
942     *
943     * @throws IllegalStateException if it is called in an invalid state
944     */
945    public  void start() throws IllegalStateException {
946        stayAwake(true);
947        _start();
948    }
949
950    private native void _start() throws IllegalStateException;
951
952    /**
953     * Stops playback after playback has been stopped or paused.
954     *
955     * @throws IllegalStateException if the internal player engine has not been
956     * initialized.
957     */
958    public void stop() throws IllegalStateException {
959        stayAwake(false);
960        _stop();
961    }
962
963    private native void _stop() throws IllegalStateException;
964
965    /**
966     * Pauses playback. Call start() to resume.
967     *
968     * @throws IllegalStateException if the internal player engine has not been
969     * initialized.
970     */
971    public void pause() throws IllegalStateException {
972        stayAwake(false);
973        _pause();
974    }
975
976    private native void _pause() throws IllegalStateException;
977
978    /**
979     * Set the low-level power management behavior for this MediaPlayer.  This
980     * can be used when the MediaPlayer is not playing through a SurfaceHolder
981     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
982     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
983     *
984     * <p>This function has the MediaPlayer access the low-level power manager
985     * service to control the device's power usage while playing is occurring.
986     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
987     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
988     * permission.
989     * By default, no attempt is made to keep the device awake during playback.
990     *
991     * @param context the Context to use
992     * @param mode    the power/wake mode to set
993     * @see android.os.PowerManager
994     */
995    public void setWakeMode(Context context, int mode) {
996        boolean washeld = false;
997        if (mWakeLock != null) {
998            if (mWakeLock.isHeld()) {
999                washeld = true;
1000                mWakeLock.release();
1001            }
1002            mWakeLock = null;
1003        }
1004
1005        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1006        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
1007        mWakeLock.setReferenceCounted(false);
1008        if (washeld) {
1009            mWakeLock.acquire();
1010        }
1011    }
1012
1013    /**
1014     * Control whether we should use the attached SurfaceHolder to keep the
1015     * screen on while video playback is occurring.  This is the preferred
1016     * method over {@link #setWakeMode} where possible, since it doesn't
1017     * require that the application have permission for low-level wake lock
1018     * access.
1019     *
1020     * @param screenOn Supply true to keep the screen on, false to allow it
1021     * to turn off.
1022     */
1023    public void setScreenOnWhilePlaying(boolean screenOn) {
1024        if (mScreenOnWhilePlaying != screenOn) {
1025            if (screenOn && mSurfaceHolder == null) {
1026                Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
1027            }
1028            mScreenOnWhilePlaying = screenOn;
1029            updateSurfaceScreenOn();
1030        }
1031    }
1032
1033    private void stayAwake(boolean awake) {
1034        if (mWakeLock != null) {
1035            if (awake && !mWakeLock.isHeld()) {
1036                mWakeLock.acquire();
1037            } else if (!awake && mWakeLock.isHeld()) {
1038                mWakeLock.release();
1039            }
1040        }
1041        mStayAwake = awake;
1042        updateSurfaceScreenOn();
1043    }
1044
1045    private void updateSurfaceScreenOn() {
1046        if (mSurfaceHolder != null) {
1047            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1048        }
1049    }
1050
1051    /**
1052     * Returns the width of the video.
1053     *
1054     * @return the width of the video, or 0 if there is no video,
1055     * no display surface was set, or the width has not been determined
1056     * yet. The OnVideoSizeChangedListener can be registered via
1057     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1058     * to provide a notification when the width is available.
1059     */
1060    public native int getVideoWidth();
1061
1062    /**
1063     * Returns the height of the video.
1064     *
1065     * @return the height of the video, or 0 if there is no video,
1066     * no display surface was set, or the height has not been determined
1067     * yet. The OnVideoSizeChangedListener can be registered via
1068     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1069     * to provide a notification when the height is available.
1070     */
1071    public native int getVideoHeight();
1072
1073    /**
1074     * Checks whether the MediaPlayer is playing.
1075     *
1076     * @return true if currently playing, false otherwise
1077     */
1078    public native boolean isPlaying();
1079
1080    /**
1081     * Seeks to specified time position.
1082     *
1083     * @param msec the offset in milliseconds from the start to seek to
1084     * @throws IllegalStateException if the internal player engine has not been
1085     * initialized
1086     */
1087    public native void seekTo(int msec) throws IllegalStateException;
1088
1089    /**
1090     * Gets the current playback position.
1091     *
1092     * @return the current position in milliseconds
1093     */
1094    public native int getCurrentPosition();
1095
1096    /**
1097     * Gets the duration of the file.
1098     *
1099     * @return the duration in milliseconds
1100     */
1101    public native int getDuration();
1102
1103    /**
1104     * Gets the media metadata.
1105     *
1106     * @param update_only controls whether the full set of available
1107     * metadata is returned or just the set that changed since the
1108     * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
1109     * #METADATA_ALL}.
1110     *
1111     * @param apply_filter if true only metadata that matches the
1112     * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
1113     * #BYPASS_METADATA_FILTER}.
1114     *
1115     * @return The metadata, possibly empty. null if an error occured.
1116     // FIXME: unhide.
1117     * {@hide}
1118     */
1119    public Metadata getMetadata(final boolean update_only,
1120                                final boolean apply_filter) {
1121        Parcel reply = Parcel.obtain();
1122        Metadata data = new Metadata();
1123
1124        if (!native_getMetadata(update_only, apply_filter, reply)) {
1125            reply.recycle();
1126            return null;
1127        }
1128
1129        // Metadata takes over the parcel, don't recycle it unless
1130        // there is an error.
1131        if (!data.parse(reply)) {
1132            reply.recycle();
1133            return null;
1134        }
1135        return data;
1136    }
1137
1138    /**
1139     * Set a filter for the metadata update notification and update
1140     * retrieval. The caller provides 2 set of metadata keys, allowed
1141     * and blocked. The blocked set always takes precedence over the
1142     * allowed one.
1143     * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
1144     * shorthands to allow/block all or no metadata.
1145     *
1146     * By default, there is no filter set.
1147     *
1148     * @param allow Is the set of metadata the client is interested
1149     *              in receiving new notifications for.
1150     * @param block Is the set of metadata the client is not interested
1151     *              in receiving new notifications for.
1152     * @return The call status code.
1153     *
1154     // FIXME: unhide.
1155     * {@hide}
1156     */
1157    public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
1158        // Do our serialization manually instead of calling
1159        // Parcel.writeArray since the sets are made of the same type
1160        // we avoid paying the price of calling writeValue (used by
1161        // writeArray) which burns an extra int per element to encode
1162        // the type.
1163        Parcel request =  newRequest();
1164
1165        // The parcel starts already with an interface token. There
1166        // are 2 filters. Each one starts with a 4bytes number to
1167        // store the len followed by a number of int (4 bytes as well)
1168        // representing the metadata type.
1169        int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
1170
1171        if (request.dataCapacity() < capacity) {
1172            request.setDataCapacity(capacity);
1173        }
1174
1175        request.writeInt(allow.size());
1176        for(Integer t: allow) {
1177            request.writeInt(t);
1178        }
1179        request.writeInt(block.size());
1180        for(Integer t: block) {
1181            request.writeInt(t);
1182        }
1183        return native_setMetadataFilter(request);
1184    }
1185
1186    /**
1187     * Releases resources associated with this MediaPlayer object.
1188     * It is considered good practice to call this method when you're
1189     * done using the MediaPlayer. For instance, whenever the Activity
1190     * of an application is paused, this method should be invoked to
1191     * release the MediaPlayer object. In addition to unnecessary resources
1192     * (such as memory and instances of codecs) being hold, failure to
1193     * call this method immediately if a MediaPlayer object is no longer
1194     * needed may also lead to continuous battery consumption for mobile
1195     * devices, and playback failure if no multiple instances of the
1196     * same codec is supported on a device.
1197     */
1198    public void release() {
1199        stayAwake(false);
1200        updateSurfaceScreenOn();
1201        mOnPreparedListener = null;
1202        mOnBufferingUpdateListener = null;
1203        mOnCompletionListener = null;
1204        mOnSeekCompleteListener = null;
1205        mOnErrorListener = null;
1206        mOnInfoListener = null;
1207        mOnVideoSizeChangedListener = null;
1208        mOnTimedTextListener = null;
1209        _release();
1210    }
1211
1212    private native void _release();
1213
1214    /**
1215     * Resets the MediaPlayer to its uninitialized state. After calling
1216     * this method, you will have to initialize it again by setting the
1217     * data source and calling prepare().
1218     */
1219    public void reset() {
1220        stayAwake(false);
1221        _reset();
1222        // make sure none of the listeners get called anymore
1223        mEventHandler.removeCallbacksAndMessages(null);
1224    }
1225
1226    private native void _reset();
1227
1228    /**
1229     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
1230     * for a list of stream types. Must call this method before prepare() or
1231     * prepareAsync() in order for the target stream type to become effective
1232     * thereafter.
1233     *
1234     * @param streamtype the audio stream type
1235     * @see android.media.AudioManager
1236     */
1237    public native void setAudioStreamType(int streamtype);
1238
1239    /**
1240     * Sets the player to be looping or non-looping.
1241     *
1242     * @param looping whether to loop or not
1243     */
1244    public native void setLooping(boolean looping);
1245
1246    /**
1247     * Checks whether the MediaPlayer is looping or non-looping.
1248     *
1249     * @return true if the MediaPlayer is currently looping, false otherwise
1250     */
1251    public native boolean isLooping();
1252
1253    /**
1254     * Sets the volume on this player.
1255     * This API is recommended for balancing the output of audio streams
1256     * within an application. Unless you are writing an application to
1257     * control user settings, this API should be used in preference to
1258     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
1259     * a particular type. Note that the passed volume values are raw scalars.
1260     * UI controls should be scaled logarithmically.
1261     *
1262     * @param leftVolume left volume scalar
1263     * @param rightVolume right volume scalar
1264     */
1265    public native void setVolume(float leftVolume, float rightVolume);
1266
1267    /**
1268     * Currently not implemented, returns null.
1269     * @deprecated
1270     * @hide
1271     */
1272    public native Bitmap getFrameAt(int msec) throws IllegalStateException;
1273
1274    /**
1275     * Sets the audio session ID.
1276     *
1277     * @param sessionId the audio session ID.
1278     * The audio session ID is a system wide unique identifier for the audio stream played by
1279     * this MediaPlayer instance.
1280     * The primary use of the audio session ID  is to associate audio effects to a particular
1281     * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
1282     * this effect will be applied only to the audio content of media players within the same
1283     * audio session and not to the output mix.
1284     * When created, a MediaPlayer instance automatically generates its own audio session ID.
1285     * However, it is possible to force this player to be part of an already existing audio session
1286     * by calling this method.
1287     * This method must be called before one of the overloaded <code> setDataSource </code> methods.
1288     * @throws IllegalStateException if it is called in an invalid state
1289     */
1290    public native void setAudioSessionId(int sessionId)  throws IllegalArgumentException, IllegalStateException;
1291
1292    /**
1293     * Returns the audio session ID.
1294     *
1295     * @return the audio session ID. {@see #setAudioSessionId(int)}
1296     * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
1297     */
1298    public native int getAudioSessionId();
1299
1300    /**
1301     * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1302     * effect which can be applied on any sound source that directs a certain amount of its
1303     * energy to this effect. This amount is defined by setAuxEffectSendLevel().
1304     * {@see #setAuxEffectSendLevel(float)}.
1305     * <p>After creating an auxiliary effect (e.g.
1306     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1307     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1308     * to attach the player to the effect.
1309     * <p>To detach the effect from the player, call this method with a null effect id.
1310     * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1311     * methods.
1312     * @param effectId system wide unique id of the effect to attach
1313     */
1314    public native void attachAuxEffect(int effectId);
1315
1316    /* Do not change these values (starting with KEY_PARAMETER) without updating
1317     * their counterparts in include/media/mediaplayer.h!
1318     */
1319    /*
1320     * Key used in setParameter method.
1321     * Indicates the index of the timed text track to be enabled/disabled.
1322     * The index includes both the in-band and out-of-band timed text.
1323     * The index should start from in-band text if any. Application can retrieve the number
1324     * of in-band text tracks by using MediaMetadataRetriever::extractMetadata().
1325     * Note it might take a few hundred ms to scan an out-of-band text file
1326     * before displaying it.
1327     */
1328    private static final int KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX = 1000;
1329    /*
1330     * Key used in setParameter method.
1331     * Used to add out-of-band timed text source path.
1332     * Application can add multiple text sources by calling setParameter() with
1333     * KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE multiple times.
1334     */
1335    private static final int KEY_PARAMETER_TIMED_TEXT_ADD_OUT_OF_BAND_SOURCE = 1001;
1336
1337    // There are currently no defined keys usable from Java with get*Parameter.
1338    // But if any keys are defined, the order must be kept in sync with include/media/mediaplayer.h.
1339    // private static final int KEY_PARAMETER_... = ...;
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 native boolean setParameter(int key, Parcel value);
1349
1350    /**
1351     * Sets the parameter indicated by key.
1352     * @param key key indicates the parameter to be set.
1353     * @param value value of the parameter to be set.
1354     * @return true if the parameter is set successfully, false otherwise
1355     * {@hide}
1356     */
1357    public boolean setParameter(int key, String value) {
1358        Parcel p = Parcel.obtain();
1359        p.writeString(value);
1360        boolean ret = setParameter(key, p);
1361        p.recycle();
1362        return ret;
1363    }
1364
1365    /**
1366     * Sets the parameter indicated by key.
1367     * @param key key indicates the parameter to be set.
1368     * @param value value of the parameter to be set.
1369     * @return true if the parameter is set successfully, false otherwise
1370     * {@hide}
1371     */
1372    public boolean setParameter(int key, int value) {
1373        Parcel p = Parcel.obtain();
1374        p.writeInt(value);
1375        boolean ret = setParameter(key, p);
1376        p.recycle();
1377        return ret;
1378    }
1379
1380    /**
1381     * Gets the value of the parameter indicated by key.
1382     * @param key key indicates the parameter to get.
1383     * @param reply value of the parameter to get.
1384     */
1385    private native void getParameter(int key, Parcel reply);
1386
1387    /**
1388     * Gets the value of the parameter indicated by key.
1389     * The caller is responsible for recycling the returned parcel.
1390     * @param key key indicates the parameter to get.
1391     * @return value of the parameter.
1392     * {@hide}
1393     */
1394    public Parcel getParcelParameter(int key) {
1395        Parcel p = Parcel.obtain();
1396        getParameter(key, p);
1397        return p;
1398    }
1399
1400    /**
1401     * Gets the value of the parameter indicated by key.
1402     * @param key key indicates the parameter to get.
1403     * @return value of the parameter.
1404     * {@hide}
1405     */
1406    public String getStringParameter(int key) {
1407        Parcel p = Parcel.obtain();
1408        getParameter(key, p);
1409        String ret = p.readString();
1410        p.recycle();
1411        return ret;
1412    }
1413
1414    /**
1415     * Gets the value of the parameter indicated by key.
1416     * @param key key indicates the parameter to get.
1417     * @return value of the parameter.
1418     * {@hide}
1419     */
1420    public int getIntParameter(int key) {
1421        Parcel p = Parcel.obtain();
1422        getParameter(key, p);
1423        int ret = p.readInt();
1424        p.recycle();
1425        return ret;
1426    }
1427
1428    /**
1429     * Sets the send level of the player to the attached auxiliary effect
1430     * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1431     * <p>By default the send level is 0, so even if an effect is attached to the player
1432     * this method must be called for the effect to be applied.
1433     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1434     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1435     * so an appropriate conversion from linear UI input x to level is:
1436     * x == 0 -> level = 0
1437     * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1438     * @param level send level scalar
1439     */
1440    public native void setAuxEffectSendLevel(float level);
1441
1442    /**
1443     * @param request Parcel destinated to the media player. The
1444     *                Interface token must be set to the IMediaPlayer
1445     *                one to be routed correctly through the system.
1446     * @param reply[out] Parcel that will contain the reply.
1447     * @return The status code.
1448     */
1449    private native final int native_invoke(Parcel request, Parcel reply);
1450
1451
1452    /**
1453     * @param update_only If true fetch only the set of metadata that have
1454     *                    changed since the last invocation of getMetadata.
1455     *                    The set is built using the unfiltered
1456     *                    notifications the native player sent to the
1457     *                    MediaPlayerService during that period of
1458     *                    time. If false, all the metadatas are considered.
1459     * @param apply_filter  If true, once the metadata set has been built based on
1460     *                     the value update_only, the current filter is applied.
1461     * @param reply[out] On return contains the serialized
1462     *                   metadata. Valid only if the call was successful.
1463     * @return The status code.
1464     */
1465    private native final boolean native_getMetadata(boolean update_only,
1466                                                    boolean apply_filter,
1467                                                    Parcel reply);
1468
1469    /**
1470     * @param request Parcel with the 2 serialized lists of allowed
1471     *                metadata types followed by the one to be
1472     *                dropped. Each list starts with an integer
1473     *                indicating the number of metadata type elements.
1474     * @return The status code.
1475     */
1476    private native final int native_setMetadataFilter(Parcel request);
1477
1478    private static native final void native_init();
1479    private native final void native_setup(Object mediaplayer_this);
1480    private native final void native_finalize();
1481
1482    /**
1483     * @param index The index of the text track to be turned on.
1484     * @return true if the text track is enabled successfully.
1485     * {@hide}
1486     */
1487    public boolean enableTimedTextTrackIndex(int index) {
1488        if (index < 0) {
1489            return false;
1490        }
1491        return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, index);
1492    }
1493
1494    /**
1495     * Enables the first timed text track if any.
1496     * @return true if the text track is enabled successfully
1497     * {@hide}
1498     */
1499    public boolean enableTimedText() {
1500        return enableTimedTextTrackIndex(0);
1501    }
1502
1503    /**
1504     * Disables timed text display.
1505     * @return true if the text track is disabled successfully.
1506     * {@hide}
1507     */
1508    public boolean disableTimedText() {
1509        return setParameter(KEY_PARAMETER_TIMED_TEXT_TRACK_INDEX, -1);
1510    }
1511
1512    /**
1513     * @param reply Parcel with audio/video duration info for battery
1514                    tracking usage
1515     * @return The status code.
1516     * {@hide}
1517     */
1518    public native static int native_pullBatteryData(Parcel reply);
1519
1520    @Override
1521    protected void finalize() { native_finalize(); }
1522
1523    /* Do not change these values without updating their counterparts
1524     * in include/media/mediaplayer.h!
1525     */
1526    private static final int MEDIA_NOP = 0; // interface test message
1527    private static final int MEDIA_PREPARED = 1;
1528    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
1529    private static final int MEDIA_BUFFERING_UPDATE = 3;
1530    private static final int MEDIA_SEEK_COMPLETE = 4;
1531    private static final int MEDIA_SET_VIDEO_SIZE = 5;
1532    private static final int MEDIA_TIMED_TEXT = 99;
1533    private static final int MEDIA_ERROR = 100;
1534    private static final int MEDIA_INFO = 200;
1535
1536    private class EventHandler extends Handler
1537    {
1538        private MediaPlayer mMediaPlayer;
1539
1540        public EventHandler(MediaPlayer mp, Looper looper) {
1541            super(looper);
1542            mMediaPlayer = mp;
1543        }
1544
1545        @Override
1546        public void handleMessage(Message msg) {
1547            if (mMediaPlayer.mNativeContext == 0) {
1548                Log.w(TAG, "mediaplayer went away with unhandled events");
1549                return;
1550            }
1551            switch(msg.what) {
1552            case MEDIA_PREPARED:
1553                if (mOnPreparedListener != null)
1554                    mOnPreparedListener.onPrepared(mMediaPlayer);
1555                return;
1556
1557            case MEDIA_PLAYBACK_COMPLETE:
1558                if (mOnCompletionListener != null)
1559                    mOnCompletionListener.onCompletion(mMediaPlayer);
1560                stayAwake(false);
1561                return;
1562
1563            case MEDIA_BUFFERING_UPDATE:
1564                if (mOnBufferingUpdateListener != null)
1565                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
1566                return;
1567
1568            case MEDIA_SEEK_COMPLETE:
1569              if (mOnSeekCompleteListener != null)
1570                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
1571              return;
1572
1573            case MEDIA_SET_VIDEO_SIZE:
1574              if (mOnVideoSizeChangedListener != null)
1575                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
1576              return;
1577
1578            case MEDIA_ERROR:
1579                // For PV specific error values (msg.arg2) look in
1580                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
1581                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
1582                boolean error_was_handled = false;
1583                if (mOnErrorListener != null) {
1584                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
1585                }
1586                if (mOnCompletionListener != null && ! error_was_handled) {
1587                    mOnCompletionListener.onCompletion(mMediaPlayer);
1588                }
1589                stayAwake(false);
1590                return;
1591
1592            case MEDIA_INFO:
1593                if (msg.arg1 != MEDIA_INFO_VIDEO_TRACK_LAGGING) {
1594                    Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
1595                }
1596                if (mOnInfoListener != null) {
1597                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
1598                }
1599                // No real default action so far.
1600                return;
1601            case MEDIA_TIMED_TEXT:
1602                if (mOnTimedTextListener != null) {
1603                    if (msg.obj == null) {
1604                        mOnTimedTextListener.onTimedText(mMediaPlayer, null);
1605                    } else {
1606                        if (msg.obj instanceof byte[]) {
1607                            TimedText text = new TimedText((byte[])(msg.obj));
1608                            mOnTimedTextListener.onTimedText(mMediaPlayer, text);
1609                        }
1610                    }
1611                }
1612                return;
1613
1614            case MEDIA_NOP: // interface test message - ignore
1615                break;
1616
1617            default:
1618                Log.e(TAG, "Unknown message type " + msg.what);
1619                return;
1620            }
1621        }
1622    }
1623
1624    /**
1625     * Called from native code when an interesting event happens.  This method
1626     * just uses the EventHandler system to post the event back to the main app thread.
1627     * We use a weak reference to the original MediaPlayer object so that the native
1628     * code is safe from the object disappearing from underneath it.  (This is
1629     * the cookie passed to native_setup().)
1630     */
1631    private static void postEventFromNative(Object mediaplayer_ref,
1632                                            int what, int arg1, int arg2, Object obj)
1633    {
1634        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
1635        if (mp == null) {
1636            return;
1637        }
1638
1639        if (mp.mEventHandler != null) {
1640            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1641            mp.mEventHandler.sendMessage(m);
1642        }
1643    }
1644
1645    /**
1646     * Interface definition for a callback to be invoked when the media
1647     * source is ready for playback.
1648     */
1649    public interface OnPreparedListener
1650    {
1651        /**
1652         * Called when the media file is ready for playback.
1653         *
1654         * @param mp the MediaPlayer that is ready for playback
1655         */
1656        void onPrepared(MediaPlayer mp);
1657    }
1658
1659    /**
1660     * Register a callback to be invoked when the media source is ready
1661     * for playback.
1662     *
1663     * @param listener the callback that will be run
1664     */
1665    public void setOnPreparedListener(OnPreparedListener listener)
1666    {
1667        mOnPreparedListener = listener;
1668    }
1669
1670    private OnPreparedListener mOnPreparedListener;
1671
1672    /**
1673     * Interface definition for a callback to be invoked when playback of
1674     * a media source has completed.
1675     */
1676    public interface OnCompletionListener
1677    {
1678        /**
1679         * Called when the end of a media source is reached during playback.
1680         *
1681         * @param mp the MediaPlayer that reached the end of the file
1682         */
1683        void onCompletion(MediaPlayer mp);
1684    }
1685
1686    /**
1687     * Register a callback to be invoked when the end of a media source
1688     * has been reached during playback.
1689     *
1690     * @param listener the callback that will be run
1691     */
1692    public void setOnCompletionListener(OnCompletionListener listener)
1693    {
1694        mOnCompletionListener = listener;
1695    }
1696
1697    private OnCompletionListener mOnCompletionListener;
1698
1699    /**
1700     * Interface definition of a callback to be invoked indicating buffering
1701     * status of a media resource being streamed over the network.
1702     */
1703    public interface OnBufferingUpdateListener
1704    {
1705        /**
1706         * Called to update status in buffering a media stream received through
1707         * progressive HTTP download. The received buffering percentage
1708         * indicates how much of the content has been buffered or played.
1709         * For example a buffering update of 80 percent when half the content
1710         * has already been played indicates that the next 30 percent of the
1711         * content to play has been buffered.
1712         *
1713         * @param mp      the MediaPlayer the update pertains to
1714         * @param percent the percentage (0-100) of the content
1715         *                that has been buffered or played thus far
1716         */
1717        void onBufferingUpdate(MediaPlayer mp, int percent);
1718    }
1719
1720    /**
1721     * Register a callback to be invoked when the status of a network
1722     * stream's buffer has changed.
1723     *
1724     * @param listener the callback that will be run.
1725     */
1726    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
1727    {
1728        mOnBufferingUpdateListener = listener;
1729    }
1730
1731    private OnBufferingUpdateListener mOnBufferingUpdateListener;
1732
1733    /**
1734     * Interface definition of a callback to be invoked indicating
1735     * the completion of a seek operation.
1736     */
1737    public interface OnSeekCompleteListener
1738    {
1739        /**
1740         * Called to indicate the completion of a seek operation.
1741         *
1742         * @param mp the MediaPlayer that issued the seek operation
1743         */
1744        public void onSeekComplete(MediaPlayer mp);
1745    }
1746
1747    /**
1748     * Register a callback to be invoked when a seek operation has been
1749     * completed.
1750     *
1751     * @param listener the callback that will be run
1752     */
1753    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
1754    {
1755        mOnSeekCompleteListener = listener;
1756    }
1757
1758    private OnSeekCompleteListener mOnSeekCompleteListener;
1759
1760    /**
1761     * Interface definition of a callback to be invoked when the
1762     * video size is first known or updated
1763     */
1764    public interface OnVideoSizeChangedListener
1765    {
1766        /**
1767         * Called to indicate the video size
1768         *
1769         * @param mp        the MediaPlayer associated with this callback
1770         * @param width     the width of the video
1771         * @param height    the height of the video
1772         */
1773        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
1774    }
1775
1776    /**
1777     * Register a callback to be invoked when the video size is
1778     * known or updated.
1779     *
1780     * @param listener the callback that will be run
1781     */
1782    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
1783    {
1784        mOnVideoSizeChangedListener = listener;
1785    }
1786
1787    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
1788
1789    /**
1790     * Interface definition of a callback to be invoked when a
1791     * timed text is available for display.
1792     * {@hide}
1793     */
1794    public interface OnTimedTextListener
1795    {
1796        /**
1797         * Called to indicate an avaliable timed text
1798         *
1799         * @param mp             the MediaPlayer associated with this callback
1800         * @param text           the timed text sample which contains the text
1801         *                       needed to be displayed and the display format.
1802         * {@hide}
1803         */
1804        public void onTimedText(MediaPlayer mp, TimedText text);
1805    }
1806
1807    /**
1808     * Register a callback to be invoked when a timed text is available
1809     * for display.
1810     *
1811     * @param listener the callback that will be run
1812     * {@hide}
1813     */
1814    public void setOnTimedTextListener(OnTimedTextListener listener)
1815    {
1816        mOnTimedTextListener = listener;
1817    }
1818
1819    private OnTimedTextListener mOnTimedTextListener;
1820
1821
1822    /* Do not change these values without updating their counterparts
1823     * in include/media/mediaplayer.h!
1824     */
1825    /** Unspecified media player error.
1826     * @see android.media.MediaPlayer.OnErrorListener
1827     */
1828    public static final int MEDIA_ERROR_UNKNOWN = 1;
1829
1830    /** Media server died. In this case, the application must release the
1831     * MediaPlayer object and instantiate a new one.
1832     * @see android.media.MediaPlayer.OnErrorListener
1833     */
1834    public static final int MEDIA_ERROR_SERVER_DIED = 100;
1835
1836    /** The video is streamed and its container is not valid for progressive
1837     * playback i.e the video's index (e.g moov atom) is not at the start of the
1838     * file.
1839     * @see android.media.MediaPlayer.OnErrorListener
1840     */
1841    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
1842
1843    /**
1844     * Interface definition of a callback to be invoked when there
1845     * has been an error during an asynchronous operation (other errors
1846     * will throw exceptions at method call time).
1847     */
1848    public interface OnErrorListener
1849    {
1850        /**
1851         * Called to indicate an error.
1852         *
1853         * @param mp      the MediaPlayer the error pertains to
1854         * @param what    the type of error that has occurred:
1855         * <ul>
1856         * <li>{@link #MEDIA_ERROR_UNKNOWN}
1857         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1858         * </ul>
1859         * @param extra an extra code, specific to the error. Typically
1860         * implementation dependant.
1861         * @return True if the method handled the error, false if it didn't.
1862         * Returning false, or not having an OnErrorListener at all, will
1863         * cause the OnCompletionListener to be called.
1864         */
1865        boolean onError(MediaPlayer mp, int what, int extra);
1866    }
1867
1868    /**
1869     * Register a callback to be invoked when an error has happened
1870     * during an asynchronous operation.
1871     *
1872     * @param listener the callback that will be run
1873     */
1874    public void setOnErrorListener(OnErrorListener listener)
1875    {
1876        mOnErrorListener = listener;
1877    }
1878
1879    private OnErrorListener mOnErrorListener;
1880
1881
1882    /* Do not change these values without updating their counterparts
1883     * in include/media/mediaplayer.h!
1884     */
1885    /** Unspecified media player info.
1886     * @see android.media.MediaPlayer.OnInfoListener
1887     */
1888    public static final int MEDIA_INFO_UNKNOWN = 1;
1889
1890    /** The video is too complex for the decoder: it can't decode frames fast
1891     *  enough. Possibly only the audio plays fine at this stage.
1892     * @see android.media.MediaPlayer.OnInfoListener
1893     */
1894    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
1895
1896    /** MediaPlayer is temporarily pausing playback internally in order to
1897     * buffer more data.
1898     * @see android.media.MediaPlayer.OnInfoListener
1899     */
1900    public static final int MEDIA_INFO_BUFFERING_START = 701;
1901
1902    /** MediaPlayer is resuming playback after filling buffers.
1903     * @see android.media.MediaPlayer.OnInfoListener
1904     */
1905    public static final int MEDIA_INFO_BUFFERING_END = 702;
1906
1907    /** Bad interleaving means that a media has been improperly interleaved or
1908     * not interleaved at all, e.g has all the video samples first then all the
1909     * audio ones. Video is playing but a lot of disk seeks may be happening.
1910     * @see android.media.MediaPlayer.OnInfoListener
1911     */
1912    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
1913
1914    /** The media cannot be seeked (e.g live stream)
1915     * @see android.media.MediaPlayer.OnInfoListener
1916     */
1917    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
1918
1919    /** A new set of metadata is available.
1920     * @see android.media.MediaPlayer.OnInfoListener
1921     */
1922    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
1923
1924    /**
1925     * Interface definition of a callback to be invoked to communicate some
1926     * info and/or warning about the media or its playback.
1927     */
1928    public interface OnInfoListener
1929    {
1930        /**
1931         * Called to indicate an info or a warning.
1932         *
1933         * @param mp      the MediaPlayer the info pertains to.
1934         * @param what    the type of info or warning.
1935         * <ul>
1936         * <li>{@link #MEDIA_INFO_UNKNOWN}
1937         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
1938         * <li>{@link #MEDIA_INFO_BUFFERING_START}
1939         * <li>{@link #MEDIA_INFO_BUFFERING_END}
1940         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
1941         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
1942         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
1943         * </ul>
1944         * @param extra an extra code, specific to the info. Typically
1945         * implementation dependant.
1946         * @return True if the method handled the info, false if it didn't.
1947         * Returning false, or not having an OnErrorListener at all, will
1948         * cause the info to be discarded.
1949         */
1950        boolean onInfo(MediaPlayer mp, int what, int extra);
1951    }
1952
1953    /**
1954     * Register a callback to be invoked when an info/warning is available.
1955     *
1956     * @param listener the callback that will be run
1957     */
1958    public void setOnInfoListener(OnInfoListener listener)
1959    {
1960        mOnInfoListener = listener;
1961    }
1962
1963    private OnInfoListener mOnInfoListener;
1964
1965}
1966