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