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