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