MediaPlayer.java revision 85a2c7f1cad8fd55ed72a8a3dbb2b36632ebbff3
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.media.AudioManager;
34
35import java.io.FileDescriptor;
36import java.io.IOException;
37import java.util.Set;
38import java.lang.ref.WeakReference;
39
40/**
41 * MediaPlayer class can be used to control playback
42 * of audio/video files and streams. An example on how to use the methods in
43 * this class can be found in {@link android.widget.VideoView}.
44 * Please see <a href="{@docRoot}guide/topics/media/index.html">Audio and Video</a>
45 * for additional help using MediaPlayer.
46 *
47 * <p>Topics covered here are:
48 * <ol>
49 * <li><a href="#StateDiagram">State Diagram</a>
50 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
51 * <li><a href="#Permissions">Permissions</a>
52 * </ol>
53 *
54 * <a name="StateDiagram"></a>
55 * <h3>State Diagram</h3>
56 *
57 * <p>Playback control of audio/video files and streams is managed as a state
58 * machine. The following diagram shows the life cycle and the states of a
59 * MediaPlayer object driven by the supported playback control operations.
60 * The ovals represent the states a MediaPlayer object may reside
61 * in. The arcs represent the playback control operations that drive the object
62 * state transition. There are two types of arcs. The arcs with a single arrow
63 * head represent synchronous method calls, while those with
64 * a double arrow head represent asynchronous method calls.</p>
65 *
66 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
67 *         alt="MediaPlayer State diagram"
68 *         border="0" /></p>
69 *
70 * <p>From this state diagram, one can see that a MediaPlayer object has the
71 *    following states:</p>
72 * <ul>
73 *     <li>When a MediaPlayer object is just created using <code>new</code> or
74 *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
75 *         {@link #release()} is called, it is in the <em>End</em> state. Between these
76 *         two states is the life cycle of the MediaPlayer object.
77 *         <ul>
78 *         <li>There is a subtle but important difference between a newly constructed
79 *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
80 *         is called. It is a programming error to invoke methods such
81 *         as {@link #getCurrentPosition()},
82 *         {@link #getDuration()}, {@link #getVideoHeight()},
83 *         {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
84 *         {@link #setLooping(boolean)},
85 *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
86 *         {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
87 *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
88 *         methods is called right after a MediaPlayer object is constructed,
89 *         the user supplied callback method OnErrorListener.onError() won't be
90 *         called by the internal player engine and the object state remains
91 *         unchanged; but if these methods are called right after {@link #reset()},
92 *         the user supplied callback method OnErrorListener.onError() will be
93 *         invoked by the internal player engine and the object will be
94 *         transfered to the <em>Error</em> state. </li>
95 *         <li>It is also recommended that once
96 *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
97 *         so that resources used by the internal player engine associated with the
98 *         MediaPlayer object can be released immediately. Resource may include
99 *         singleton resources such as hardware acceleration components and
100 *         failure to call {@link #release()} may cause subsequent instances of
101 *         MediaPlayer objects to fallback to software implementations or fail
102 *         altogether. Once the MediaPlayer
103 *         object is in the <em>End</em> state, it can no longer be used and
104 *         there is no way to bring it back to any other state. </li>
105 *         <li>Furthermore,
106 *         the MediaPlayer objects created using <code>new</code> is in the
107 *         <em>Idle</em> state, while those created with one
108 *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
109 *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
110 *         state if the creation using <code>create</code> method is successful.
111 *         </li>
112 *         </ul>
113 *         </li>
114 *     <li>In general, some playback control operation may fail due to various
115 *         reasons, such as unsupported audio/video format, poorly interleaved
116 *         audio/video, resolution too high, streaming timeout, and the like.
117 *         Thus, error reporting and recovery is an important concern under
118 *         these circumstances. Sometimes, due to programming errors, invoking a playback
119 *         control operation in an invalid state may also occur. Under all these
120 *         error conditions, the internal player engine invokes a user supplied
121 *         OnErrorListener.onError() method if an OnErrorListener has been
122 *         registered beforehand via
123 *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
124 *         <ul>
125 *         <li>It is important to note that once an error occurs, the
126 *         MediaPlayer object enters the <em>Error</em> state (except as noted
127 *         above), even if an error listener has not been registered by the application.</li>
128 *         <li>In order to reuse a MediaPlayer object that is in the <em>
129 *         Error</em> state and recover from the error,
130 *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
131 *         state.</li>
132 *         <li>It is good programming practice to have your application
133 *         register a OnErrorListener to look out for error notifications from
134 *         the internal player engine.</li>
135 *         <li>IlleglStateException is
136 *         thrown to prevent programming errors such as calling {@link #prepare()},
137 *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
138 *         </code> methods in an invalid state. </li>
139 *         </ul>
140 *         </li>
141 *     <li>Calling
142 *         {@link #setDataSource(FileDescriptor)}, or
143 *         {@link #setDataSource(String)}, or
144 *         {@link #setDataSource(Context, Uri)}, or
145 *         {@link #setDataSource(FileDescriptor, long, long)} transfers a
146 *         MediaPlayer object in the <em>Idle</em> state to the
147 *         <em>Initialized</em> state.
148 *         <ul>
149 *         <li>An IllegalStateException is thrown if
150 *         setDataSource() is called in any other state.</li>
151 *         <li>It is good programming
152 *         practice to always look out for <code>IllegalArgumentException</code>
153 *         and <code>IOException</code> that may be thrown from the overloaded
154 *         <code>setDataSource</code> methods.</li>
155 *         </ul>
156 *         </li>
157 *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
158 *         before playback can be started.
159 *         <ul>
160 *         <li>There are two ways (synchronous vs.
161 *         asynchronous) that the <em>Prepared</em> state can be reached:
162 *         either a call to {@link #prepare()} (synchronous) which
163 *         transfers the object to the <em>Prepared</em> state once the method call
164 *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
165 *         first transfers the object to the <em>Preparing</em> state after the
166 *         call returns (which occurs almost right way) while the internal
167 *         player engine continues working on the rest of preparation work
168 *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
169 *         the internal player engine then calls a user supplied callback method,
170 *         onPrepared() of the OnPreparedListener interface, if an
171 *         OnPreparedListener is registered beforehand via {@link
172 *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
173 *         <li>It is important to note that
174 *         the <em>Preparing</em> state is a transient state, and the behavior
175 *         of calling any method with side effect while a MediaPlayer object is
176 *         in the <em>Preparing</em> state is undefined.</li>
177 *         <li>An IllegalStateException is
178 *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
179 *         any other state.</li>
180 *         <li>While in the <em>Prepared</em> state, properties
181 *         such as audio/sound volume, screenOnWhilePlaying, looping can be
182 *         adjusted by invoking the corresponding set methods.</li>
183 *         </ul>
184 *         </li>
185 *     <li>To start the playback, {@link #start()} must be called. After
186 *         {@link #start()} returns successfully, the MediaPlayer object is in the
187 *         <em>Started</em> state. {@link #isPlaying()} can be called to test
188 *         whether the MediaPlayer object is in the <em>Started</em> state.
189 *         <ul>
190 *         <li>While in the <em>Started</em> state, the internal player engine calls
191 *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
192 *         method if a OnBufferingUpdateListener has been registered beforehand
193 *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
194 *         This callback allows applications to keep track of the buffering status
195 *         while streaming audio/video.</li>
196 *         <li>Calling {@link #start()} has not effect
197 *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
198 *         </ul>
199 *         </li>
200 *     <li>Playback can be paused and stopped, and the current playback position
201 *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
202 *         {@link #pause()} returns, the MediaPlayer object enters the
203 *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
204 *         state to the <em>Paused</em> state and vice versa happens
205 *         asynchronously in the player engine. It may take some time before
206 *         the state is updated in calls to {@link #isPlaying()}, and it can be
207 *         a number of seconds in the case of streamed content.
208 *         <ul>
209 *         <li>Calling {@link #start()} to resume playback for a paused
210 *         MediaPlayer object, and the resumed playback
211 *         position is the same as where it was paused. When the call to
212 *         {@link #start()} returns, the paused MediaPlayer object goes back to
213 *         the <em>Started</em> state.</li>
214 *         <li>Calling {@link #pause()} has no effect on
215 *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
216 *         </ul>
217 *         </li>
218 *     <li>Calling  {@link #stop()} stops playback and causes a
219 *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
220 *         </em> or <em>PlaybackCompleted</em> state to enter the
221 *         <em>Stopped</em> state.
222 *         <ul>
223 *         <li>Once in the <em>Stopped</em> state, playback cannot be started
224 *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
225 *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
226 *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
227 *         object that is already in the <em>Stopped</em> state.</li>
228 *         </ul>
229 *         </li>
230 *     <li>The playback position can be adjusted with a call to
231 *         {@link #seekTo(int)}.
232 *         <ul>
233 *         <li>Although the asynchronuous {@link #seekTo(int)}
234 *         call returns right way, the actual seek operation may take a while to
235 *         finish, especially for audio/video being streamed. When the actual
236 *         seek operation completes, the internal player engine calls a user
237 *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
238 *         has been registered beforehand via
239 *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
240 *         <li>Please
241 *         note that {@link #seekTo(int)} can also be called in the other states,
242 *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
243 *         </em> state.</li>
244 *         <li>Furthermore, the actual current playback position
245 *         can be retrieved with a call to {@link #getCurrentPosition()}, which
246 *         is helpful for applications such as a Music player that need to keep
247 *         track of the playback progress.</li>
248 *         </ul>
249 *         </li>
250 *     <li>When the playback reaches the end of stream, the playback completes.
251 *         <ul>
252 *         <li>If the looping mode was being set to <var>true</var>with
253 *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
254 *         the <em>Started</em> state.</li>
255 *         <li>If the looping mode was set to <var>false
256 *         </var>, the player engine calls a user supplied callback method,
257 *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
258 *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
259 *         The invoke of the callback signals that the object is now in the <em>
260 *         PlaybackCompleted</em> state.</li>
261 *         <li>While in the <em>PlaybackCompleted</em>
262 *         state, calling {@link #start()} can restart the playback from the
263 *         beginning of the audio/video source.</li>
264 * </ul>
265 *
266 *
267 * <a name="Valid_and_Invalid_States"></a>
268 * <h3>Valid and invalid states</h3>
269 *
270 * <table border="0" cellspacing="0" cellpadding="0">
271 * <tr><td>Method Name </p></td>
272 *     <td>Valid Sates </p></td>
273 *     <td>Invalid States </p></td>
274 *     <td>Comments </p></td></tr>
275 * <tr><td>getCurrentPosition </p></td>
276 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
277 *         PlaybackCompleted} </p></td>
278 *     <td>{Error}</p></td>
279 *     <td>Successful invoke of this method in a valid state does not change the
280 *         state. Calling this method in an invalid state transfers the object
281 *         to the <em>Error</em> state. </p></td></tr>
282 * <tr><td>getDuration </p></td>
283 *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
284 *     <td>{Idle, Initialized, Error} </p></td>
285 *     <td>Successful invoke of this method in a valid state does not change the
286 *         state. Calling this method in an invalid state transfers the object
287 *         to the <em>Error</em> state. </p></td></tr>
288 * <tr><td>getVideoHeight </p></td>
289 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
290 *         PlaybackCompleted}</p></td>
291 *     <td>{Error}</p></td>
292 *     <td>Successful invoke of this method in a valid state does not change the
293 *         state. Calling this method in an invalid state transfers the object
294 *         to the <em>Error</em> state.  </p></td></tr>
295 * <tr><td>getVideoWidth </p></td>
296 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
297 *         PlaybackCompleted}</p></td>
298 *     <td>{Error}</p></td>
299 *     <td>Successful invoke of this method in a valid state does not change
300 *         the state. Calling this method in an invalid state transfers the
301 *         object to the <em>Error</em> state. </p></td></tr>
302 * <tr><td>isPlaying </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
307 *         the state. Calling this method in an invalid state transfers the
308 *         object to the <em>Error</em> state. </p></td></tr>
309 * <tr><td>pause </p></td>
310 *     <td>{Started, Paused}</p></td>
311 *     <td>{Idle, Initialized, Prepared, Stopped, PlaybackCompleted, Error}</p></td>
312 *     <td>Successful invoke of this method in a valid state transfers the
313 *         object to the <em>Paused</em> state. Calling this method in an
314 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
315 * <tr><td>prepare </p></td>
316 *     <td>{Initialized, Stopped} </p></td>
317 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
318 *     <td>Successful invoke of this method in a valid state transfers the
319 *         object to the <em>Prepared</em> state. Calling this method in an
320 *         invalid state throws an IllegalStateException.</p></td></tr>
321 * <tr><td>prepareAsync </p></td>
322 *     <td>{Initialized, Stopped} </p></td>
323 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
324 *     <td>Successful invoke of this method in a valid state transfers the
325 *         object to the <em>Preparing</em> state. Calling this method in an
326 *         invalid state throws an IllegalStateException.</p></td></tr>
327 * <tr><td>release </p></td>
328 *     <td>any </p></td>
329 *     <td>{} </p></td>
330 *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
331 * <tr><td>reset </p></td>
332 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
333 *         PlaybackCompleted, Error}</p></td>
334 *     <td>{}</p></td>
335 *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
336 * <tr><td>seekTo </p></td>
337 *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
338 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
339 *     <td>Successful invoke of this method in a valid state does not change
340 *         the state. Calling this method in an invalid state transfers the
341 *         object to the <em>Error</em> state. </p></td></tr>
342 * <tr><td>setAudioStreamType </p></td>
343 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
344 *          PlaybackCompleted}</p></td>
345 *     <td>{Error}</p></td>
346 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
347 * <tr><td>setDataSource </p></td>
348 *     <td>{Idle} </p></td>
349 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
350 *          Error} </p></td>
351 *     <td>Successful invoke of this method in a valid state transfers the
352 *         object to the <em>Initialized</em> state. Calling this method in an
353 *         invalid state throws an IllegalStateException.</p></td></tr>
354 * <tr><td>setDisplay </p></td>
355 *     <td>any </p></td>
356 *     <td>{} </p></td>
357 *     <td>This method can be called in any state and calling it does not change
358 *         the object state. </p></td></tr>
359 * <tr><td>setLooping </p></td>
360 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
361 *         PlaybackCompleted}</p></td>
362 *     <td>{Error}</p></td>
363 *     <td>Successful invoke of this method in a valid state does not change
364 *         the state. Calling this method in an
365 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
366 * <tr><td>isLooping </p></td>
367 *     <td>any </p></td>
368 *     <td>{} </p></td>
369 *     <td>This method can be called in any state and calling it does not change
370 *         the object state. </p></td></tr>
371 * <tr><td>setOnBufferingUpdateListener </p></td>
372 *     <td>any </p></td>
373 *     <td>{} </p></td>
374 *     <td>This method can be called in any state and calling it does not change
375 *         the object state. </p></td></tr>
376 * <tr><td>setOnCompletionListener </p></td>
377 *     <td>any </p></td>
378 *     <td>{} </p></td>
379 *     <td>This method can be called in any state and calling it does not change
380 *         the object state. </p></td></tr>
381 * <tr><td>setOnErrorListener </p></td>
382 *     <td>any </p></td>
383 *     <td>{} </p></td>
384 *     <td>This method can be called in any state and calling it does not change
385 *         the object state. </p></td></tr>
386 * <tr><td>setOnPreparedListener </p></td>
387 *     <td>any </p></td>
388 *     <td>{} </p></td>
389 *     <td>This method can be called in any state and calling it does not change
390 *         the object state. </p></td></tr>
391 * <tr><td>setOnSeekCompleteListener </p></td>
392 *     <td>any </p></td>
393 *     <td>{} </p></td>
394 *     <td>This method can be called in any state and calling it does not change
395 *         the object state. </p></td></tr>
396 * <tr><td>setScreenOnWhilePlaying</></td>
397 *     <td>any </p></td>
398 *     <td>{} </p></td>
399 *     <td>This method can be called in any state and calling it does not change
400 *         the object state.  </p></td></tr>
401 * <tr><td>setVolume </p></td>
402 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
403 *          PlaybackCompleted}</p></td>
404 *     <td>{Error}</p></td>
405 *     <td>Successful invoke of this method does not change the state.
406 * <tr><td>setWakeMode </p></td>
407 *     <td>any </p></td>
408 *     <td>{} </p></td>
409 *     <td>This method can be called in any state and calling it does not change
410 *         the object state.</p></td></tr>
411 * <tr><td>start </p></td>
412 *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
413 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
414 *     <td>Successful invoke of this method in a valid state transfers the
415 *         object to the <em>Started</em> state. Calling this method in an
416 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
417 * <tr><td>stop </p></td>
418 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
419 *     <td>{Idle, Initialized, Error}</p></td>
420 *     <td>Successful invoke of this method in a valid state transfers the
421 *         object to the <em>Stopped</em> state. Calling this method in an
422 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
423 * </table>
424 *
425 * <a name="Permissions"></a>
426 * <h3>Permissions</h3>
427 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
428 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
429 * element.
430 *
431 */
432public class MediaPlayer
433{
434    /**
435       Constant to retrieve only the new metadata since the last
436       call.
437       // FIXME: unhide.
438       // FIXME: add link to getMetadata(boolean, boolean)
439       {@hide}
440     */
441    public static final boolean METADATA_UPDATE_ONLY = true;
442
443    /**
444       Constant to retrieve all the metadata.
445       // FIXME: unhide.
446       // FIXME: add link to getMetadata(boolean, boolean)
447       {@hide}
448     */
449    public static final boolean METADATA_ALL = false;
450
451    /**
452       Constant to enable the metadata filter during retrieval.
453       // FIXME: unhide.
454       // FIXME: add link to getMetadata(boolean, boolean)
455       {@hide}
456     */
457    public static final boolean APPLY_METADATA_FILTER = true;
458
459    /**
460       Constant to disable the metadata filter during retrieval.
461       // FIXME: unhide.
462       // FIXME: add link to getMetadata(boolean, boolean)
463       {@hide}
464     */
465    public static final boolean BYPASS_METADATA_FILTER = false;
466
467    static {
468        System.loadLibrary("media_jni");
469        native_init();
470    }
471
472    private final static String TAG = "MediaPlayer";
473    // Name of the remote interface for the media player. Must be kept
474    // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
475    // macro invocation in IMediaPlayer.cpp
476    private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
477
478    private int mNativeContext; // accessed by native methods
479    private int mListenerContext; // accessed by native methods
480    private Surface mSurface; // accessed by native methods
481    private SurfaceHolder  mSurfaceHolder;
482    private EventHandler mEventHandler;
483    private PowerManager.WakeLock mWakeLock = null;
484    private boolean mScreenOnWhilePlaying;
485    private boolean mStayAwake;
486
487    /**
488     * Default constructor. Consider using one of the create() methods for
489     * synchronously instantiating a MediaPlayer from a Uri or resource.
490     * <p>When done with the MediaPlayer, you should call  {@link #release()},
491     * to free the resources. If not released, too many MediaPlayer instances may
492     * result in an exception.</p>
493     */
494    public MediaPlayer() {
495
496        Looper looper;
497        if ((looper = Looper.myLooper()) != null) {
498            mEventHandler = new EventHandler(this, looper);
499        } else if ((looper = Looper.getMainLooper()) != null) {
500            mEventHandler = new EventHandler(this, looper);
501        } else {
502            mEventHandler = null;
503        }
504
505        /* Native setup requires a weak reference to our object.
506         * It's easier to create it here than in C++.
507         */
508        native_setup(new WeakReference<MediaPlayer>(this));
509    }
510
511    /*
512     * Update the MediaPlayer ISurface. Call after updating mSurface.
513     */
514    private native void _setVideoSurface();
515
516    /**
517     * Create a request parcel which can be routed to the native media
518     * player using {@link #invoke(Parcel, Parcel)}. The Parcel
519     * returned has the proper InterfaceToken set. The caller should
520     * not overwrite that token, i.e it can only append data to the
521     * Parcel.
522     *
523     * @return A parcel suitable to hold a request for the native
524     * player.
525     */
526    public Parcel newRequest() {
527        Parcel parcel = Parcel.obtain();
528        parcel.writeInterfaceToken(IMEDIA_PLAYER);
529        return parcel;
530    }
531
532    /**
533     * Invoke a generic method on the native player using opaque
534     * parcels for the request and reply. Both payloads' format is a
535     * convention between the java caller and the native player.
536     * Must be called after setDataSource to make sure a native player
537     * exists.
538     *
539     * @param request Parcel with the data for the extension. The
540     * caller must use {@link #newRequest()} to get one.
541     *
542     * @param reply Output parcel with the data returned by the
543     * native player.
544     *
545     * @return The status code see utils/Errors.h
546     */
547    public int invoke(Parcel request, Parcel reply) {
548        int retcode = native_invoke(request, reply);
549        reply.setDataPosition(0);
550        return retcode;
551    }
552
553    /**
554     * Sets the SurfaceHolder to use for displaying the video portion of the media.
555     * This call is optional. Not calling it when playing back a video will
556     * result in only the audio track being played.
557     *
558     * @param sh the SurfaceHolder to use for video display
559     */
560    public void setDisplay(SurfaceHolder sh) {
561        mSurfaceHolder = sh;
562        if (sh != null) {
563            mSurface = sh.getSurface();
564        } else {
565            mSurface = null;
566        }
567        _setVideoSurface();
568        updateSurfaceScreenOn();
569    }
570
571    /**
572     * Convenience method to create a MediaPlayer for a given Uri.
573     * On success, {@link #prepare()} will already have been called and must not be called again.
574     * <p>When done with the MediaPlayer, you should call  {@link #release()},
575     * to free the resources. If not released, too many MediaPlayer instances will
576     * result in an exception.</p>
577     *
578     * @param context the Context to use
579     * @param uri the Uri from which to get the datasource
580     * @return a MediaPlayer object, or null if creation failed
581     */
582    public static MediaPlayer create(Context context, Uri uri) {
583        return create (context, uri, null);
584    }
585
586    /**
587     * Convenience method to create a MediaPlayer for a given Uri.
588     * On success, {@link #prepare()} will already have been called and must not be called again.
589     * <p>When done with the MediaPlayer, you should call  {@link #release()},
590     * to free the resources. If not released, too many MediaPlayer instances will
591     * result in an exception.</p>
592     *
593     * @param context the Context to use
594     * @param uri the Uri from which to get the datasource
595     * @param holder the SurfaceHolder to use for displaying the video
596     * @return a MediaPlayer object, or null if creation failed
597     */
598    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
599
600        try {
601            MediaPlayer mp = new MediaPlayer();
602            mp.setDataSource(context, uri);
603            if (holder != null) {
604                mp.setDisplay(holder);
605            }
606            mp.prepare();
607            return mp;
608        } catch (IOException ex) {
609            Log.d(TAG, "create failed:", ex);
610            // fall through
611        } catch (IllegalArgumentException ex) {
612            Log.d(TAG, "create failed:", ex);
613            // fall through
614        } catch (SecurityException ex) {
615            Log.d(TAG, "create failed:", ex);
616            // fall through
617        }
618
619        return null;
620    }
621
622    /**
623     * Convenience method to create a MediaPlayer for a given resource id.
624     * On success, {@link #prepare()} will already have been called and must not be called again.
625     * <p>When done with the MediaPlayer, you should call  {@link #release()},
626     * to free the resources. If not released, too many MediaPlayer instances will
627     * result in an exception.</p>
628     *
629     * @param context the Context to use
630     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
631     *              the resource to use as the datasource
632     * @return a MediaPlayer object, or null if creation failed
633     */
634    public static MediaPlayer create(Context context, int resid) {
635        try {
636            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
637            if (afd == null) return null;
638
639            MediaPlayer mp = new MediaPlayer();
640            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
641            afd.close();
642            mp.prepare();
643            return mp;
644        } catch (IOException ex) {
645            Log.d(TAG, "create failed:", ex);
646            // fall through
647        } catch (IllegalArgumentException ex) {
648            Log.d(TAG, "create failed:", ex);
649           // fall through
650        } catch (SecurityException ex) {
651            Log.d(TAG, "create failed:", ex);
652            // fall through
653        }
654        return null;
655    }
656
657    /**
658     * Sets the data source as a content Uri.
659     *
660     * @param context the Context to use when resolving the Uri
661     * @param uri the Content URI of the data you want to play
662     * @throws IllegalStateException if it is called in an invalid state
663     */
664    public void setDataSource(Context context, Uri uri)
665        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
666
667        String scheme = uri.getScheme();
668        if(scheme == null || scheme.equals("file")) {
669            setDataSource(uri.getPath());
670            return;
671        }
672
673        AssetFileDescriptor fd = null;
674        try {
675            ContentResolver resolver = context.getContentResolver();
676            fd = resolver.openAssetFileDescriptor(uri, "r");
677            if (fd == null) {
678                return;
679            }
680            // Note: using getDeclaredLength so that our behavior is the same
681            // as previous versions when the content provider is returning
682            // a full file.
683            if (fd.getDeclaredLength() < 0) {
684                setDataSource(fd.getFileDescriptor());
685            } else {
686                setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
687            }
688            return;
689        } catch (SecurityException ex) {
690        } catch (IOException ex) {
691        } finally {
692            if (fd != null) {
693                fd.close();
694            }
695        }
696        Log.d(TAG, "Couldn't open file on client side, trying server side");
697        setDataSource(uri.toString());
698        return;
699    }
700
701    /**
702     * Sets the data source (file-path or http/rtsp URL) to use.
703     *
704     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
705     * @throws IllegalStateException if it is called in an invalid state
706     */
707    public native void setDataSource(String path) throws IOException, IllegalArgumentException, IllegalStateException;
708
709    /**
710     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
711     * to close the file descriptor. It is safe to do so as soon as this call returns.
712     *
713     * @param fd the FileDescriptor for the file you want to play
714     * @throws IllegalStateException if it is called in an invalid state
715     */
716    public void setDataSource(FileDescriptor fd)
717            throws IOException, IllegalArgumentException, IllegalStateException {
718        // intentionally less than LONG_MAX
719        setDataSource(fd, 0, 0x7ffffffffffffffL);
720    }
721
722    /**
723     * Sets the data source (FileDescriptor) to use.  The FileDescriptor must be
724     * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
725     * to close the file descriptor. It is safe to do so as soon as this call returns.
726     *
727     * @param fd the FileDescriptor for the file you want to play
728     * @param offset the offset into the file where the data to be played starts, in bytes
729     * @param length the length in bytes of the data to be played
730     * @throws IllegalStateException if it is called in an invalid state
731     */
732    public native void setDataSource(FileDescriptor fd, long offset, long length)
733            throws IOException, IllegalArgumentException, IllegalStateException;
734
735    /**
736     * Prepares the player for playback, synchronously.
737     *
738     * After setting the datasource and the display surface, you need to either
739     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
740     * which blocks until MediaPlayer is ready for playback.
741     *
742     * @throws IllegalStateException if it is called in an invalid state
743     */
744    public native void prepare() throws IOException, IllegalStateException;
745
746    /**
747     * Prepares the player for playback, asynchronously.
748     *
749     * After setting the datasource and the display surface, you need to either
750     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
751     * which returns immediately, rather than blocking until enough data has been
752     * buffered.
753     *
754     * @throws IllegalStateException if it is called in an invalid state
755     */
756    public native void prepareAsync() throws IllegalStateException;
757
758    /**
759     * Starts or resumes playback. If playback had previously been paused,
760     * playback will continue from where it was paused. If playback had
761     * been stopped, or never started before, playback will start at the
762     * beginning.
763     *
764     * @throws IllegalStateException if it is called in an invalid state
765     */
766    public  void start() throws IllegalStateException {
767        stayAwake(true);
768        _start();
769    }
770
771    private native void _start() throws IllegalStateException;
772
773    /**
774     * Stops playback after playback has been stopped or paused.
775     *
776     * @throws IllegalStateException if the internal player engine has not been
777     * initialized.
778     */
779    public void stop() throws IllegalStateException {
780        stayAwake(false);
781        _stop();
782    }
783
784    private native void _stop() throws IllegalStateException;
785
786    /**
787     * Pauses playback. Call start() to resume.
788     *
789     * @throws IllegalStateException if the internal player engine has not been
790     * initialized.
791     */
792    public void pause() throws IllegalStateException {
793        stayAwake(false);
794        _pause();
795    }
796
797    private native void _pause() throws IllegalStateException;
798
799    /**
800     * Set the low-level power management behavior for this MediaPlayer.  This
801     * can be used when the MediaPlayer is not playing through a SurfaceHolder
802     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
803     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
804     *
805     * <p>This function has the MediaPlayer access the low-level power manager
806     * service to control the device's power usage while playing is occurring.
807     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
808     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
809     * permission.
810     * By default, no attempt is made to keep the device awake during playback.
811     *
812     * @param context the Context to use
813     * @param mode    the power/wake mode to set
814     * @see android.os.PowerManager
815     */
816    public void setWakeMode(Context context, int mode) {
817        boolean washeld = false;
818        if (mWakeLock != null) {
819            if (mWakeLock.isHeld()) {
820                washeld = true;
821                mWakeLock.release();
822            }
823            mWakeLock = null;
824        }
825
826        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
827        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
828        mWakeLock.setReferenceCounted(false);
829        if (washeld) {
830            mWakeLock.acquire();
831        }
832    }
833
834    /**
835     * Control whether we should use the attached SurfaceHolder to keep the
836     * screen on while video playback is occurring.  This is the preferred
837     * method over {@link #setWakeMode} where possible, since it doesn't
838     * require that the application have permission for low-level wake lock
839     * access.
840     *
841     * @param screenOn Supply true to keep the screen on, false to allow it
842     * to turn off.
843     */
844    public void setScreenOnWhilePlaying(boolean screenOn) {
845        if (mScreenOnWhilePlaying != screenOn) {
846            mScreenOnWhilePlaying = screenOn;
847            updateSurfaceScreenOn();
848        }
849    }
850
851    private void stayAwake(boolean awake) {
852        if (mWakeLock != null) {
853            if (awake && !mWakeLock.isHeld()) {
854                mWakeLock.acquire();
855            } else if (!awake && mWakeLock.isHeld()) {
856                mWakeLock.release();
857            }
858        }
859        mStayAwake = awake;
860        updateSurfaceScreenOn();
861    }
862
863    private void updateSurfaceScreenOn() {
864        if (mSurfaceHolder != null) {
865            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
866        }
867    }
868
869    /**
870     * Returns the width of the video.
871     *
872     * @return the width of the video, or 0 if there is no video,
873     * no display surface was set, or prepare()/prepareAsync()
874     * have not completed yet
875     */
876    public native int getVideoWidth();
877
878    /**
879     * Returns the height of the video.
880     *
881     * @return the height of the video, or 0 if there is no video,
882     * no display surface was set, or prepare()/prepareAsync()
883     * have not completed yet
884     */
885    public native int getVideoHeight();
886
887    /**
888     * Checks whether the MediaPlayer is playing.
889     *
890     * @return true if currently playing, false otherwise
891     */
892    public native boolean isPlaying();
893
894    /**
895     * Seeks to specified time position.
896     *
897     * @param msec the offset in milliseconds from the start to seek to
898     * @throws IllegalStateException if the internal player engine has not been
899     * initialized
900     */
901    public native void seekTo(int msec) throws IllegalStateException;
902
903    /**
904     * Gets the current playback position.
905     *
906     * @return the current position in milliseconds
907     */
908    public native int getCurrentPosition();
909
910    /**
911     * Gets the duration of the file.
912     *
913     * @return the duration in milliseconds
914     */
915    public native int getDuration();
916
917    /**
918     * Gets the media metadata.
919     *
920     * @param update_only controls whether the full set of available
921     * metadata is returned or just the set that changed since the
922     * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
923     * #METADATA_ALL}.
924     *
925     * @param apply_filter if true only metadata that matches the
926     * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
927     * #BYPASS_METADATA_FILTER}.
928     *
929     * @return The metadata, possibly empty. null if an error occured.
930     // FIXME: unhide.
931     * {@hide}
932     */
933    public Metadata getMetadata(final boolean update_only,
934                                final boolean apply_filter) {
935        Parcel reply = Parcel.obtain();
936        Metadata data = new Metadata();
937
938        if (!native_getMetadata(update_only, apply_filter, reply)) {
939            reply.recycle();
940            return null;
941        }
942
943        // Metadata takes over the parcel, don't recycle it unless
944        // there is an error.
945        if (!data.parse(reply)) {
946            reply.recycle();
947            return null;
948        }
949        return data;
950    }
951
952    /**
953     * Set a filter for the metadata update notification and update
954     * retrieval. The caller provides 2 set of metadata keys, allowed
955     * and blocked. The blocked set always takes precedence over the
956     * allowed one.
957     * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
958     * shorthands to allow/block all or no metadata.
959     *
960     * By default, there is no filter set.
961     *
962     * @param allow Is the set of metadata the client is interested
963     *              in receiving new notifications for.
964     * @param block Is the set of metadata the client is not interested
965     *              in receiving new notifications for.
966     * @return The call status code.
967     *
968     // FIXME: unhide.
969     * {@hide}
970     */
971    public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
972        // Do our serialization manually instead of calling
973        // Parcel.writeArray since the sets are made of the same type
974        // we avoid paying the price of calling writeValue (used by
975        // writeArray) which burns an extra int per element to encode
976        // the type.
977        Parcel request =  newRequest();
978
979        // The parcel starts already with an interface token. There
980        // are 2 filters. Each one starts with a 4bytes number to
981        // store the len followed by a number of int (4 bytes as well)
982        // representing the metadata type.
983        int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
984
985        if (request.dataCapacity() < capacity) {
986            request.setDataCapacity(capacity);
987        }
988
989        request.writeInt(allow.size());
990        for(Integer t: allow) {
991            request.writeInt(t);
992        }
993        request.writeInt(block.size());
994        for(Integer t: block) {
995            request.writeInt(t);
996        }
997        return native_setMetadataFilter(request);
998    }
999
1000    /**
1001     * Releases resources associated with this MediaPlayer object.
1002     * It is considered good practice to call this method when you're
1003     * done using the MediaPlayer.
1004     */
1005    public void release() {
1006        stayAwake(false);
1007        updateSurfaceScreenOn();
1008        mOnPreparedListener = null;
1009        mOnBufferingUpdateListener = null;
1010        mOnCompletionListener = null;
1011        mOnSeekCompleteListener = null;
1012        mOnErrorListener = null;
1013        mOnInfoListener = null;
1014        mOnVideoSizeChangedListener = null;
1015        _release();
1016    }
1017
1018    private native void _release();
1019
1020    /**
1021     * Resets the MediaPlayer to its uninitialized state. After calling
1022     * this method, you will have to initialize it again by setting the
1023     * data source and calling prepare().
1024     */
1025    public void reset() {
1026        stayAwake(false);
1027        _reset();
1028        // make sure none of the listeners get called anymore
1029        mEventHandler.removeCallbacksAndMessages(null);
1030    }
1031
1032    private native void _reset();
1033
1034    /**
1035     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
1036     * for a list of stream types.
1037     *
1038     * @param streamtype the audio stream type
1039     * @see android.media.AudioManager
1040     */
1041    public native void setAudioStreamType(int streamtype);
1042
1043    /**
1044     * Sets the player to be looping or non-looping.
1045     *
1046     * @param looping whether to loop or not
1047     */
1048    public native void setLooping(boolean looping);
1049
1050    /**
1051     * Checks whether the MediaPlayer is looping or non-looping.
1052     *
1053     * @return true if the MediaPlayer is currently looping, false otherwise
1054     */
1055    public native boolean isLooping();
1056
1057    /**
1058     * Sets the volume on this player.
1059     * This API is recommended for balancing the output of audio streams
1060     * within an application. Unless you are writing an application to
1061     * control user settings, this API should be used in preference to
1062     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
1063     * a particular type. Note that the passed volume values are raw scalars.
1064     * UI controls should be scaled logarithmically.
1065     *
1066     * @param leftVolume left volume scalar
1067     * @param rightVolume right volume scalar
1068     */
1069    public native void setVolume(float leftVolume, float rightVolume);
1070
1071    /**
1072     * Currently not implemented, returns null.
1073     * @deprecated
1074     * @hide
1075     */
1076    public native Bitmap getFrameAt(int msec) throws IllegalStateException;
1077
1078    /**
1079     * @param request Parcel destinated to the media player. The
1080     *                Interface token must be set to the IMediaPlayer
1081     *                one to be routed correctly through the system.
1082     * @param reply[out] Parcel that will contain the reply.
1083     * @return The status code.
1084     */
1085    private native final int native_invoke(Parcel request, Parcel reply);
1086
1087
1088    /**
1089     * @param update_only If true fetch only the set of metadata that have
1090     *                    changed since the last invocation of getMetadata.
1091     *                    The set is built using the unfiltered
1092     *                    notifications the native player sent to the
1093     *                    MediaPlayerService during that period of
1094     *                    time. If false, all the metadatas are considered.
1095     * @param apply_filter  If true, once the metadata set has been built based on
1096     *                     the value update_only, the current filter is applied.
1097     * @param reply[out] On return contains the serialized
1098     *                   metadata. Valid only if the call was successful.
1099     * @return The status code.
1100     */
1101    private native final boolean native_getMetadata(boolean update_only,
1102                                                    boolean apply_filter,
1103                                                    Parcel reply);
1104
1105    /**
1106     * @param request Parcel with the 2 serialized lists of allowed
1107     *                metadata types followed by the one to be
1108     *                dropped. Each list starts with an integer
1109     *                indicating the number of metadata type elements.
1110     * @return The status code.
1111     */
1112    private native final int native_setMetadataFilter(Parcel request);
1113
1114    private static native final void native_init();
1115    private native final void native_setup(Object mediaplayer_this);
1116    private native final void native_finalize();
1117
1118    @Override
1119    protected void finalize() { native_finalize(); }
1120
1121    /* Do not change these values without updating their counterparts
1122     * in include/media/mediaplayer.h!
1123     */
1124    private static final int MEDIA_NOP = 0; // interface test message
1125    private static final int MEDIA_PREPARED = 1;
1126    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
1127    private static final int MEDIA_BUFFERING_UPDATE = 3;
1128    private static final int MEDIA_SEEK_COMPLETE = 4;
1129    private static final int MEDIA_SET_VIDEO_SIZE = 5;
1130    private static final int MEDIA_ERROR = 100;
1131    private static final int MEDIA_INFO = 200;
1132
1133    private class EventHandler extends Handler
1134    {
1135        private MediaPlayer mMediaPlayer;
1136
1137        public EventHandler(MediaPlayer mp, Looper looper) {
1138            super(looper);
1139            mMediaPlayer = mp;
1140        }
1141
1142        @Override
1143        public void handleMessage(Message msg) {
1144            if (mMediaPlayer.mNativeContext == 0) {
1145                Log.w(TAG, "mediaplayer went away with unhandled events");
1146                return;
1147            }
1148            switch(msg.what) {
1149            case MEDIA_PREPARED:
1150                if (mOnPreparedListener != null)
1151                    mOnPreparedListener.onPrepared(mMediaPlayer);
1152                return;
1153
1154            case MEDIA_PLAYBACK_COMPLETE:
1155                if (mOnCompletionListener != null)
1156                    mOnCompletionListener.onCompletion(mMediaPlayer);
1157                stayAwake(false);
1158                return;
1159
1160            case MEDIA_BUFFERING_UPDATE:
1161                if (mOnBufferingUpdateListener != null)
1162                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
1163                return;
1164
1165            case MEDIA_SEEK_COMPLETE:
1166              if (mOnSeekCompleteListener != null)
1167                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
1168              return;
1169
1170            case MEDIA_SET_VIDEO_SIZE:
1171              if (mOnVideoSizeChangedListener != null)
1172                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
1173              return;
1174
1175            case MEDIA_ERROR:
1176                // For PV specific error values (msg.arg2) look in
1177                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
1178                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
1179                boolean error_was_handled = false;
1180                if (mOnErrorListener != null) {
1181                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
1182                }
1183                if (mOnCompletionListener != null && ! error_was_handled) {
1184                    mOnCompletionListener.onCompletion(mMediaPlayer);
1185                }
1186                stayAwake(false);
1187                return;
1188
1189            case MEDIA_INFO:
1190                // For PV specific code values (msg.arg2) look in
1191                // opencore/pvmi/pvmf/include/pvmf_return_codes.h
1192                Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
1193                if (mOnInfoListener != null) {
1194                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
1195                }
1196                // No real default action so far.
1197                return;
1198
1199            case MEDIA_NOP: // interface test message - ignore
1200                break;
1201
1202            default:
1203                Log.e(TAG, "Unknown message type " + msg.what);
1204                return;
1205            }
1206        }
1207    }
1208
1209    /**
1210     * Called from native code when an interesting event happens.  This method
1211     * just uses the EventHandler system to post the event back to the main app thread.
1212     * We use a weak reference to the original MediaPlayer object so that the native
1213     * code is safe from the object disappearing from underneath it.  (This is
1214     * the cookie passed to native_setup().)
1215     */
1216    private static void postEventFromNative(Object mediaplayer_ref,
1217                                            int what, int arg1, int arg2, Object obj)
1218    {
1219        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
1220        if (mp == null) {
1221            return;
1222        }
1223
1224        if (mp.mEventHandler != null) {
1225            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
1226            mp.mEventHandler.sendMessage(m);
1227        }
1228    }
1229
1230    /**
1231     * Interface definition for a callback to be invoked when the media
1232     * source is ready for playback.
1233     */
1234    public interface OnPreparedListener
1235    {
1236        /**
1237         * Called when the media file is ready for playback.
1238         *
1239         * @param mp the MediaPlayer that is ready for playback
1240         */
1241        void onPrepared(MediaPlayer mp);
1242    }
1243
1244    /**
1245     * Register a callback to be invoked when the media source is ready
1246     * for playback.
1247     *
1248     * @param listener the callback that will be run
1249     */
1250    public void setOnPreparedListener(OnPreparedListener listener)
1251    {
1252        mOnPreparedListener = listener;
1253    }
1254
1255    private OnPreparedListener mOnPreparedListener;
1256
1257    /**
1258     * Interface definition for a callback to be invoked when playback of
1259     * a media source has completed.
1260     */
1261    public interface OnCompletionListener
1262    {
1263        /**
1264         * Called when the end of a media source is reached during playback.
1265         *
1266         * @param mp the MediaPlayer that reached the end of the file
1267         */
1268        void onCompletion(MediaPlayer mp);
1269    }
1270
1271    /**
1272     * Register a callback to be invoked when the end of a media source
1273     * has been reached during playback.
1274     *
1275     * @param listener the callback that will be run
1276     */
1277    public void setOnCompletionListener(OnCompletionListener listener)
1278    {
1279        mOnCompletionListener = listener;
1280    }
1281
1282    private OnCompletionListener mOnCompletionListener;
1283
1284    /**
1285     * Interface definition of a callback to be invoked indicating buffering
1286     * status of a media resource being streamed over the network.
1287     */
1288    public interface OnBufferingUpdateListener
1289    {
1290        /**
1291         * Called to update status in buffering a media stream.
1292         *
1293         * @param mp      the MediaPlayer the update pertains to
1294         * @param percent the percentage (0-100) of the buffer
1295         *                that has been filled thus far
1296         */
1297        void onBufferingUpdate(MediaPlayer mp, int percent);
1298    }
1299
1300    /**
1301     * Register a callback to be invoked when the status of a network
1302     * stream's buffer has changed.
1303     *
1304     * @param listener the callback that will be run.
1305     */
1306    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
1307    {
1308        mOnBufferingUpdateListener = listener;
1309    }
1310
1311    private OnBufferingUpdateListener mOnBufferingUpdateListener;
1312
1313    /**
1314     * Interface definition of a callback to be invoked indicating
1315     * the completion of a seek operation.
1316     */
1317    public interface OnSeekCompleteListener
1318    {
1319        /**
1320         * Called to indicate the completion of a seek operation.
1321         *
1322         * @param mp the MediaPlayer that issued the seek operation
1323         */
1324        public void onSeekComplete(MediaPlayer mp);
1325    }
1326
1327    /**
1328     * Register a callback to be invoked when a seek operation has been
1329     * completed.
1330     *
1331     * @param listener the callback that will be run
1332     */
1333    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
1334    {
1335        mOnSeekCompleteListener = listener;
1336    }
1337
1338    private OnSeekCompleteListener mOnSeekCompleteListener;
1339
1340    /**
1341     * Interface definition of a callback to be invoked when the
1342     * video size is first known or updated
1343     */
1344    public interface OnVideoSizeChangedListener
1345    {
1346        /**
1347         * Called to indicate the video size
1348         *
1349         * @param mp        the MediaPlayer associated with this callback
1350         * @param width     the width of the video
1351         * @param height    the height of the video
1352         */
1353        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
1354    }
1355
1356    /**
1357     * Register a callback to be invoked when the video size is
1358     * known or updated.
1359     *
1360     * @param listener the callback that will be run
1361     */
1362    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
1363    {
1364        mOnVideoSizeChangedListener = listener;
1365    }
1366
1367    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
1368
1369    /* Do not change these values without updating their counterparts
1370     * in include/media/mediaplayer.h!
1371     */
1372    /** Unspecified media player error.
1373     * @see android.media.MediaPlayer.OnErrorListener
1374     */
1375    public static final int MEDIA_ERROR_UNKNOWN = 1;
1376
1377    /** Media server died. In this case, the application must release the
1378     * MediaPlayer object and instantiate a new one.
1379     * @see android.media.MediaPlayer.OnErrorListener
1380     */
1381    public static final int MEDIA_ERROR_SERVER_DIED = 100;
1382
1383    /** The video is streamed and its container is not valid for progressive
1384     * playback i.e the video's index (e.g moov atom) is not at the start of the
1385     * file.
1386     * @see android.media.MediaPlayer.OnErrorListener
1387     */
1388    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
1389
1390    /**
1391     * Interface definition of a callback to be invoked when there
1392     * has been an error during an asynchronous operation (other errors
1393     * will throw exceptions at method call time).
1394     */
1395    public interface OnErrorListener
1396    {
1397        /**
1398         * Called to indicate an error.
1399         *
1400         * @param mp      the MediaPlayer the error pertains to
1401         * @param what    the type of error that has occurred:
1402         * <ul>
1403         * <li>{@link #MEDIA_ERROR_UNKNOWN}
1404         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
1405         * </ul>
1406         * @param extra an extra code, specific to the error. Typically
1407         * implementation dependant.
1408         * @return True if the method handled the error, false if it didn't.
1409         * Returning false, or not having an OnErrorListener at all, will
1410         * cause the OnCompletionListener to be called.
1411         */
1412        boolean onError(MediaPlayer mp, int what, int extra);
1413    }
1414
1415    /**
1416     * Register a callback to be invoked when an error has happened
1417     * during an asynchronous operation.
1418     *
1419     * @param listener the callback that will be run
1420     */
1421    public void setOnErrorListener(OnErrorListener listener)
1422    {
1423        mOnErrorListener = listener;
1424    }
1425
1426    private OnErrorListener mOnErrorListener;
1427
1428
1429    /* Do not change these values without updating their counterparts
1430     * in include/media/mediaplayer.h!
1431     */
1432    /** Unspecified media player info.
1433     * @see android.media.MediaPlayer.OnInfoListener
1434     */
1435    public static final int MEDIA_INFO_UNKNOWN = 1;
1436
1437    /** The video is too complex for the decoder: it can't decode frames fast
1438     *  enough. Possibly only the audio plays fine at this stage.
1439     * @see android.media.MediaPlayer.OnInfoListener
1440     */
1441    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
1442
1443    /** Bad interleaving means that a media has been improperly interleaved or
1444     * not interleaved at all, e.g has all the video samples first then all the
1445     * audio ones. Video is playing but a lot of disk seeks may be happening.
1446     * @see android.media.MediaPlayer.OnInfoListener
1447     */
1448    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
1449
1450    /** The media cannot be seeked (e.g live stream)
1451     * @see android.media.MediaPlayer.OnInfoListener
1452     */
1453    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
1454
1455    /** A new set of metadata is available.
1456     * @see android.media.MediaPlayer.OnInfoListener
1457     */
1458    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
1459
1460    /**
1461     * Interface definition of a callback to be invoked to communicate some
1462     * info and/or warning about the media or its playback.
1463     */
1464    public interface OnInfoListener
1465    {
1466        /**
1467         * Called to indicate an info or a warning.
1468         *
1469         * @param mp      the MediaPlayer the info pertains to.
1470         * @param what    the type of info or warning.
1471         * <ul>
1472         * <li>{@link #MEDIA_INFO_UNKNOWN}
1473         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
1474         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
1475         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
1476         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
1477         * </ul>
1478         * @param extra an extra code, specific to the info. Typically
1479         * implementation dependant.
1480         * @return True if the method handled the info, false if it didn't.
1481         * Returning false, or not having an OnErrorListener at all, will
1482         * cause the info to be discarded.
1483         */
1484        boolean onInfo(MediaPlayer mp, int what, int extra);
1485    }
1486
1487    /**
1488     * Register a callback to be invoked when an info/warning is available.
1489     *
1490     * @param listener the callback that will be run
1491     */
1492    public void setOnInfoListener(OnInfoListener listener)
1493    {
1494        mOnInfoListener = listener;
1495    }
1496
1497    private OnInfoListener mOnInfoListener;
1498}
1499