• 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.BroadcastReceiver;
20 import android.content.ContentResolver;
21 import android.content.Context;
22 import android.content.Intent;
23 import android.content.IntentFilter;
24 import android.content.res.AssetFileDescriptor;
25 import android.net.Proxy;
26 import android.net.ProxyProperties;
27 import android.net.Uri;
28 import android.os.Handler;
29 import android.os.HandlerThread;
30 import android.os.Looper;
31 import android.os.Message;
32 import android.os.Parcel;
33 import android.os.Parcelable;
34 import android.os.ParcelFileDescriptor;
35 import android.os.Process;
36 import android.os.PowerManager;
37 import android.util.Log;
38 import android.view.Surface;
39 import android.view.SurfaceHolder;
40 import android.graphics.Bitmap;
41 import android.graphics.SurfaceTexture;
42 import android.media.AudioManager;
43 import android.media.MediaFormat;
44 import android.media.MediaTimeProvider;
45 import android.media.MediaTimeProvider.OnMediaTimeListener;
46 import android.media.SubtitleController;
47 import android.media.SubtitleData;
48 
49 import java.io.File;
50 import java.io.FileDescriptor;
51 import java.io.FileInputStream;
52 import java.io.IOException;
53 import java.io.InputStream;
54 import java.lang.Runnable;
55 import java.net.InetSocketAddress;
56 import java.util.Map;
57 import java.util.Scanner;
58 import java.util.Set;
59 import java.util.Vector;
60 import java.lang.ref.WeakReference;
61 
62 /**
63  * MediaPlayer class can be used to control playback
64  * of audio/video files and streams. An example on how to use the methods in
65  * this class can be found in {@link android.widget.VideoView}.
66  *
67  * <p>Topics covered here are:
68  * <ol>
69  * <li><a href="#StateDiagram">State Diagram</a>
70  * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
71  * <li><a href="#Permissions">Permissions</a>
72  * <li><a href="#Callbacks">Register informational and error callbacks</a>
73  * </ol>
74  *
75  * <div class="special reference">
76  * <h3>Developer Guides</h3>
77  * <p>For more information about how to use MediaPlayer, read the
78  * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p>
79  * </div>
80  *
81  * <a name="StateDiagram"></a>
82  * <h3>State Diagram</h3>
83  *
84  * <p>Playback control of audio/video files and streams is managed as a state
85  * machine. The following diagram shows the life cycle and the states of a
86  * MediaPlayer object driven by the supported playback control operations.
87  * The ovals represent the states a MediaPlayer object may reside
88  * in. The arcs represent the playback control operations that drive the object
89  * state transition. There are two types of arcs. The arcs with a single arrow
90  * head represent synchronous method calls, while those with
91  * a double arrow head represent asynchronous method calls.</p>
92  *
93  * <p><img src="../../../images/mediaplayer_state_diagram.gif"
94  *         alt="MediaPlayer State diagram"
95  *         border="0" /></p>
96  *
97  * <p>From this state diagram, one can see that a MediaPlayer object has the
98  *    following states:</p>
99  * <ul>
100  *     <li>When a MediaPlayer object is just created using <code>new</code> or
101  *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
102  *         {@link #release()} is called, it is in the <em>End</em> state. Between these
103  *         two states is the life cycle of the MediaPlayer object.
104  *         <ul>
105  *         <li>There is a subtle but important difference between a newly constructed
106  *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
107  *         is called. It is a programming error to invoke methods such
108  *         as {@link #getCurrentPosition()},
109  *         {@link #getDuration()}, {@link #getVideoHeight()},
110  *         {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
111  *         {@link #setLooping(boolean)},
112  *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
113  *         {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
114  *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
115  *         methods is called right after a MediaPlayer object is constructed,
116  *         the user supplied callback method OnErrorListener.onError() won't be
117  *         called by the internal player engine and the object state remains
118  *         unchanged; but if these methods are called right after {@link #reset()},
119  *         the user supplied callback method OnErrorListener.onError() will be
120  *         invoked by the internal player engine and the object will be
121  *         transfered to the <em>Error</em> state. </li>
122  *         <li>It is also recommended that once
123  *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
124  *         so that resources used by the internal player engine associated with the
125  *         MediaPlayer object can be released immediately. Resource may include
126  *         singleton resources such as hardware acceleration components and
127  *         failure to call {@link #release()} may cause subsequent instances of
128  *         MediaPlayer objects to fallback to software implementations or fail
129  *         altogether. Once the MediaPlayer
130  *         object is in the <em>End</em> state, it can no longer be used and
131  *         there is no way to bring it back to any other state. </li>
132  *         <li>Furthermore,
133  *         the MediaPlayer objects created using <code>new</code> is in the
134  *         <em>Idle</em> state, while those created with one
135  *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
136  *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
137  *         state if the creation using <code>create</code> method is successful.
138  *         </li>
139  *         </ul>
140  *         </li>
141  *     <li>In general, some playback control operation may fail due to various
142  *         reasons, such as unsupported audio/video format, poorly interleaved
143  *         audio/video, resolution too high, streaming timeout, and the like.
144  *         Thus, error reporting and recovery is an important concern under
145  *         these circumstances. Sometimes, due to programming errors, invoking a playback
146  *         control operation in an invalid state may also occur. Under all these
147  *         error conditions, the internal player engine invokes a user supplied
148  *         OnErrorListener.onError() method if an OnErrorListener has been
149  *         registered beforehand via
150  *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
151  *         <ul>
152  *         <li>It is important to note that once an error occurs, the
153  *         MediaPlayer object enters the <em>Error</em> state (except as noted
154  *         above), even if an error listener has not been registered by the application.</li>
155  *         <li>In order to reuse a MediaPlayer object that is in the <em>
156  *         Error</em> state and recover from the error,
157  *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
158  *         state.</li>
159  *         <li>It is good programming practice to have your application
160  *         register a OnErrorListener to look out for error notifications from
161  *         the internal player engine.</li>
162  *         <li>IllegalStateException is
163  *         thrown to prevent programming errors such as calling {@link #prepare()},
164  *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
165  *         </code> methods in an invalid state. </li>
166  *         </ul>
167  *         </li>
168  *     <li>Calling
169  *         {@link #setDataSource(FileDescriptor)}, or
170  *         {@link #setDataSource(String)}, or
171  *         {@link #setDataSource(Context, Uri)}, or
172  *         {@link #setDataSource(FileDescriptor, long, long)} transfers a
173  *         MediaPlayer object in the <em>Idle</em> state to the
174  *         <em>Initialized</em> state.
175  *         <ul>
176  *         <li>An IllegalStateException is thrown if
177  *         setDataSource() is called in any other state.</li>
178  *         <li>It is good programming
179  *         practice to always look out for <code>IllegalArgumentException</code>
180  *         and <code>IOException</code> that may be thrown from the overloaded
181  *         <code>setDataSource</code> methods.</li>
182  *         </ul>
183  *         </li>
184  *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
185  *         before playback can be started.
186  *         <ul>
187  *         <li>There are two ways (synchronous vs.
188  *         asynchronous) that the <em>Prepared</em> state can be reached:
189  *         either a call to {@link #prepare()} (synchronous) which
190  *         transfers the object to the <em>Prepared</em> state once the method call
191  *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
192  *         first transfers the object to the <em>Preparing</em> state after the
193  *         call returns (which occurs almost right way) while the internal
194  *         player engine continues working on the rest of preparation work
195  *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
196  *         the internal player engine then calls a user supplied callback method,
197  *         onPrepared() of the OnPreparedListener interface, if an
198  *         OnPreparedListener is registered beforehand via {@link
199  *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
200  *         <li>It is important to note that
201  *         the <em>Preparing</em> state is a transient state, and the behavior
202  *         of calling any method with side effect while a MediaPlayer object is
203  *         in the <em>Preparing</em> state is undefined.</li>
204  *         <li>An IllegalStateException is
205  *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
206  *         any other state.</li>
207  *         <li>While in the <em>Prepared</em> state, properties
208  *         such as audio/sound volume, screenOnWhilePlaying, looping can be
209  *         adjusted by invoking the corresponding set methods.</li>
210  *         </ul>
211  *         </li>
212  *     <li>To start the playback, {@link #start()} must be called. After
213  *         {@link #start()} returns successfully, the MediaPlayer object is in the
214  *         <em>Started</em> state. {@link #isPlaying()} can be called to test
215  *         whether the MediaPlayer object is in the <em>Started</em> state.
216  *         <ul>
217  *         <li>While in the <em>Started</em> state, the internal player engine calls
218  *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
219  *         method if a OnBufferingUpdateListener has been registered beforehand
220  *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
221  *         This callback allows applications to keep track of the buffering status
222  *         while streaming audio/video.</li>
223  *         <li>Calling {@link #start()} has not effect
224  *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
225  *         </ul>
226  *         </li>
227  *     <li>Playback can be paused and stopped, and the current playback position
228  *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
229  *         {@link #pause()} returns, the MediaPlayer object enters the
230  *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
231  *         state to the <em>Paused</em> state and vice versa happens
232  *         asynchronously in the player engine. It may take some time before
233  *         the state is updated in calls to {@link #isPlaying()}, and it can be
234  *         a number of seconds in the case of streamed content.
235  *         <ul>
236  *         <li>Calling {@link #start()} to resume playback for a paused
237  *         MediaPlayer object, and the resumed playback
238  *         position is the same as where it was paused. When the call to
239  *         {@link #start()} returns, the paused MediaPlayer object goes back to
240  *         the <em>Started</em> state.</li>
241  *         <li>Calling {@link #pause()} has no effect on
242  *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
243  *         </ul>
244  *         </li>
245  *     <li>Calling  {@link #stop()} stops playback and causes a
246  *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
247  *         </em> or <em>PlaybackCompleted</em> state to enter the
248  *         <em>Stopped</em> state.
249  *         <ul>
250  *         <li>Once in the <em>Stopped</em> state, playback cannot be started
251  *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
252  *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
253  *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
254  *         object that is already in the <em>Stopped</em> state.</li>
255  *         </ul>
256  *         </li>
257  *     <li>The playback position can be adjusted with a call to
258  *         {@link #seekTo(int)}.
259  *         <ul>
260  *         <li>Although the asynchronuous {@link #seekTo(int)}
261  *         call returns right way, the actual seek operation may take a while to
262  *         finish, especially for audio/video being streamed. When the actual
263  *         seek operation completes, the internal player engine calls a user
264  *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
265  *         has been registered beforehand via
266  *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
267  *         <li>Please
268  *         note that {@link #seekTo(int)} can also be called in the other states,
269  *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
270  *         </em> state.</li>
271  *         <li>Furthermore, the actual current playback position
272  *         can be retrieved with a call to {@link #getCurrentPosition()}, which
273  *         is helpful for applications such as a Music player that need to keep
274  *         track of the playback progress.</li>
275  *         </ul>
276  *         </li>
277  *     <li>When the playback reaches the end of stream, the playback completes.
278  *         <ul>
279  *         <li>If the looping mode was being set to <var>true</var>with
280  *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
281  *         the <em>Started</em> state.</li>
282  *         <li>If the looping mode was set to <var>false
283  *         </var>, the player engine calls a user supplied callback method,
284  *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
285  *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
286  *         The invoke of the callback signals that the object is now in the <em>
287  *         PlaybackCompleted</em> state.</li>
288  *         <li>While in the <em>PlaybackCompleted</em>
289  *         state, calling {@link #start()} can restart the playback from the
290  *         beginning of the audio/video source.</li>
291  * </ul>
292  *
293  *
294  * <a name="Valid_and_Invalid_States"></a>
295  * <h3>Valid and invalid states</h3>
296  *
297  * <table border="0" cellspacing="0" cellpadding="0">
298  * <tr><td>Method Name </p></td>
299  *     <td>Valid Sates </p></td>
300  *     <td>Invalid States </p></td>
301  *     <td>Comments </p></td></tr>
302  * <tr><td>attachAuxEffect </p></td>
303  *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
304  *     <td>{Idle, Error} </p></td>
305  *     <td>This method must be called after setDataSource.
306  *     Calling it does not change the object state. </p></td></tr>
307  * <tr><td>getAudioSessionId </p></td>
308  *     <td>any </p></td>
309  *     <td>{} </p></td>
310  *     <td>This method can be called in any state and calling it does not change
311  *         the object state. </p></td></tr>
312  * <tr><td>getCurrentPosition </p></td>
313  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
314  *         PlaybackCompleted} </p></td>
315  *     <td>{Error}</p></td>
316  *     <td>Successful invoke of this method in a valid state does not change the
317  *         state. Calling this method in an invalid state transfers the object
318  *         to the <em>Error</em> state. </p></td></tr>
319  * <tr><td>getDuration </p></td>
320  *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
321  *     <td>{Idle, Initialized, Error} </p></td>
322  *     <td>Successful invoke of this method in a valid state does not change the
323  *         state. Calling this method in an invalid state transfers the object
324  *         to the <em>Error</em> state. </p></td></tr>
325  * <tr><td>getVideoHeight </p></td>
326  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
327  *         PlaybackCompleted}</p></td>
328  *     <td>{Error}</p></td>
329  *     <td>Successful invoke of this method in a valid state does not change the
330  *         state. Calling this method in an invalid state transfers the object
331  *         to the <em>Error</em> state.  </p></td></tr>
332  * <tr><td>getVideoWidth </p></td>
333  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
334  *         PlaybackCompleted}</p></td>
335  *     <td>{Error}</p></td>
336  *     <td>Successful invoke of this method in a valid state does not change
337  *         the state. Calling this method in an invalid state transfers the
338  *         object to the <em>Error</em> state. </p></td></tr>
339  * <tr><td>isPlaying </p></td>
340  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
341  *          PlaybackCompleted}</p></td>
342  *     <td>{Error}</p></td>
343  *     <td>Successful invoke of this method in a valid state does not change
344  *         the state. Calling this method in an invalid state transfers the
345  *         object to the <em>Error</em> state. </p></td></tr>
346  * <tr><td>pause </p></td>
347  *     <td>{Started, Paused, PlaybackCompleted}</p></td>
348  *     <td>{Idle, Initialized, Prepared, Stopped, Error}</p></td>
349  *     <td>Successful invoke of this method in a valid state transfers the
350  *         object to the <em>Paused</em> state. Calling this method in an
351  *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
352  * <tr><td>prepare </p></td>
353  *     <td>{Initialized, Stopped} </p></td>
354  *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
355  *     <td>Successful invoke of this method in a valid state transfers the
356  *         object to the <em>Prepared</em> state. Calling this method in an
357  *         invalid state throws an IllegalStateException.</p></td></tr>
358  * <tr><td>prepareAsync </p></td>
359  *     <td>{Initialized, Stopped} </p></td>
360  *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
361  *     <td>Successful invoke of this method in a valid state transfers the
362  *         object to the <em>Preparing</em> state. Calling this method in an
363  *         invalid state throws an IllegalStateException.</p></td></tr>
364  * <tr><td>release </p></td>
365  *     <td>any </p></td>
366  *     <td>{} </p></td>
367  *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
368  * <tr><td>reset </p></td>
369  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
370  *         PlaybackCompleted, Error}</p></td>
371  *     <td>{}</p></td>
372  *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
373  * <tr><td>seekTo </p></td>
374  *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
375  *     <td>{Idle, Initialized, Stopped, Error}</p></td>
376  *     <td>Successful invoke of this method in a valid state does not change
377  *         the state. Calling this method in an invalid state transfers the
378  *         object to the <em>Error</em> state. </p></td></tr>
379  * <tr><td>setAudioSessionId </p></td>
380  *     <td>{Idle} </p></td>
381  *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
382  *          Error} </p></td>
383  *     <td>This method must be called in idle state as the audio session ID must be known before
384  *         calling setDataSource. Calling it does not change the object state. </p></td></tr>
385  * <tr><td>setAudioStreamType </p></td>
386  *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
387  *          PlaybackCompleted}</p></td>
388  *     <td>{Error}</p></td>
389  *     <td>Successful invoke of this method does not change the state. In order for the
390  *         target audio stream type to become effective, this method must be called before
391  *         prepare() or prepareAsync().</p></td></tr>
392  * <tr><td>setAuxEffectSendLevel </p></td>
393  *     <td>any</p></td>
394  *     <td>{} </p></td>
395  *     <td>Calling this method does not change the object state. </p></td></tr>
396  * <tr><td>setDataSource </p></td>
397  *     <td>{Idle} </p></td>
398  *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
399  *          Error} </p></td>
400  *     <td>Successful invoke of this method in a valid state transfers the
401  *         object to the <em>Initialized</em> state. Calling this method in an
402  *         invalid state throws an IllegalStateException.</p></td></tr>
403  * <tr><td>setDisplay </p></td>
404  *     <td>any </p></td>
405  *     <td>{} </p></td>
406  *     <td>This method can be called in any state and calling it does not change
407  *         the object state. </p></td></tr>
408  * <tr><td>setSurface </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>setVideoScalingMode </p></td>
414  *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
415  *     <td>{Idle, Error}</p></td>
416  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
417  * <tr><td>setLooping </p></td>
418  *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
419  *         PlaybackCompleted}</p></td>
420  *     <td>{Error}</p></td>
421  *     <td>Successful invoke of this method in a valid state does not change
422  *         the state. Calling this method in an
423  *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
424  * <tr><td>isLooping </p></td>
425  *     <td>any </p></td>
426  *     <td>{} </p></td>
427  *     <td>This method can be called in any state and calling it does not change
428  *         the object state. </p></td></tr>
429  * <tr><td>setOnBufferingUpdateListener </p></td>
430  *     <td>any </p></td>
431  *     <td>{} </p></td>
432  *     <td>This method can be called in any state and calling it does not change
433  *         the object state. </p></td></tr>
434  * <tr><td>setOnCompletionListener </p></td>
435  *     <td>any </p></td>
436  *     <td>{} </p></td>
437  *     <td>This method can be called in any state and calling it does not change
438  *         the object state. </p></td></tr>
439  * <tr><td>setOnErrorListener </p></td>
440  *     <td>any </p></td>
441  *     <td>{} </p></td>
442  *     <td>This method can be called in any state and calling it does not change
443  *         the object state. </p></td></tr>
444  * <tr><td>setOnPreparedListener </p></td>
445  *     <td>any </p></td>
446  *     <td>{} </p></td>
447  *     <td>This method can be called in any state and calling it does not change
448  *         the object state. </p></td></tr>
449  * <tr><td>setOnSeekCompleteListener </p></td>
450  *     <td>any </p></td>
451  *     <td>{} </p></td>
452  *     <td>This method can be called in any state and calling it does not change
453  *         the object state. </p></td></tr>
454  * <tr><td>setScreenOnWhilePlaying</></td>
455  *     <td>any </p></td>
456  *     <td>{} </p></td>
457  *     <td>This method can be called in any state and calling it does not change
458  *         the object state.  </p></td></tr>
459  * <tr><td>setVolume </p></td>
460  *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
461  *          PlaybackCompleted}</p></td>
462  *     <td>{Error}</p></td>
463  *     <td>Successful invoke of this method does not change the state.
464  * <tr><td>setWakeMode </p></td>
465  *     <td>any </p></td>
466  *     <td>{} </p></td>
467  *     <td>This method can be called in any state and calling it does not change
468  *         the object state.</p></td></tr>
469  * <tr><td>start </p></td>
470  *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
471  *     <td>{Idle, Initialized, Stopped, Error}</p></td>
472  *     <td>Successful invoke of this method in a valid state transfers the
473  *         object to the <em>Started</em> state. Calling this method in an
474  *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
475  * <tr><td>stop </p></td>
476  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
477  *     <td>{Idle, Initialized, Error}</p></td>
478  *     <td>Successful invoke of this method in a valid state transfers the
479  *         object to the <em>Stopped</em> state. Calling this method in an
480  *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
481  * <tr><td>getTrackInfo </p></td>
482  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
483  *     <td>{Idle, Initialized, Error}</p></td>
484  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
485  * <tr><td>addTimedTextSource </p></td>
486  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
487  *     <td>{Idle, Initialized, Error}</p></td>
488  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
489  * <tr><td>selectTrack </p></td>
490  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
491  *     <td>{Idle, Initialized, Error}</p></td>
492  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
493  * <tr><td>deselectTrack </p></td>
494  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
495  *     <td>{Idle, Initialized, Error}</p></td>
496  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
497  *
498  * </table>
499  *
500  * <a name="Permissions"></a>
501  * <h3>Permissions</h3>
502  * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
503  * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
504  * element.
505  *
506  * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
507  * when used with network-based content.
508  *
509  * <a name="Callbacks"></a>
510  * <h3>Callbacks</h3>
511  * <p>Applications may want to register for informational and error
512  * events in order to be informed of some internal state update and
513  * possible runtime errors during playback or streaming. Registration for
514  * these events is done by properly setting the appropriate listeners (via calls
515  * to
516  * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
517  * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
518  * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
519  * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
520  * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
521  * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
522  * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
523  * In order to receive the respective callback
524  * associated with these listeners, applications are required to create
525  * MediaPlayer objects on a thread with its own Looper running (main UI
526  * thread by default has a Looper running).
527  *
528  */
529 public class MediaPlayer implements SubtitleController.Listener
530 {
531     /**
532        Constant to retrieve only the new metadata since the last
533        call.
534        // FIXME: unhide.
535        // FIXME: add link to getMetadata(boolean, boolean)
536        {@hide}
537      */
538     public static final boolean METADATA_UPDATE_ONLY = true;
539 
540     /**
541        Constant to retrieve all the metadata.
542        // FIXME: unhide.
543        // FIXME: add link to getMetadata(boolean, boolean)
544        {@hide}
545      */
546     public static final boolean METADATA_ALL = false;
547 
548     /**
549        Constant to enable the metadata filter during retrieval.
550        // FIXME: unhide.
551        // FIXME: add link to getMetadata(boolean, boolean)
552        {@hide}
553      */
554     public static final boolean APPLY_METADATA_FILTER = true;
555 
556     /**
557        Constant to disable the metadata filter during retrieval.
558        // FIXME: unhide.
559        // FIXME: add link to getMetadata(boolean, boolean)
560        {@hide}
561      */
562     public static final boolean BYPASS_METADATA_FILTER = false;
563 
564     static {
565         System.loadLibrary("media_jni");
native_init()566         native_init();
567     }
568 
569     private final static String TAG = "MediaPlayer";
570     // Name of the remote interface for the media player. Must be kept
571     // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
572     // macro invocation in IMediaPlayer.cpp
573     private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
574 
575     private int mNativeContext; // accessed by native methods
576     private int mNativeSurfaceTexture;  // accessed by native methods
577     private int mListenerContext; // accessed by native methods
578     private SurfaceHolder mSurfaceHolder;
579     private EventHandler mEventHandler;
580     private PowerManager.WakeLock mWakeLock = null;
581     private boolean mScreenOnWhilePlaying;
582     private boolean mStayAwake;
583 
584     /**
585      * Default constructor. Consider using one of the create() methods for
586      * synchronously instantiating a MediaPlayer from a Uri or resource.
587      * <p>When done with the MediaPlayer, you should call  {@link #release()},
588      * to free the resources. If not released, too many MediaPlayer instances may
589      * result in an exception.</p>
590      */
MediaPlayer()591     public MediaPlayer() {
592 
593         Looper looper;
594         if ((looper = Looper.myLooper()) != null) {
595             mEventHandler = new EventHandler(this, looper);
596         } else if ((looper = Looper.getMainLooper()) != null) {
597             mEventHandler = new EventHandler(this, looper);
598         } else {
599             mEventHandler = null;
600         }
601 
602         mTimeProvider = new TimeProvider(this);
603         mOutOfBandSubtitleTracks = new Vector<SubtitleTrack>();
604         mOpenSubtitleSources = new Vector<InputStream>();
605         mInbandSubtitleTracks = new SubtitleTrack[0];
606 
607         /* Native setup requires a weak reference to our object.
608          * It's easier to create it here than in C++.
609          */
610         native_setup(new WeakReference<MediaPlayer>(this));
611     }
612 
613     /*
614      * Update the MediaPlayer SurfaceTexture.
615      * Call after setting a new display surface.
616      */
_setVideoSurface(Surface surface)617     private native void _setVideoSurface(Surface surface);
618 
619     /* Do not change these values (starting with INVOKE_ID) without updating
620      * their counterparts in include/media/mediaplayer.h!
621      */
622     private static final int INVOKE_ID_GET_TRACK_INFO = 1;
623     private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE = 2;
624     private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3;
625     private static final int INVOKE_ID_SELECT_TRACK = 4;
626     private static final int INVOKE_ID_DESELECT_TRACK = 5;
627     private static final int INVOKE_ID_SET_VIDEO_SCALE_MODE = 6;
628 
629     /**
630      * Create a request parcel which can be routed to the native media
631      * player using {@link #invoke(Parcel, Parcel)}. The Parcel
632      * returned has the proper InterfaceToken set. The caller should
633      * not overwrite that token, i.e it can only append data to the
634      * Parcel.
635      *
636      * @return A parcel suitable to hold a request for the native
637      * player.
638      * {@hide}
639      */
newRequest()640     public Parcel newRequest() {
641         Parcel parcel = Parcel.obtain();
642         parcel.writeInterfaceToken(IMEDIA_PLAYER);
643         return parcel;
644     }
645 
646     /**
647      * Invoke a generic method on the native player using opaque
648      * parcels for the request and reply. Both payloads' format is a
649      * convention between the java caller and the native player.
650      * Must be called after setDataSource to make sure a native player
651      * exists. On failure, a RuntimeException is thrown.
652      *
653      * @param request Parcel with the data for the extension. The
654      * caller must use {@link #newRequest()} to get one.
655      *
656      * @param reply Output parcel with the data returned by the
657      * native player.
658      * {@hide}
659      */
invoke(Parcel request, Parcel reply)660     public void invoke(Parcel request, Parcel reply) {
661         int retcode = native_invoke(request, reply);
662         reply.setDataPosition(0);
663         if (retcode != 0) {
664             throw new RuntimeException("failure code: " + retcode);
665         }
666     }
667 
668     /**
669      * Sets the {@link SurfaceHolder} to use for displaying the video
670      * portion of the media.
671      *
672      * Either a surface holder or surface must be set if a display or video sink
673      * is needed.  Not calling this method or {@link #setSurface(Surface)}
674      * when playing back a video will result in only the audio track being played.
675      * A null surface holder or surface will result in only the audio track being
676      * played.
677      *
678      * @param sh the SurfaceHolder to use for video display
679      */
setDisplay(SurfaceHolder sh)680     public void setDisplay(SurfaceHolder sh) {
681         mSurfaceHolder = sh;
682         Surface surface;
683         if (sh != null) {
684             surface = sh.getSurface();
685         } else {
686             surface = null;
687         }
688         _setVideoSurface(surface);
689         updateSurfaceScreenOn();
690     }
691 
692     /**
693      * Sets the {@link Surface} to be used as the sink for the video portion of
694      * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but
695      * does not support {@link #setScreenOnWhilePlaying(boolean)}.  Setting a
696      * Surface will un-set any Surface or SurfaceHolder that was previously set.
697      * A null surface will result in only the audio track being played.
698      *
699      * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
700      * returned from {@link SurfaceTexture#getTimestamp()} will have an
701      * unspecified zero point.  These timestamps cannot be directly compared
702      * between different media sources, different instances of the same media
703      * source, or multiple runs of the same program.  The timestamp is normally
704      * monotonically increasing and is unaffected by time-of-day adjustments,
705      * but it is reset when the position is set.
706      *
707      * @param surface The {@link Surface} to be used for the video portion of
708      * the media.
709      */
setSurface(Surface surface)710     public void setSurface(Surface surface) {
711         if (mScreenOnWhilePlaying && surface != null) {
712             Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
713         }
714         mSurfaceHolder = null;
715         _setVideoSurface(surface);
716         updateSurfaceScreenOn();
717     }
718 
719     /* Do not change these video scaling mode values below without updating
720      * their counterparts in system/window.h! Please do not forget to update
721      * {@link #isVideoScalingModeSupported} when new video scaling modes
722      * are added.
723      */
724     /**
725      * Specifies a video scaling mode. The content is stretched to the
726      * surface rendering area. When the surface has the same aspect ratio
727      * as the content, the aspect ratio of the content is maintained;
728      * otherwise, the aspect ratio of the content is not maintained when video
729      * is being rendered. Unlike {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING},
730      * there is no content cropping with this video scaling mode.
731      */
732     public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1;
733 
734     /**
735      * Specifies a video scaling mode. The content is scaled, maintaining
736      * its aspect ratio. The whole surface area is always used. When the
737      * aspect ratio of the content is the same as the surface, no content
738      * is cropped; otherwise, content is cropped to fit the surface.
739      */
740     public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2;
741     /**
742      * Sets video scaling mode. To make the target video scaling mode
743      * effective during playback, this method must be called after
744      * data source is set. If not called, the default video
745      * scaling mode is {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}.
746      *
747      * <p> The supported video scaling modes are:
748      * <ul>
749      * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}
750      * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING}
751      * </ul>
752      *
753      * @param mode target video scaling mode. Most be one of the supported
754      * video scaling modes; otherwise, IllegalArgumentException will be thrown.
755      *
756      * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT
757      * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
758      */
setVideoScalingMode(int mode)759     public void setVideoScalingMode(int mode) {
760         if (!isVideoScalingModeSupported(mode)) {
761             final String msg = "Scaling mode " + mode + " is not supported";
762             throw new IllegalArgumentException(msg);
763         }
764         Parcel request = Parcel.obtain();
765         Parcel reply = Parcel.obtain();
766         try {
767             request.writeInterfaceToken(IMEDIA_PLAYER);
768             request.writeInt(INVOKE_ID_SET_VIDEO_SCALE_MODE);
769             request.writeInt(mode);
770             invoke(request, reply);
771         } finally {
772             request.recycle();
773             reply.recycle();
774         }
775     }
776 
777     /**
778      * Convenience method to create a MediaPlayer for a given Uri.
779      * On success, {@link #prepare()} will already have been called and must not be called again.
780      * <p>When done with the MediaPlayer, you should call  {@link #release()},
781      * to free the resources. If not released, too many MediaPlayer instances will
782      * result in an exception.</p>
783      *
784      * @param context the Context to use
785      * @param uri the Uri from which to get the datasource
786      * @return a MediaPlayer object, or null if creation failed
787      */
create(Context context, Uri uri)788     public static MediaPlayer create(Context context, Uri uri) {
789         return create (context, uri, null);
790     }
791 
792     /**
793      * Convenience method to create a MediaPlayer for a given Uri.
794      * On success, {@link #prepare()} will already have been called and must not be called again.
795      * <p>When done with the MediaPlayer, you should call  {@link #release()},
796      * to free the resources. If not released, too many MediaPlayer instances will
797      * result in an exception.</p>
798      *
799      * @param context the Context to use
800      * @param uri the Uri from which to get the datasource
801      * @param holder the SurfaceHolder to use for displaying the video
802      * @return a MediaPlayer object, or null if creation failed
803      */
create(Context context, Uri uri, SurfaceHolder holder)804     public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
805 
806         try {
807             MediaPlayer mp = new MediaPlayer();
808             mp.setDataSource(context, uri);
809             if (holder != null) {
810                 mp.setDisplay(holder);
811             }
812             mp.prepare();
813             return mp;
814         } catch (IOException ex) {
815             Log.d(TAG, "create failed:", ex);
816             // fall through
817         } catch (IllegalArgumentException ex) {
818             Log.d(TAG, "create failed:", ex);
819             // fall through
820         } catch (SecurityException ex) {
821             Log.d(TAG, "create failed:", ex);
822             // fall through
823         }
824 
825         return null;
826     }
827 
828     // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
829 
830     /**
831      * Convenience method to create a MediaPlayer for a given resource id.
832      * On success, {@link #prepare()} will already have been called and must not be called again.
833      * <p>When done with the MediaPlayer, you should call  {@link #release()},
834      * to free the resources. If not released, too many MediaPlayer instances will
835      * result in an exception.</p>
836      *
837      * @param context the Context to use
838      * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
839      *              the resource to use as the datasource
840      * @return a MediaPlayer object, or null if creation failed
841      */
create(Context context, int resid)842     public static MediaPlayer create(Context context, int resid) {
843         try {
844             AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
845             if (afd == null) return null;
846 
847             MediaPlayer mp = new MediaPlayer();
848             mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
849             afd.close();
850             mp.prepare();
851             return mp;
852         } catch (IOException ex) {
853             Log.d(TAG, "create failed:", ex);
854             // fall through
855         } catch (IllegalArgumentException ex) {
856             Log.d(TAG, "create failed:", ex);
857            // fall through
858         } catch (SecurityException ex) {
859             Log.d(TAG, "create failed:", ex);
860             // fall through
861         }
862         return null;
863     }
864 
865     /**
866      * Sets the data source as a content Uri.
867      *
868      * @param context the Context to use when resolving the Uri
869      * @param uri the Content URI of the data you want to play
870      * @throws IllegalStateException if it is called in an invalid state
871      */
setDataSource(Context context, Uri uri)872     public void setDataSource(Context context, Uri uri)
873         throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
874         setDataSource(context, uri, null);
875     }
876 
877     /**
878      * Sets the data source as a content Uri.
879      *
880      * @param context the Context to use when resolving the Uri
881      * @param uri the Content URI of the data you want to play
882      * @param headers the headers to be sent together with the request for the data
883      * @throws IllegalStateException if it is called in an invalid state
884      */
setDataSource(Context context, Uri uri, Map<String, String> headers)885     public void setDataSource(Context context, Uri uri, Map<String, String> headers)
886         throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
887         disableProxyListener();
888 
889         String scheme = uri.getScheme();
890         if(scheme == null || scheme.equals("file")) {
891             setDataSource(uri.getPath());
892             return;
893         }
894 
895         AssetFileDescriptor fd = null;
896         try {
897             ContentResolver resolver = context.getContentResolver();
898             fd = resolver.openAssetFileDescriptor(uri, "r");
899             if (fd == null) {
900                 return;
901             }
902             // Note: using getDeclaredLength so that our behavior is the same
903             // as previous versions when the content provider is returning
904             // a full file.
905             if (fd.getDeclaredLength() < 0) {
906                 setDataSource(fd.getFileDescriptor());
907             } else {
908                 setDataSource(fd.getFileDescriptor(), fd.getStartOffset(), fd.getDeclaredLength());
909             }
910             return;
911         } catch (SecurityException ex) {
912         } catch (IOException ex) {
913         } finally {
914             if (fd != null) {
915                 fd.close();
916             }
917         }
918 
919         Log.d(TAG, "Couldn't open file on client side, trying server side");
920 
921         setDataSource(uri.toString(), headers);
922 
923         if (scheme.equalsIgnoreCase("http")
924                 || scheme.equalsIgnoreCase("https")) {
925             setupProxyListener(context);
926         }
927     }
928 
929     /**
930      * Sets the data source (file-path or http/rtsp URL) to use.
931      *
932      * @param path the path of the file, or the http/rtsp URL of the stream you want to play
933      * @throws IllegalStateException if it is called in an invalid state
934      *
935      * <p>When <code>path</code> refers to a local file, the file may actually be opened by a
936      * process other than the calling application.  This implies that the pathname
937      * should be an absolute path (as any other process runs with unspecified current working
938      * directory), and that the pathname should reference a world-readable file.
939      * As an alternative, the application could first open the file for reading,
940      * and then use the file descriptor form {@link #setDataSource(FileDescriptor)}.
941      */
setDataSource(String path)942     public void setDataSource(String path)
943             throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
944         setDataSource(path, null, null);
945     }
946 
947     /**
948      * Sets the data source (file-path or http/rtsp URL) to use.
949      *
950      * @param path the path of the file, or the http/rtsp URL of the stream you want to play
951      * @param headers the headers associated with the http request for the stream you want to play
952      * @throws IllegalStateException if it is called in an invalid state
953      * @hide pending API council
954      */
setDataSource(String path, Map<String, String> headers)955     public void setDataSource(String path, Map<String, String> headers)
956             throws IOException, IllegalArgumentException, SecurityException, IllegalStateException
957     {
958         String[] keys = null;
959         String[] values = null;
960 
961         if (headers != null) {
962             keys = new String[headers.size()];
963             values = new String[headers.size()];
964 
965             int i = 0;
966             for (Map.Entry<String, String> entry: headers.entrySet()) {
967                 keys[i] = entry.getKey();
968                 values[i] = entry.getValue();
969                 ++i;
970             }
971         }
972         setDataSource(path, keys, values);
973     }
974 
setDataSource(String path, String[] keys, String[] values)975     private void setDataSource(String path, String[] keys, String[] values)
976             throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
977         disableProxyListener();
978 
979         final Uri uri = Uri.parse(path);
980         if ("file".equals(uri.getScheme())) {
981             path = uri.getPath();
982         }
983 
984         final File file = new File(path);
985         if (file.exists()) {
986             FileInputStream is = new FileInputStream(file);
987             FileDescriptor fd = is.getFD();
988             setDataSource(fd);
989             is.close();
990         } else {
991             _setDataSource(path, keys, values);
992         }
993     }
994 
_setDataSource( String path, String[] keys, String[] values)995     private native void _setDataSource(
996         String path, String[] keys, String[] values)
997         throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
998 
999     /**
1000      * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
1001      * to close the file descriptor. It is safe to do so as soon as this call returns.
1002      *
1003      * @param fd the FileDescriptor for the file you want to play
1004      * @throws IllegalStateException if it is called in an invalid state
1005      */
setDataSource(FileDescriptor fd)1006     public void setDataSource(FileDescriptor fd)
1007             throws IOException, IllegalArgumentException, IllegalStateException {
1008         // intentionally less than LONG_MAX
1009         setDataSource(fd, 0, 0x7ffffffffffffffL);
1010     }
1011 
1012     /**
1013      * Sets the data source (FileDescriptor) to use.  The FileDescriptor must be
1014      * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
1015      * to close the file descriptor. It is safe to do so as soon as this call returns.
1016      *
1017      * @param fd the FileDescriptor for the file you want to play
1018      * @param offset the offset into the file where the data to be played starts, in bytes
1019      * @param length the length in bytes of the data to be played
1020      * @throws IllegalStateException if it is called in an invalid state
1021      */
setDataSource(FileDescriptor fd, long offset, long length)1022     public void setDataSource(FileDescriptor fd, long offset, long length)
1023             throws IOException, IllegalArgumentException, IllegalStateException {
1024         disableProxyListener();
1025         _setDataSource(fd, offset, length);
1026     }
1027 
_setDataSource(FileDescriptor fd, long offset, long length)1028     private native void _setDataSource(FileDescriptor fd, long offset, long length)
1029             throws IOException, IllegalArgumentException, IllegalStateException;
1030 
1031     /**
1032      * Prepares the player for playback, synchronously.
1033      *
1034      * After setting the datasource and the display surface, you need to either
1035      * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
1036      * which blocks until MediaPlayer is ready for playback.
1037      *
1038      * @throws IllegalStateException if it is called in an invalid state
1039      */
prepare()1040     public native void prepare() throws IOException, IllegalStateException;
1041 
1042     /**
1043      * Prepares the player for playback, asynchronously.
1044      *
1045      * After setting the datasource and the display surface, you need to either
1046      * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
1047      * which returns immediately, rather than blocking until enough data has been
1048      * buffered.
1049      *
1050      * @throws IllegalStateException if it is called in an invalid state
1051      */
prepareAsync()1052     public native void prepareAsync() throws IllegalStateException;
1053 
1054     /**
1055      * Starts or resumes playback. If playback had previously been paused,
1056      * playback will continue from where it was paused. If playback had
1057      * been stopped, or never started before, playback will start at the
1058      * beginning.
1059      *
1060      * @throws IllegalStateException if it is called in an invalid state
1061      */
start()1062     public  void start() throws IllegalStateException {
1063         stayAwake(true);
1064         _start();
1065     }
1066 
_start()1067     private native void _start() throws IllegalStateException;
1068 
1069     /**
1070      * Stops playback after playback has been stopped or paused.
1071      *
1072      * @throws IllegalStateException if the internal player engine has not been
1073      * initialized.
1074      */
stop()1075     public void stop() throws IllegalStateException {
1076         stayAwake(false);
1077         _stop();
1078     }
1079 
_stop()1080     private native void _stop() throws IllegalStateException;
1081 
1082     /**
1083      * Pauses playback. Call start() to resume.
1084      *
1085      * @throws IllegalStateException if the internal player engine has not been
1086      * initialized.
1087      */
pause()1088     public void pause() throws IllegalStateException {
1089         stayAwake(false);
1090         _pause();
1091     }
1092 
_pause()1093     private native void _pause() throws IllegalStateException;
1094 
1095     /**
1096      * Set the low-level power management behavior for this MediaPlayer.  This
1097      * can be used when the MediaPlayer is not playing through a SurfaceHolder
1098      * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
1099      * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
1100      *
1101      * <p>This function has the MediaPlayer access the low-level power manager
1102      * service to control the device's power usage while playing is occurring.
1103      * The parameter is a combination of {@link android.os.PowerManager} wake flags.
1104      * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
1105      * permission.
1106      * By default, no attempt is made to keep the device awake during playback.
1107      *
1108      * @param context the Context to use
1109      * @param mode    the power/wake mode to set
1110      * @see android.os.PowerManager
1111      */
setWakeMode(Context context, int mode)1112     public void setWakeMode(Context context, int mode) {
1113         boolean washeld = false;
1114         if (mWakeLock != null) {
1115             if (mWakeLock.isHeld()) {
1116                 washeld = true;
1117                 mWakeLock.release();
1118             }
1119             mWakeLock = null;
1120         }
1121 
1122         PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1123         mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
1124         mWakeLock.setReferenceCounted(false);
1125         if (washeld) {
1126             mWakeLock.acquire();
1127         }
1128     }
1129 
1130     /**
1131      * Control whether we should use the attached SurfaceHolder to keep the
1132      * screen on while video playback is occurring.  This is the preferred
1133      * method over {@link #setWakeMode} where possible, since it doesn't
1134      * require that the application have permission for low-level wake lock
1135      * access.
1136      *
1137      * @param screenOn Supply true to keep the screen on, false to allow it
1138      * to turn off.
1139      */
setScreenOnWhilePlaying(boolean screenOn)1140     public void setScreenOnWhilePlaying(boolean screenOn) {
1141         if (mScreenOnWhilePlaying != screenOn) {
1142             if (screenOn && mSurfaceHolder == null) {
1143                 Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
1144             }
1145             mScreenOnWhilePlaying = screenOn;
1146             updateSurfaceScreenOn();
1147         }
1148     }
1149 
stayAwake(boolean awake)1150     private void stayAwake(boolean awake) {
1151         if (mWakeLock != null) {
1152             if (awake && !mWakeLock.isHeld()) {
1153                 mWakeLock.acquire();
1154             } else if (!awake && mWakeLock.isHeld()) {
1155                 mWakeLock.release();
1156             }
1157         }
1158         mStayAwake = awake;
1159         updateSurfaceScreenOn();
1160     }
1161 
updateSurfaceScreenOn()1162     private void updateSurfaceScreenOn() {
1163         if (mSurfaceHolder != null) {
1164             mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1165         }
1166     }
1167 
1168     /**
1169      * Returns the width of the video.
1170      *
1171      * @return the width of the video, or 0 if there is no video,
1172      * no display surface was set, or the width has not been determined
1173      * yet. The OnVideoSizeChangedListener can be registered via
1174      * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1175      * to provide a notification when the width is available.
1176      */
getVideoWidth()1177     public native int getVideoWidth();
1178 
1179     /**
1180      * Returns the height of the video.
1181      *
1182      * @return the height of the video, or 0 if there is no video,
1183      * no display surface was set, or the height has not been determined
1184      * yet. The OnVideoSizeChangedListener can be registered via
1185      * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1186      * to provide a notification when the height is available.
1187      */
getVideoHeight()1188     public native int getVideoHeight();
1189 
1190     /**
1191      * Checks whether the MediaPlayer is playing.
1192      *
1193      * @return true if currently playing, false otherwise
1194      * @throws IllegalStateException if the internal player engine has not been
1195      * initialized or has been released.
1196      */
isPlaying()1197     public native boolean isPlaying();
1198 
1199     /**
1200      * Seeks to specified time position.
1201      *
1202      * @param msec the offset in milliseconds from the start to seek to
1203      * @throws IllegalStateException if the internal player engine has not been
1204      * initialized
1205      */
seekTo(int msec)1206     public native void seekTo(int msec) throws IllegalStateException;
1207 
1208     /**
1209      * Gets the current playback position.
1210      *
1211      * @return the current position in milliseconds
1212      */
getCurrentPosition()1213     public native int getCurrentPosition();
1214 
1215     /**
1216      * Gets the duration of the file.
1217      *
1218      * @return the duration in milliseconds, if no duration is available
1219      *         (for example, if streaming live content), -1 is returned.
1220      */
getDuration()1221     public native int getDuration();
1222 
1223     /**
1224      * Gets the media metadata.
1225      *
1226      * @param update_only controls whether the full set of available
1227      * metadata is returned or just the set that changed since the
1228      * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
1229      * #METADATA_ALL}.
1230      *
1231      * @param apply_filter if true only metadata that matches the
1232      * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
1233      * #BYPASS_METADATA_FILTER}.
1234      *
1235      * @return The metadata, possibly empty. null if an error occured.
1236      // FIXME: unhide.
1237      * {@hide}
1238      */
getMetadata(final boolean update_only, final boolean apply_filter)1239     public Metadata getMetadata(final boolean update_only,
1240                                 final boolean apply_filter) {
1241         Parcel reply = Parcel.obtain();
1242         Metadata data = new Metadata();
1243 
1244         if (!native_getMetadata(update_only, apply_filter, reply)) {
1245             reply.recycle();
1246             return null;
1247         }
1248 
1249         // Metadata takes over the parcel, don't recycle it unless
1250         // there is an error.
1251         if (!data.parse(reply)) {
1252             reply.recycle();
1253             return null;
1254         }
1255         return data;
1256     }
1257 
1258     /**
1259      * Set a filter for the metadata update notification and update
1260      * retrieval. The caller provides 2 set of metadata keys, allowed
1261      * and blocked. The blocked set always takes precedence over the
1262      * allowed one.
1263      * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
1264      * shorthands to allow/block all or no metadata.
1265      *
1266      * By default, there is no filter set.
1267      *
1268      * @param allow Is the set of metadata the client is interested
1269      *              in receiving new notifications for.
1270      * @param block Is the set of metadata the client is not interested
1271      *              in receiving new notifications for.
1272      * @return The call status code.
1273      *
1274      // FIXME: unhide.
1275      * {@hide}
1276      */
setMetadataFilter(Set<Integer> allow, Set<Integer> block)1277     public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
1278         // Do our serialization manually instead of calling
1279         // Parcel.writeArray since the sets are made of the same type
1280         // we avoid paying the price of calling writeValue (used by
1281         // writeArray) which burns an extra int per element to encode
1282         // the type.
1283         Parcel request =  newRequest();
1284 
1285         // The parcel starts already with an interface token. There
1286         // are 2 filters. Each one starts with a 4bytes number to
1287         // store the len followed by a number of int (4 bytes as well)
1288         // representing the metadata type.
1289         int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
1290 
1291         if (request.dataCapacity() < capacity) {
1292             request.setDataCapacity(capacity);
1293         }
1294 
1295         request.writeInt(allow.size());
1296         for(Integer t: allow) {
1297             request.writeInt(t);
1298         }
1299         request.writeInt(block.size());
1300         for(Integer t: block) {
1301             request.writeInt(t);
1302         }
1303         return native_setMetadataFilter(request);
1304     }
1305 
1306     /**
1307      * Set the MediaPlayer to start when this MediaPlayer finishes playback
1308      * (i.e. reaches the end of the stream).
1309      * The media framework will attempt to transition from this player to
1310      * the next as seamlessly as possible. The next player can be set at
1311      * any time before completion. The next player must be prepared by the
1312      * app, and the application should not call start() on it.
1313      * The next MediaPlayer must be different from 'this'. An exception
1314      * will be thrown if next == this.
1315      * The application may call setNextMediaPlayer(null) to indicate no
1316      * next player should be started at the end of playback.
1317      * If the current player is looping, it will keep looping and the next
1318      * player will not be started.
1319      *
1320      * @param next the player to start after this one completes playback.
1321      *
1322      */
setNextMediaPlayer(MediaPlayer next)1323     public native void setNextMediaPlayer(MediaPlayer next);
1324 
1325     /**
1326      * Releases resources associated with this MediaPlayer object.
1327      * It is considered good practice to call this method when you're
1328      * done using the MediaPlayer. In particular, whenever an Activity
1329      * of an application is paused (its onPause() method is called),
1330      * or stopped (its onStop() method is called), this method should be
1331      * invoked to release the MediaPlayer object, unless the application
1332      * has a special need to keep the object around. In addition to
1333      * unnecessary resources (such as memory and instances of codecs)
1334      * being held, failure to call this method immediately if a
1335      * MediaPlayer object is no longer needed may also lead to
1336      * continuous battery consumption for mobile devices, and playback
1337      * failure for other applications if no multiple instances of the
1338      * same codec are supported on a device. Even if multiple instances
1339      * of the same codec are supported, some performance degradation
1340      * may be expected when unnecessary multiple instances are used
1341      * at the same time.
1342      */
release()1343     public void release() {
1344         stayAwake(false);
1345         updateSurfaceScreenOn();
1346         mOnPreparedListener = null;
1347         mOnBufferingUpdateListener = null;
1348         mOnCompletionListener = null;
1349         mOnSeekCompleteListener = null;
1350         mOnErrorListener = null;
1351         mOnInfoListener = null;
1352         mOnVideoSizeChangedListener = null;
1353         mOnTimedTextListener = null;
1354         if (mTimeProvider != null) {
1355             mTimeProvider.close();
1356             mTimeProvider = null;
1357         }
1358         mOnSubtitleDataListener = null;
1359         _release();
1360     }
1361 
_release()1362     private native void _release();
1363 
1364     /**
1365      * Resets the MediaPlayer to its uninitialized state. After calling
1366      * this method, you will have to initialize it again by setting the
1367      * data source and calling prepare().
1368      */
reset()1369     public void reset() {
1370         mSelectedSubtitleTrackIndex = -1;
1371         synchronized(mOpenSubtitleSources) {
1372             for (final InputStream is: mOpenSubtitleSources) {
1373                 try {
1374                     is.close();
1375                 } catch (IOException e) {
1376                 }
1377             }
1378             mOpenSubtitleSources.clear();
1379         }
1380         mOutOfBandSubtitleTracks.clear();
1381         mInbandSubtitleTracks = new SubtitleTrack[0];
1382         if (mSubtitleController != null) {
1383             mSubtitleController.reset();
1384         }
1385         if (mTimeProvider != null) {
1386             mTimeProvider.close();
1387             mTimeProvider = null;
1388         }
1389 
1390         stayAwake(false);
1391         _reset();
1392         // make sure none of the listeners get called anymore
1393         if (mEventHandler != null) {
1394             mEventHandler.removeCallbacksAndMessages(null);
1395         }
1396 
1397         disableProxyListener();
1398     }
1399 
_reset()1400     private native void _reset();
1401 
1402     /**
1403      * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
1404      * for a list of stream types. Must call this method before prepare() or
1405      * prepareAsync() in order for the target stream type to become effective
1406      * thereafter.
1407      *
1408      * @param streamtype the audio stream type
1409      * @see android.media.AudioManager
1410      */
setAudioStreamType(int streamtype)1411     public native void setAudioStreamType(int streamtype);
1412 
1413     /**
1414      * Sets the player to be looping or non-looping.
1415      *
1416      * @param looping whether to loop or not
1417      */
setLooping(boolean looping)1418     public native void setLooping(boolean looping);
1419 
1420     /**
1421      * Checks whether the MediaPlayer is looping or non-looping.
1422      *
1423      * @return true if the MediaPlayer is currently looping, false otherwise
1424      */
isLooping()1425     public native boolean isLooping();
1426 
1427     /**
1428      * Sets the volume on this player.
1429      * This API is recommended for balancing the output of audio streams
1430      * within an application. Unless you are writing an application to
1431      * control user settings, this API should be used in preference to
1432      * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
1433      * a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
1434      * UI controls should be scaled logarithmically.
1435      *
1436      * @param leftVolume left volume scalar
1437      * @param rightVolume right volume scalar
1438      */
1439     /*
1440      * FIXME: Merge this into javadoc comment above when setVolume(float) is not @hide.
1441      * The single parameter form below is preferred if the channel volumes don't need
1442      * to be set independently.
1443      */
setVolume(float leftVolume, float rightVolume)1444     public native void setVolume(float leftVolume, float rightVolume);
1445 
1446     /**
1447      * Similar, excepts sets volume of all channels to same value.
1448      * @hide
1449      */
setVolume(float volume)1450     public void setVolume(float volume) {
1451         setVolume(volume, volume);
1452     }
1453 
1454     /**
1455      * Sets the audio session ID.
1456      *
1457      * @param sessionId the audio session ID.
1458      * The audio session ID is a system wide unique identifier for the audio stream played by
1459      * this MediaPlayer instance.
1460      * The primary use of the audio session ID  is to associate audio effects to a particular
1461      * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
1462      * this effect will be applied only to the audio content of media players within the same
1463      * audio session and not to the output mix.
1464      * When created, a MediaPlayer instance automatically generates its own audio session ID.
1465      * However, it is possible to force this player to be part of an already existing audio session
1466      * by calling this method.
1467      * This method must be called before one of the overloaded <code> setDataSource </code> methods.
1468      * @throws IllegalStateException if it is called in an invalid state
1469      */
setAudioSessionId(int sessionId)1470     public native void setAudioSessionId(int sessionId)  throws IllegalArgumentException, IllegalStateException;
1471 
1472     /**
1473      * Returns the audio session ID.
1474      *
1475      * @return the audio session ID. {@see #setAudioSessionId(int)}
1476      * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
1477      */
getAudioSessionId()1478     public native int getAudioSessionId();
1479 
1480     /**
1481      * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1482      * effect which can be applied on any sound source that directs a certain amount of its
1483      * energy to this effect. This amount is defined by setAuxEffectSendLevel().
1484      * {@see #setAuxEffectSendLevel(float)}.
1485      * <p>After creating an auxiliary effect (e.g.
1486      * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1487      * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1488      * to attach the player to the effect.
1489      * <p>To detach the effect from the player, call this method with a null effect id.
1490      * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1491      * methods.
1492      * @param effectId system wide unique id of the effect to attach
1493      */
attachAuxEffect(int effectId)1494     public native void attachAuxEffect(int effectId);
1495 
1496 
1497     /**
1498      * Sets the send level of the player to the attached auxiliary effect
1499      * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1500      * <p>By default the send level is 0, so even if an effect is attached to the player
1501      * this method must be called for the effect to be applied.
1502      * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1503      * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1504      * so an appropriate conversion from linear UI input x to level is:
1505      * x == 0 -> level = 0
1506      * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1507      * @param level send level scalar
1508      */
setAuxEffectSendLevel(float level)1509     public native void setAuxEffectSendLevel(float level);
1510 
1511     /*
1512      * @param request Parcel destinated to the media player. The
1513      *                Interface token must be set to the IMediaPlayer
1514      *                one to be routed correctly through the system.
1515      * @param reply[out] Parcel that will contain the reply.
1516      * @return The status code.
1517      */
native_invoke(Parcel request, Parcel reply)1518     private native final int native_invoke(Parcel request, Parcel reply);
1519 
1520 
1521     /*
1522      * @param update_only If true fetch only the set of metadata that have
1523      *                    changed since the last invocation of getMetadata.
1524      *                    The set is built using the unfiltered
1525      *                    notifications the native player sent to the
1526      *                    MediaPlayerService during that period of
1527      *                    time. If false, all the metadatas are considered.
1528      * @param apply_filter  If true, once the metadata set has been built based on
1529      *                     the value update_only, the current filter is applied.
1530      * @param reply[out] On return contains the serialized
1531      *                   metadata. Valid only if the call was successful.
1532      * @return The status code.
1533      */
native_getMetadata(boolean update_only, boolean apply_filter, Parcel reply)1534     private native final boolean native_getMetadata(boolean update_only,
1535                                                     boolean apply_filter,
1536                                                     Parcel reply);
1537 
1538     /*
1539      * @param request Parcel with the 2 serialized lists of allowed
1540      *                metadata types followed by the one to be
1541      *                dropped. Each list starts with an integer
1542      *                indicating the number of metadata type elements.
1543      * @return The status code.
1544      */
native_setMetadataFilter(Parcel request)1545     private native final int native_setMetadataFilter(Parcel request);
1546 
native_init()1547     private static native final void native_init();
native_setup(Object mediaplayer_this)1548     private native final void native_setup(Object mediaplayer_this);
native_finalize()1549     private native final void native_finalize();
1550 
1551     /**
1552      * Class for MediaPlayer to return each audio/video/subtitle track's metadata.
1553      *
1554      * @see android.media.MediaPlayer#getTrackInfo
1555      */
1556     static public class TrackInfo implements Parcelable {
1557         /**
1558          * Gets the track type.
1559          * @return TrackType which indicates if the track is video, audio, timed text.
1560          */
getTrackType()1561         public int getTrackType() {
1562             return mTrackType;
1563         }
1564 
1565         /**
1566          * Gets the language code of the track.
1567          * @return a language code in either way of ISO-639-1 or ISO-639-2.
1568          * When the language is unknown or could not be determined,
1569          * ISO-639-2 language code, "und", is returned.
1570          */
getLanguage()1571         public String getLanguage() {
1572             String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
1573             return language == null ? "und" : language;
1574         }
1575 
1576         /**
1577          * Gets the {@link MediaFormat} of the track.  If the format is
1578          * unknown or could not be determined, null is returned.
1579          */
getFormat()1580         public MediaFormat getFormat() {
1581             if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT
1582                     || mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
1583                 return mFormat;
1584             }
1585             return null;
1586         }
1587 
1588         public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
1589         public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
1590         public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
1591         public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
1592         /** @hide */
1593         public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
1594 
1595         final int mTrackType;
1596         final MediaFormat mFormat;
1597 
TrackInfo(Parcel in)1598         TrackInfo(Parcel in) {
1599             mTrackType = in.readInt();
1600             // TODO: parcel in the full MediaFormat
1601             String language = in.readString();
1602 
1603             if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1604                 mFormat = MediaFormat.createSubtitleFormat(
1605                     MEDIA_MIMETYPE_TEXT_SUBRIP, language);
1606             } else if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
1607                 mFormat = MediaFormat.createSubtitleFormat(
1608                     MEDIA_MIMETYPE_TEXT_VTT, language);
1609                 mFormat.setInteger(MediaFormat.KEY_IS_AUTOSELECT, in.readInt());
1610                 mFormat.setInteger(MediaFormat.KEY_IS_DEFAULT, in.readInt());
1611                 mFormat.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.readInt());
1612             } else {
1613                 mFormat = new MediaFormat();
1614                 mFormat.setString(MediaFormat.KEY_LANGUAGE, language);
1615             }
1616         }
1617 
1618         /** @hide */
TrackInfo(int type, MediaFormat format)1619         TrackInfo(int type, MediaFormat format) {
1620             mTrackType = type;
1621             mFormat = format;
1622         }
1623 
1624         /**
1625          * {@inheritDoc}
1626          */
1627         @Override
describeContents()1628         public int describeContents() {
1629             return 0;
1630         }
1631 
1632         /**
1633          * {@inheritDoc}
1634          */
1635         @Override
writeToParcel(Parcel dest, int flags)1636         public void writeToParcel(Parcel dest, int flags) {
1637             dest.writeInt(mTrackType);
1638             dest.writeString(getLanguage());
1639 
1640             if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
1641                 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_AUTOSELECT));
1642                 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_DEFAULT));
1643                 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE));
1644             }
1645         }
1646 
1647         /**
1648          * Used to read a TrackInfo from a Parcel.
1649          */
1650         static final Parcelable.Creator<TrackInfo> CREATOR
1651                 = new Parcelable.Creator<TrackInfo>() {
1652                     @Override
1653                     public TrackInfo createFromParcel(Parcel in) {
1654                         return new TrackInfo(in);
1655                     }
1656 
1657                     @Override
1658                     public TrackInfo[] newArray(int size) {
1659                         return new TrackInfo[size];
1660                     }
1661                 };
1662 
1663     };
1664 
1665     /**
1666      * Returns an array of track information.
1667      *
1668      * @return Array of track info. The total number of tracks is the array length.
1669      * Must be called again if an external timed text source has been added after any of the
1670      * addTimedTextSource methods are called.
1671      * @throws IllegalStateException if it is called in an invalid state.
1672      */
getTrackInfo()1673     public TrackInfo[] getTrackInfo() throws IllegalStateException {
1674         TrackInfo trackInfo[] = getInbandTrackInfo();
1675         // add out-of-band tracks
1676         TrackInfo allTrackInfo[] = new TrackInfo[trackInfo.length + mOutOfBandSubtitleTracks.size()];
1677         System.arraycopy(trackInfo, 0, allTrackInfo, 0, trackInfo.length);
1678         int i = trackInfo.length;
1679         for (SubtitleTrack track: mOutOfBandSubtitleTracks) {
1680             allTrackInfo[i] = new TrackInfo(TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE, track.getFormat());
1681             ++i;
1682         }
1683         return allTrackInfo;
1684     }
1685 
getInbandTrackInfo()1686     private TrackInfo[] getInbandTrackInfo() throws IllegalStateException {
1687         Parcel request = Parcel.obtain();
1688         Parcel reply = Parcel.obtain();
1689         try {
1690             request.writeInterfaceToken(IMEDIA_PLAYER);
1691             request.writeInt(INVOKE_ID_GET_TRACK_INFO);
1692             invoke(request, reply);
1693             TrackInfo trackInfo[] = reply.createTypedArray(TrackInfo.CREATOR);
1694             return trackInfo;
1695         } finally {
1696             request.recycle();
1697             reply.recycle();
1698         }
1699     }
1700 
1701     /* Do not change these values without updating their counterparts
1702      * in include/media/stagefright/MediaDefs.h and media/libstagefright/MediaDefs.cpp!
1703      */
1704     /**
1705      * MIME type for SubRip (SRT) container. Used in addTimedTextSource APIs.
1706      */
1707     public static final String MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
1708 
1709     /**
1710      * MIME type for WebVTT subtitle data.
1711      * @hide
1712      */
1713     public static final String MEDIA_MIMETYPE_TEXT_VTT = "text/vtt";
1714 
1715     /*
1716      * A helper function to check if the mime type is supported by media framework.
1717      */
availableMimeTypeForExternalSource(String mimeType)1718     private static boolean availableMimeTypeForExternalSource(String mimeType) {
1719         if (mimeType == MEDIA_MIMETYPE_TEXT_SUBRIP) {
1720             return true;
1721         }
1722         return false;
1723     }
1724 
1725     private SubtitleController mSubtitleController;
1726 
1727     /** @hide */
setSubtitleAnchor( SubtitleController controller, SubtitleController.Anchor anchor)1728     public void setSubtitleAnchor(
1729             SubtitleController controller,
1730             SubtitleController.Anchor anchor) {
1731         // TODO: create SubtitleController in MediaPlayer
1732         mSubtitleController = controller;
1733         mSubtitleController.setAnchor(anchor);
1734     }
1735 
1736     private SubtitleTrack[] mInbandSubtitleTracks;
1737     private int mSelectedSubtitleTrackIndex = -1;
1738     private Vector<SubtitleTrack> mOutOfBandSubtitleTracks;
1739     private Vector<InputStream> mOpenSubtitleSources;
1740 
1741     private OnSubtitleDataListener mSubtitleDataListener = new OnSubtitleDataListener() {
1742         @Override
1743         public void onSubtitleData(MediaPlayer mp, SubtitleData data) {
1744             int index = data.getTrackIndex();
1745             if (index >= mInbandSubtitleTracks.length) {
1746                 return;
1747             }
1748             SubtitleTrack track = mInbandSubtitleTracks[index];
1749             if (track != null) {
1750                 try {
1751                     long runID = data.getStartTimeUs() + 1;
1752                     // TODO: move conversion into track
1753                     track.onData(new String(data.getData(), "UTF-8"), true /* eos */, runID);
1754                     track.setRunDiscardTimeMs(
1755                             runID,
1756                             (data.getStartTimeUs() + data.getDurationUs()) / 1000);
1757                 } catch (java.io.UnsupportedEncodingException e) {
1758                     Log.w(TAG, "subtitle data for track " + index + " is not UTF-8 encoded: " + e);
1759                 }
1760             }
1761         }
1762     };
1763 
1764     /** @hide */
1765     @Override
onSubtitleTrackSelected(SubtitleTrack track)1766     public void onSubtitleTrackSelected(SubtitleTrack track) {
1767         if (mSelectedSubtitleTrackIndex >= 0) {
1768             try {
1769                 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, false);
1770             } catch (IllegalStateException e) {
1771             }
1772             mSelectedSubtitleTrackIndex = -1;
1773         }
1774         setOnSubtitleDataListener(null);
1775         if (track == null) {
1776             return;
1777         }
1778         for (int i = 0; i < mInbandSubtitleTracks.length; i++) {
1779             if (mInbandSubtitleTracks[i] == track) {
1780                 Log.v(TAG, "Selecting subtitle track " + i);
1781                 mSelectedSubtitleTrackIndex = i;
1782                 try {
1783                     selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, true);
1784                 } catch (IllegalStateException e) {
1785                 }
1786                 setOnSubtitleDataListener(mSubtitleDataListener);
1787                 break;
1788             }
1789         }
1790         // no need to select out-of-band tracks
1791     }
1792 
1793     /** @hide */
addSubtitleSource(InputStream is, MediaFormat format)1794     public void addSubtitleSource(InputStream is, MediaFormat format)
1795             throws IllegalStateException
1796     {
1797         final InputStream fIs = is;
1798         final MediaFormat fFormat = format;
1799 
1800         // Ensure all input streams are closed.  It is also a handy
1801         // way to implement timeouts in the future.
1802         synchronized(mOpenSubtitleSources) {
1803             mOpenSubtitleSources.add(is);
1804         }
1805 
1806         // process each subtitle in its own thread
1807         final HandlerThread thread = new HandlerThread("SubtitleReadThread",
1808               Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
1809         thread.start();
1810         Handler handler = new Handler(thread.getLooper());
1811         handler.post(new Runnable() {
1812             private int addTrack() {
1813                 if (fIs == null || mSubtitleController == null) {
1814                     return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
1815                 }
1816 
1817                 SubtitleTrack track = mSubtitleController.addTrack(fFormat);
1818                 if (track == null) {
1819                     return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
1820                 }
1821 
1822                 // TODO: do the conversion in the subtitle track
1823                 Scanner scanner = new Scanner(fIs, "UTF-8");
1824                 String contents = scanner.useDelimiter("\\A").next();
1825                 synchronized(mOpenSubtitleSources) {
1826                     mOpenSubtitleSources.remove(fIs);
1827                 }
1828                 scanner.close();
1829                 mOutOfBandSubtitleTracks.add(track);
1830                 track.onData(contents, true /* eos */, ~0 /* runID: keep forever */);
1831                 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
1832             }
1833 
1834             public void run() {
1835                 int res = addTrack();
1836                 if (mEventHandler != null) {
1837                     Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
1838                     mEventHandler.sendMessage(m);
1839                 }
1840                 thread.getLooper().quitSafely();
1841             }
1842         });
1843     }
1844 
scanInternalSubtitleTracks()1845     private void scanInternalSubtitleTracks() {
1846         if (mSubtitleController == null) {
1847             Log.e(TAG, "Should have subtitle controller already set");
1848             return;
1849         }
1850 
1851         TrackInfo[] tracks = getInbandTrackInfo();
1852         SubtitleTrack[] inbandTracks = new SubtitleTrack[tracks.length];
1853         for (int i=0; i < tracks.length; i++) {
1854             if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
1855                 if (i < mInbandSubtitleTracks.length) {
1856                     inbandTracks[i] = mInbandSubtitleTracks[i];
1857                 } else {
1858                     SubtitleTrack track = mSubtitleController.addTrack(
1859                             tracks[i].getFormat());
1860                     inbandTracks[i] = track;
1861                 }
1862             }
1863         }
1864         mInbandSubtitleTracks = inbandTracks;
1865         mSubtitleController.selectDefaultTrack();
1866     }
1867 
1868     /* TODO: Limit the total number of external timed text source to a reasonable number.
1869      */
1870     /**
1871      * Adds an external timed text source file.
1872      *
1873      * Currently supported format is SubRip with the file extension .srt, case insensitive.
1874      * Note that a single external timed text source may contain multiple tracks in it.
1875      * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1876      * additional tracks become available after this method call.
1877      *
1878      * @param path The file path of external timed text source file.
1879      * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1880      * @throws IOException if the file cannot be accessed or is corrupted.
1881      * @throws IllegalArgumentException if the mimeType is not supported.
1882      * @throws IllegalStateException if called in an invalid state.
1883      */
addTimedTextSource(String path, String mimeType)1884     public void addTimedTextSource(String path, String mimeType)
1885             throws IOException, IllegalArgumentException, IllegalStateException {
1886         if (!availableMimeTypeForExternalSource(mimeType)) {
1887             final String msg = "Illegal mimeType for timed text source: " + mimeType;
1888             throw new IllegalArgumentException(msg);
1889         }
1890 
1891         File file = new File(path);
1892         if (file.exists()) {
1893             FileInputStream is = new FileInputStream(file);
1894             FileDescriptor fd = is.getFD();
1895             addTimedTextSource(fd, mimeType);
1896             is.close();
1897         } else {
1898             // We do not support the case where the path is not a file.
1899             throw new IOException(path);
1900         }
1901     }
1902 
1903     /**
1904      * Adds an external timed text source file (Uri).
1905      *
1906      * Currently supported format is SubRip with the file extension .srt, case insensitive.
1907      * Note that a single external timed text source may contain multiple tracks in it.
1908      * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1909      * additional tracks become available after this method call.
1910      *
1911      * @param context the Context to use when resolving the Uri
1912      * @param uri the Content URI of the data you want to play
1913      * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1914      * @throws IOException if the file cannot be accessed or is corrupted.
1915      * @throws IllegalArgumentException if the mimeType is not supported.
1916      * @throws IllegalStateException if called in an invalid state.
1917      */
addTimedTextSource(Context context, Uri uri, String mimeType)1918     public void addTimedTextSource(Context context, Uri uri, String mimeType)
1919             throws IOException, IllegalArgumentException, IllegalStateException {
1920         String scheme = uri.getScheme();
1921         if(scheme == null || scheme.equals("file")) {
1922             addTimedTextSource(uri.getPath(), mimeType);
1923             return;
1924         }
1925 
1926         AssetFileDescriptor fd = null;
1927         try {
1928             ContentResolver resolver = context.getContentResolver();
1929             fd = resolver.openAssetFileDescriptor(uri, "r");
1930             if (fd == null) {
1931                 return;
1932             }
1933             addTimedTextSource(fd.getFileDescriptor(), mimeType);
1934             return;
1935         } catch (SecurityException ex) {
1936         } catch (IOException ex) {
1937         } finally {
1938             if (fd != null) {
1939                 fd.close();
1940             }
1941         }
1942     }
1943 
1944     /**
1945      * Adds an external timed text source file (FileDescriptor).
1946      *
1947      * It is the caller's responsibility to close the file descriptor.
1948      * It is safe to do so as soon as this call returns.
1949      *
1950      * Currently supported format is SubRip. Note that a single external timed text source may
1951      * contain multiple tracks in it. One can find the total number of available tracks
1952      * using {@link #getTrackInfo()} to see what additional tracks become available
1953      * after this method call.
1954      *
1955      * @param fd the FileDescriptor for the file you want to play
1956      * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1957      * @throws IllegalArgumentException if the mimeType is not supported.
1958      * @throws IllegalStateException if called in an invalid state.
1959      */
addTimedTextSource(FileDescriptor fd, String mimeType)1960     public void addTimedTextSource(FileDescriptor fd, String mimeType)
1961             throws IllegalArgumentException, IllegalStateException {
1962         // intentionally less than LONG_MAX
1963         addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
1964     }
1965 
1966     /**
1967      * Adds an external timed text file (FileDescriptor).
1968      *
1969      * It is the caller's responsibility to close the file descriptor.
1970      * It is safe to do so as soon as this call returns.
1971      *
1972      * Currently supported format is SubRip. Note that a single external timed text source may
1973      * contain multiple tracks in it. One can find the total number of available tracks
1974      * using {@link #getTrackInfo()} to see what additional tracks become available
1975      * after this method call.
1976      *
1977      * @param fd the FileDescriptor for the file you want to play
1978      * @param offset the offset into the file where the data to be played starts, in bytes
1979      * @param length the length in bytes of the data to be played
1980      * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1981      * @throws IllegalArgumentException if the mimeType is not supported.
1982      * @throws IllegalStateException if called in an invalid state.
1983      */
addTimedTextSource(FileDescriptor fd, long offset, long length, String mimeType)1984     public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mimeType)
1985             throws IllegalArgumentException, IllegalStateException {
1986         if (!availableMimeTypeForExternalSource(mimeType)) {
1987             throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mimeType);
1988         }
1989 
1990         Parcel request = Parcel.obtain();
1991         Parcel reply = Parcel.obtain();
1992         try {
1993             request.writeInterfaceToken(IMEDIA_PLAYER);
1994             request.writeInt(INVOKE_ID_ADD_EXTERNAL_SOURCE_FD);
1995             request.writeFileDescriptor(fd);
1996             request.writeLong(offset);
1997             request.writeLong(length);
1998             request.writeString(mimeType);
1999             invoke(request, reply);
2000         } finally {
2001             request.recycle();
2002             reply.recycle();
2003         }
2004     }
2005 
2006     /**
2007      * Selects a track.
2008      * <p>
2009      * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
2010      * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
2011      * If a MediaPlayer is not in Started state, it just marks the track to be played.
2012      * </p>
2013      * <p>
2014      * In any valid state, if it is called multiple times on the same type of track (ie. Video,
2015      * Audio, Timed Text), the most recent one will be chosen.
2016      * </p>
2017      * <p>
2018      * The first audio and video tracks are selected by default if available, even though
2019      * this method is not called. However, no timed text track will be selected until
2020      * this function is called.
2021      * </p>
2022      * <p>
2023      * Currently, only timed text tracks or audio tracks can be selected via this method.
2024      * In addition, the support for selecting an audio track at runtime is pretty limited
2025      * in that an audio track can only be selected in the <em>Prepared</em> state.
2026      * </p>
2027      * @param index the index of the track to be selected. The valid range of the index
2028      * is 0..total number of track - 1. The total number of tracks as well as the type of
2029      * each individual track can be found by calling {@link #getTrackInfo()} method.
2030      * @throws IllegalStateException if called in an invalid state.
2031      *
2032      * @see android.media.MediaPlayer#getTrackInfo
2033      */
selectTrack(int index)2034     public void selectTrack(int index) throws IllegalStateException {
2035         selectOrDeselectTrack(index, true /* select */);
2036     }
2037 
2038     /**
2039      * Deselect a track.
2040      * <p>
2041      * Currently, the track must be a timed text track and no audio or video tracks can be
2042      * deselected. If the timed text track identified by index has not been
2043      * selected before, it throws an exception.
2044      * </p>
2045      * @param index the index of the track to be deselected. The valid range of the index
2046      * is 0..total number of tracks - 1. The total number of tracks as well as the type of
2047      * each individual track can be found by calling {@link #getTrackInfo()} method.
2048      * @throws IllegalStateException if called in an invalid state.
2049      *
2050      * @see android.media.MediaPlayer#getTrackInfo
2051      */
deselectTrack(int index)2052     public void deselectTrack(int index) throws IllegalStateException {
2053         selectOrDeselectTrack(index, false /* select */);
2054     }
2055 
selectOrDeselectTrack(int index, boolean select)2056     private void selectOrDeselectTrack(int index, boolean select)
2057             throws IllegalStateException {
2058         // handle subtitle track through subtitle controller
2059         SubtitleTrack track = null;
2060         if (index < mInbandSubtitleTracks.length) {
2061             track = mInbandSubtitleTracks[index];
2062         } else if (index < mInbandSubtitleTracks.length + mOutOfBandSubtitleTracks.size()) {
2063             track = mOutOfBandSubtitleTracks.get(index - mInbandSubtitleTracks.length);
2064         }
2065 
2066         if (mSubtitleController != null && track != null) {
2067             if (select) {
2068                 mSubtitleController.selectTrack(track);
2069             } else if (mSubtitleController.getSelectedTrack() == track) {
2070                 mSubtitleController.selectTrack(null);
2071             } else {
2072                 Log.w(TAG, "trying to deselect track that was not selected");
2073             }
2074             return;
2075         }
2076 
2077         selectOrDeselectInbandTrack(index, select);
2078     }
2079 
selectOrDeselectInbandTrack(int index, boolean select)2080     private void selectOrDeselectInbandTrack(int index, boolean select)
2081             throws IllegalStateException {
2082         Parcel request = Parcel.obtain();
2083         Parcel reply = Parcel.obtain();
2084         try {
2085             request.writeInterfaceToken(IMEDIA_PLAYER);
2086             request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
2087             request.writeInt(index);
2088             invoke(request, reply);
2089         } finally {
2090             request.recycle();
2091             reply.recycle();
2092         }
2093     }
2094 
2095 
2096     /**
2097      * @param reply Parcel with audio/video duration info for battery
2098                     tracking usage
2099      * @return The status code.
2100      * {@hide}
2101      */
native_pullBatteryData(Parcel reply)2102     public native static int native_pullBatteryData(Parcel reply);
2103 
2104     /**
2105      * Sets the target UDP re-transmit endpoint for the low level player.
2106      * Generally, the address portion of the endpoint is an IP multicast
2107      * address, although a unicast address would be equally valid.  When a valid
2108      * retransmit endpoint has been set, the media player will not decode and
2109      * render the media presentation locally.  Instead, the player will attempt
2110      * to re-multiplex its media data using the Android@Home RTP profile and
2111      * re-transmit to the target endpoint.  Receiver devices (which may be
2112      * either the same as the transmitting device or different devices) may
2113      * instantiate, prepare, and start a receiver player using a setDataSource
2114      * URL of the form...
2115      *
2116      * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
2117      *
2118      * to receive, decode and render the re-transmitted content.
2119      *
2120      * setRetransmitEndpoint may only be called before setDataSource has been
2121      * called; while the player is in the Idle state.
2122      *
2123      * @param endpoint the address and UDP port of the re-transmission target or
2124      * null if no re-transmission is to be performed.
2125      * @throws IllegalStateException if it is called in an invalid state
2126      * @throws IllegalArgumentException if the retransmit endpoint is supplied,
2127      * but invalid.
2128      *
2129      * {@hide} pending API council
2130      */
setRetransmitEndpoint(InetSocketAddress endpoint)2131     public void setRetransmitEndpoint(InetSocketAddress endpoint)
2132             throws IllegalStateException, IllegalArgumentException
2133     {
2134         String addrString = null;
2135         int port = 0;
2136 
2137         if (null != endpoint) {
2138             addrString = endpoint.getAddress().getHostAddress();
2139             port = endpoint.getPort();
2140         }
2141 
2142         int ret = native_setRetransmitEndpoint(addrString, port);
2143         if (ret != 0) {
2144             throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
2145         }
2146     }
2147 
native_setRetransmitEndpoint(String addrString, int port)2148     private native final int native_setRetransmitEndpoint(String addrString, int port);
2149 
2150     @Override
finalize()2151     protected void finalize() { native_finalize(); }
2152 
2153     /* Do not change these values without updating their counterparts
2154      * in include/media/mediaplayer.h!
2155      */
2156     private static final int MEDIA_NOP = 0; // interface test message
2157     private static final int MEDIA_PREPARED = 1;
2158     private static final int MEDIA_PLAYBACK_COMPLETE = 2;
2159     private static final int MEDIA_BUFFERING_UPDATE = 3;
2160     private static final int MEDIA_SEEK_COMPLETE = 4;
2161     private static final int MEDIA_SET_VIDEO_SIZE = 5;
2162     private static final int MEDIA_STARTED = 6;
2163     private static final int MEDIA_PAUSED = 7;
2164     private static final int MEDIA_STOPPED = 8;
2165     private static final int MEDIA_SKIPPED = 9;
2166     private static final int MEDIA_TIMED_TEXT = 99;
2167     private static final int MEDIA_ERROR = 100;
2168     private static final int MEDIA_INFO = 200;
2169     private static final int MEDIA_SUBTITLE_DATA = 201;
2170 
2171     private TimeProvider mTimeProvider;
2172 
2173     /** @hide */
getMediaTimeProvider()2174     public MediaTimeProvider getMediaTimeProvider() {
2175         if (mTimeProvider == null) {
2176             mTimeProvider = new TimeProvider(this);
2177         }
2178         return mTimeProvider;
2179     }
2180 
2181     private class EventHandler extends Handler
2182     {
2183         private MediaPlayer mMediaPlayer;
2184 
EventHandler(MediaPlayer mp, Looper looper)2185         public EventHandler(MediaPlayer mp, Looper looper) {
2186             super(looper);
2187             mMediaPlayer = mp;
2188         }
2189 
2190         @Override
handleMessage(Message msg)2191         public void handleMessage(Message msg) {
2192             if (mMediaPlayer.mNativeContext == 0) {
2193                 Log.w(TAG, "mediaplayer went away with unhandled events");
2194                 return;
2195             }
2196             switch(msg.what) {
2197             case MEDIA_PREPARED:
2198                 scanInternalSubtitleTracks();
2199                 if (mOnPreparedListener != null)
2200                     mOnPreparedListener.onPrepared(mMediaPlayer);
2201                 return;
2202 
2203             case MEDIA_PLAYBACK_COMPLETE:
2204                 if (mOnCompletionListener != null)
2205                     mOnCompletionListener.onCompletion(mMediaPlayer);
2206                 stayAwake(false);
2207                 return;
2208 
2209             case MEDIA_STOPPED:
2210                 if (mTimeProvider != null) {
2211                     mTimeProvider.onStopped();
2212                 }
2213                 break;
2214 
2215             case MEDIA_STARTED:
2216             case MEDIA_PAUSED:
2217                 if (mTimeProvider != null) {
2218                     mTimeProvider.onPaused(msg.what == MEDIA_PAUSED);
2219                 }
2220                 break;
2221 
2222             case MEDIA_BUFFERING_UPDATE:
2223                 if (mOnBufferingUpdateListener != null)
2224                     mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
2225                 return;
2226 
2227             case MEDIA_SEEK_COMPLETE:
2228               if (mOnSeekCompleteListener != null) {
2229                   mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
2230               }
2231               // fall through
2232 
2233             case MEDIA_SKIPPED:
2234               if (mTimeProvider != null) {
2235                   mTimeProvider.onSeekComplete(mMediaPlayer);
2236               }
2237               return;
2238 
2239             case MEDIA_SET_VIDEO_SIZE:
2240               if (mOnVideoSizeChangedListener != null)
2241                   mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
2242               return;
2243 
2244             case MEDIA_ERROR:
2245                 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
2246                 boolean error_was_handled = false;
2247                 if (mOnErrorListener != null) {
2248                     error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
2249                 }
2250                 if (mOnCompletionListener != null && ! error_was_handled) {
2251                     mOnCompletionListener.onCompletion(mMediaPlayer);
2252                 }
2253                 stayAwake(false);
2254                 return;
2255 
2256             case MEDIA_INFO:
2257                 switch (msg.arg1) {
2258                 case MEDIA_INFO_VIDEO_TRACK_LAGGING:
2259                     Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
2260                     break;
2261                 case MEDIA_INFO_METADATA_UPDATE:
2262                     scanInternalSubtitleTracks();
2263                     // fall through
2264 
2265                 case MEDIA_INFO_EXTERNAL_METADATA_UPDATE:
2266                     msg.arg1 = MEDIA_INFO_METADATA_UPDATE;
2267                     // update default track selection
2268                     mSubtitleController.selectDefaultTrack();
2269                     break;
2270                 }
2271 
2272                 if (mOnInfoListener != null) {
2273                     mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
2274                 }
2275                 // No real default action so far.
2276                 return;
2277             case MEDIA_TIMED_TEXT:
2278                 if (mOnTimedTextListener == null)
2279                     return;
2280                 if (msg.obj == null) {
2281                     mOnTimedTextListener.onTimedText(mMediaPlayer, null);
2282                 } else {
2283                     if (msg.obj instanceof Parcel) {
2284                         Parcel parcel = (Parcel)msg.obj;
2285                         TimedText text = new TimedText(parcel);
2286                         parcel.recycle();
2287                         mOnTimedTextListener.onTimedText(mMediaPlayer, text);
2288                     }
2289                 }
2290                 return;
2291 
2292             case MEDIA_SUBTITLE_DATA:
2293                 if (mOnSubtitleDataListener == null) {
2294                     return;
2295                 }
2296                 if (msg.obj instanceof Parcel) {
2297                     Parcel parcel = (Parcel) msg.obj;
2298                     SubtitleData data = new SubtitleData(parcel);
2299                     parcel.recycle();
2300                     mOnSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
2301                 }
2302                 return;
2303 
2304             case MEDIA_NOP: // interface test message - ignore
2305                 break;
2306 
2307             default:
2308                 Log.e(TAG, "Unknown message type " + msg.what);
2309                 return;
2310             }
2311         }
2312     }
2313 
2314     /*
2315      * Called from native code when an interesting event happens.  This method
2316      * just uses the EventHandler system to post the event back to the main app thread.
2317      * We use a weak reference to the original MediaPlayer object so that the native
2318      * code is safe from the object disappearing from underneath it.  (This is
2319      * the cookie passed to native_setup().)
2320      */
postEventFromNative(Object mediaplayer_ref, int what, int arg1, int arg2, Object obj)2321     private static void postEventFromNative(Object mediaplayer_ref,
2322                                             int what, int arg1, int arg2, Object obj)
2323     {
2324         MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
2325         if (mp == null) {
2326             return;
2327         }
2328 
2329         if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
2330             // this acquires the wakelock if needed, and sets the client side state
2331             mp.start();
2332         }
2333         if (mp.mEventHandler != null) {
2334             Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
2335             mp.mEventHandler.sendMessage(m);
2336         }
2337     }
2338 
2339     /**
2340      * Interface definition for a callback to be invoked when the media
2341      * source is ready for playback.
2342      */
2343     public interface OnPreparedListener
2344     {
2345         /**
2346          * Called when the media file is ready for playback.
2347          *
2348          * @param mp the MediaPlayer that is ready for playback
2349          */
onPrepared(MediaPlayer mp)2350         void onPrepared(MediaPlayer mp);
2351     }
2352 
2353     /**
2354      * Register a callback to be invoked when the media source is ready
2355      * for playback.
2356      *
2357      * @param listener the callback that will be run
2358      */
setOnPreparedListener(OnPreparedListener listener)2359     public void setOnPreparedListener(OnPreparedListener listener)
2360     {
2361         mOnPreparedListener = listener;
2362     }
2363 
2364     private OnPreparedListener mOnPreparedListener;
2365 
2366     /**
2367      * Interface definition for a callback to be invoked when playback of
2368      * a media source has completed.
2369      */
2370     public interface OnCompletionListener
2371     {
2372         /**
2373          * Called when the end of a media source is reached during playback.
2374          *
2375          * @param mp the MediaPlayer that reached the end of the file
2376          */
onCompletion(MediaPlayer mp)2377         void onCompletion(MediaPlayer mp);
2378     }
2379 
2380     /**
2381      * Register a callback to be invoked when the end of a media source
2382      * has been reached during playback.
2383      *
2384      * @param listener the callback that will be run
2385      */
setOnCompletionListener(OnCompletionListener listener)2386     public void setOnCompletionListener(OnCompletionListener listener)
2387     {
2388         mOnCompletionListener = listener;
2389     }
2390 
2391     private OnCompletionListener mOnCompletionListener;
2392 
2393     /**
2394      * Interface definition of a callback to be invoked indicating buffering
2395      * status of a media resource being streamed over the network.
2396      */
2397     public interface OnBufferingUpdateListener
2398     {
2399         /**
2400          * Called to update status in buffering a media stream received through
2401          * progressive HTTP download. The received buffering percentage
2402          * indicates how much of the content has been buffered or played.
2403          * For example a buffering update of 80 percent when half the content
2404          * has already been played indicates that the next 30 percent of the
2405          * content to play has been buffered.
2406          *
2407          * @param mp      the MediaPlayer the update pertains to
2408          * @param percent the percentage (0-100) of the content
2409          *                that has been buffered or played thus far
2410          */
onBufferingUpdate(MediaPlayer mp, int percent)2411         void onBufferingUpdate(MediaPlayer mp, int percent);
2412     }
2413 
2414     /**
2415      * Register a callback to be invoked when the status of a network
2416      * stream's buffer has changed.
2417      *
2418      * @param listener the callback that will be run.
2419      */
setOnBufferingUpdateListener(OnBufferingUpdateListener listener)2420     public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
2421     {
2422         mOnBufferingUpdateListener = listener;
2423     }
2424 
2425     private OnBufferingUpdateListener mOnBufferingUpdateListener;
2426 
2427     /**
2428      * Interface definition of a callback to be invoked indicating
2429      * the completion of a seek operation.
2430      */
2431     public interface OnSeekCompleteListener
2432     {
2433         /**
2434          * Called to indicate the completion of a seek operation.
2435          *
2436          * @param mp the MediaPlayer that issued the seek operation
2437          */
onSeekComplete(MediaPlayer mp)2438         public void onSeekComplete(MediaPlayer mp);
2439     }
2440 
2441     /**
2442      * Register a callback to be invoked when a seek operation has been
2443      * completed.
2444      *
2445      * @param listener the callback that will be run
2446      */
setOnSeekCompleteListener(OnSeekCompleteListener listener)2447     public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
2448     {
2449         mOnSeekCompleteListener = listener;
2450     }
2451 
2452     private OnSeekCompleteListener mOnSeekCompleteListener;
2453 
2454     /**
2455      * Interface definition of a callback to be invoked when the
2456      * video size is first known or updated
2457      */
2458     public interface OnVideoSizeChangedListener
2459     {
2460         /**
2461          * Called to indicate the video size
2462          *
2463          * The video size (width and height) could be 0 if there was no video,
2464          * no display surface was set, or the value was not determined yet.
2465          *
2466          * @param mp        the MediaPlayer associated with this callback
2467          * @param width     the width of the video
2468          * @param height    the height of the video
2469          */
onVideoSizeChanged(MediaPlayer mp, int width, int height)2470         public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
2471     }
2472 
2473     /**
2474      * Register a callback to be invoked when the video size is
2475      * known or updated.
2476      *
2477      * @param listener the callback that will be run
2478      */
setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)2479     public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
2480     {
2481         mOnVideoSizeChangedListener = listener;
2482     }
2483 
2484     private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
2485 
2486     /**
2487      * Interface definition of a callback to be invoked when a
2488      * timed text is available for display.
2489      */
2490     public interface OnTimedTextListener
2491     {
2492         /**
2493          * Called to indicate an avaliable timed text
2494          *
2495          * @param mp             the MediaPlayer associated with this callback
2496          * @param text           the timed text sample which contains the text
2497          *                       needed to be displayed and the display format.
2498          */
onTimedText(MediaPlayer mp, TimedText text)2499         public void onTimedText(MediaPlayer mp, TimedText text);
2500     }
2501 
2502     /**
2503      * Register a callback to be invoked when a timed text is available
2504      * for display.
2505      *
2506      * @param listener the callback that will be run
2507      */
setOnTimedTextListener(OnTimedTextListener listener)2508     public void setOnTimedTextListener(OnTimedTextListener listener)
2509     {
2510         mOnTimedTextListener = listener;
2511     }
2512 
2513     private OnTimedTextListener mOnTimedTextListener;
2514 
2515     /**
2516      * Interface definition of a callback to be invoked when a
2517      * track has data available.
2518      *
2519      * @hide
2520      */
2521     public interface OnSubtitleDataListener
2522     {
onSubtitleData(MediaPlayer mp, SubtitleData data)2523         public void onSubtitleData(MediaPlayer mp, SubtitleData data);
2524     }
2525 
2526     /**
2527      * Register a callback to be invoked when a track has data available.
2528      *
2529      * @param listener the callback that will be run
2530      *
2531      * @hide
2532      */
setOnSubtitleDataListener(OnSubtitleDataListener listener)2533     public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
2534     {
2535         mOnSubtitleDataListener = listener;
2536     }
2537 
2538     private OnSubtitleDataListener mOnSubtitleDataListener;
2539 
2540     /* Do not change these values without updating their counterparts
2541      * in include/media/mediaplayer.h!
2542      */
2543     /** Unspecified media player error.
2544      * @see android.media.MediaPlayer.OnErrorListener
2545      */
2546     public static final int MEDIA_ERROR_UNKNOWN = 1;
2547 
2548     /** Media server died. In this case, the application must release the
2549      * MediaPlayer object and instantiate a new one.
2550      * @see android.media.MediaPlayer.OnErrorListener
2551      */
2552     public static final int MEDIA_ERROR_SERVER_DIED = 100;
2553 
2554     /** The video is streamed and its container is not valid for progressive
2555      * playback i.e the video's index (e.g moov atom) is not at the start of the
2556      * file.
2557      * @see android.media.MediaPlayer.OnErrorListener
2558      */
2559     public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
2560 
2561     /** File or network related operation errors. */
2562     public static final int MEDIA_ERROR_IO = -1004;
2563     /** Bitstream is not conforming to the related coding standard or file spec. */
2564     public static final int MEDIA_ERROR_MALFORMED = -1007;
2565     /** Bitstream is conforming to the related coding standard or file spec, but
2566      * the media framework does not support the feature. */
2567     public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
2568     /** Some operation takes too long to complete, usually more than 3-5 seconds. */
2569     public static final int MEDIA_ERROR_TIMED_OUT = -110;
2570 
2571     /**
2572      * Interface definition of a callback to be invoked when there
2573      * has been an error during an asynchronous operation (other errors
2574      * will throw exceptions at method call time).
2575      */
2576     public interface OnErrorListener
2577     {
2578         /**
2579          * Called to indicate an error.
2580          *
2581          * @param mp      the MediaPlayer the error pertains to
2582          * @param what    the type of error that has occurred:
2583          * <ul>
2584          * <li>{@link #MEDIA_ERROR_UNKNOWN}
2585          * <li>{@link #MEDIA_ERROR_SERVER_DIED}
2586          * </ul>
2587          * @param extra an extra code, specific to the error. Typically
2588          * implementation dependent.
2589          * <ul>
2590          * <li>{@link #MEDIA_ERROR_IO}
2591          * <li>{@link #MEDIA_ERROR_MALFORMED}
2592          * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
2593          * <li>{@link #MEDIA_ERROR_TIMED_OUT}
2594          * </ul>
2595          * @return True if the method handled the error, false if it didn't.
2596          * Returning false, or not having an OnErrorListener at all, will
2597          * cause the OnCompletionListener to be called.
2598          */
onError(MediaPlayer mp, int what, int extra)2599         boolean onError(MediaPlayer mp, int what, int extra);
2600     }
2601 
2602     /**
2603      * Register a callback to be invoked when an error has happened
2604      * during an asynchronous operation.
2605      *
2606      * @param listener the callback that will be run
2607      */
setOnErrorListener(OnErrorListener listener)2608     public void setOnErrorListener(OnErrorListener listener)
2609     {
2610         mOnErrorListener = listener;
2611     }
2612 
2613     private OnErrorListener mOnErrorListener;
2614 
2615 
2616     /* Do not change these values without updating their counterparts
2617      * in include/media/mediaplayer.h!
2618      */
2619     /** Unspecified media player info.
2620      * @see android.media.MediaPlayer.OnInfoListener
2621      */
2622     public static final int MEDIA_INFO_UNKNOWN = 1;
2623 
2624     /** The player was started because it was used as the next player for another
2625      * player, which just completed playback.
2626      * @see android.media.MediaPlayer.OnInfoListener
2627      * @hide
2628      */
2629     public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
2630 
2631     /** The player just pushed the very first video frame for rendering.
2632      * @see android.media.MediaPlayer.OnInfoListener
2633      */
2634     public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
2635 
2636     /** The video is too complex for the decoder: it can't decode frames fast
2637      *  enough. Possibly only the audio plays fine at this stage.
2638      * @see android.media.MediaPlayer.OnInfoListener
2639      */
2640     public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
2641 
2642     /** MediaPlayer is temporarily pausing playback internally in order to
2643      * buffer more data.
2644      * @see android.media.MediaPlayer.OnInfoListener
2645      */
2646     public static final int MEDIA_INFO_BUFFERING_START = 701;
2647 
2648     /** MediaPlayer is resuming playback after filling buffers.
2649      * @see android.media.MediaPlayer.OnInfoListener
2650      */
2651     public static final int MEDIA_INFO_BUFFERING_END = 702;
2652 
2653     /** Bad interleaving means that a media has been improperly interleaved or
2654      * not interleaved at all, e.g has all the video samples first then all the
2655      * audio ones. Video is playing but a lot of disk seeks may be happening.
2656      * @see android.media.MediaPlayer.OnInfoListener
2657      */
2658     public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
2659 
2660     /** The media cannot be seeked (e.g live stream)
2661      * @see android.media.MediaPlayer.OnInfoListener
2662      */
2663     public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
2664 
2665     /** A new set of metadata is available.
2666      * @see android.media.MediaPlayer.OnInfoListener
2667      */
2668     public static final int MEDIA_INFO_METADATA_UPDATE = 802;
2669 
2670     /** A new set of external-only metadata is available.  Used by
2671      *  JAVA framework to avoid triggering track scanning.
2672      * @hide
2673      */
2674     public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
2675 
2676     /** Failed to handle timed text track properly.
2677      * @see android.media.MediaPlayer.OnInfoListener
2678      *
2679      * {@hide}
2680      */
2681     public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
2682 
2683     /** Subtitle track was not supported by the media framework.
2684      * @see android.media.MediaPlayer.OnInfoListener
2685      */
2686     public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
2687 
2688     /** Reading the subtitle track takes too long.
2689      * @see android.media.MediaPlayer.OnInfoListener
2690      */
2691     public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
2692 
2693     /**
2694      * Interface definition of a callback to be invoked to communicate some
2695      * info and/or warning about the media or its playback.
2696      */
2697     public interface OnInfoListener
2698     {
2699         /**
2700          * Called to indicate an info or a warning.
2701          *
2702          * @param mp      the MediaPlayer the info pertains to.
2703          * @param what    the type of info or warning.
2704          * <ul>
2705          * <li>{@link #MEDIA_INFO_UNKNOWN}
2706          * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
2707          * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
2708          * <li>{@link #MEDIA_INFO_BUFFERING_START}
2709          * <li>{@link #MEDIA_INFO_BUFFERING_END}
2710          * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
2711          * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
2712          * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
2713          * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE}
2714          * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT}
2715          * </ul>
2716          * @param extra an extra code, specific to the info. Typically
2717          * implementation dependent.
2718          * @return True if the method handled the info, false if it didn't.
2719          * Returning false, or not having an OnErrorListener at all, will
2720          * cause the info to be discarded.
2721          */
onInfo(MediaPlayer mp, int what, int extra)2722         boolean onInfo(MediaPlayer mp, int what, int extra);
2723     }
2724 
2725     /**
2726      * Register a callback to be invoked when an info/warning is available.
2727      *
2728      * @param listener the callback that will be run
2729      */
setOnInfoListener(OnInfoListener listener)2730     public void setOnInfoListener(OnInfoListener listener)
2731     {
2732         mOnInfoListener = listener;
2733     }
2734 
2735     private OnInfoListener mOnInfoListener;
2736 
2737     /*
2738      * Test whether a given video scaling mode is supported.
2739      */
isVideoScalingModeSupported(int mode)2740     private boolean isVideoScalingModeSupported(int mode) {
2741         return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
2742                 mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
2743     }
2744 
2745     private Context mProxyContext = null;
2746     private ProxyReceiver mProxyReceiver = null;
2747 
setupProxyListener(Context context)2748     private void setupProxyListener(Context context) {
2749         IntentFilter filter = new IntentFilter();
2750         filter.addAction(Proxy.PROXY_CHANGE_ACTION);
2751         mProxyReceiver = new ProxyReceiver();
2752         mProxyContext = context;
2753 
2754         Intent currentProxy =
2755             context.getApplicationContext().registerReceiver(mProxyReceiver, filter);
2756 
2757         if (currentProxy != null) {
2758             handleProxyBroadcast(currentProxy);
2759         }
2760     }
2761 
disableProxyListener()2762     private void disableProxyListener() {
2763         if (mProxyReceiver == null) {
2764             return;
2765         }
2766 
2767         Context appContext = mProxyContext.getApplicationContext();
2768         if (appContext != null) {
2769             appContext.unregisterReceiver(mProxyReceiver);
2770         }
2771 
2772         mProxyReceiver = null;
2773         mProxyContext = null;
2774     }
2775 
handleProxyBroadcast(Intent intent)2776     private void handleProxyBroadcast(Intent intent) {
2777         ProxyProperties props =
2778             (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO);
2779 
2780         if (props == null || props.getHost() == null) {
2781             updateProxyConfig(null);
2782         } else {
2783             updateProxyConfig(props);
2784         }
2785     }
2786 
2787     private class ProxyReceiver extends BroadcastReceiver {
2788         @Override
onReceive(Context context, Intent intent)2789         public void onReceive(Context context, Intent intent) {
2790             if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) {
2791                 handleProxyBroadcast(intent);
2792             }
2793         }
2794     }
2795 
updateProxyConfig(ProxyProperties props)2796     private native void updateProxyConfig(ProxyProperties props);
2797 
2798     /** @hide */
2799     static class TimeProvider implements MediaPlayer.OnSeekCompleteListener,
2800             MediaTimeProvider {
2801         private static final String TAG = "MTP";
2802         private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L;
2803         private static final long MAX_EARLY_CALLBACK_US = 1000;
2804         private static final long TIME_ADJUSTMENT_RATE = 2;  /* meaning 1/2 */
2805         private long mLastTimeUs = 0;
2806         private MediaPlayer mPlayer;
2807         private boolean mPaused = true;
2808         private boolean mStopped = true;
2809         private long mLastReportedTime;
2810         private long mTimeAdjustment;
2811         // since we are expecting only a handful listeners per stream, there is
2812         // no need for log(N) search performance
2813         private MediaTimeProvider.OnMediaTimeListener mListeners[];
2814         private long mTimes[];
2815         private long mLastNanoTime;
2816         private Handler mEventHandler;
2817         private boolean mRefresh = false;
2818         private boolean mPausing = false;
2819         private boolean mSeeking = false;
2820         private static final int NOTIFY = 1;
2821         private static final int NOTIFY_TIME = 0;
2822         private static final int REFRESH_AND_NOTIFY_TIME = 1;
2823         private static final int NOTIFY_STOP = 2;
2824         private static final int NOTIFY_SEEK = 3;
2825         private HandlerThread mHandlerThread;
2826 
2827         /** @hide */
2828         public boolean DEBUG = false;
2829 
TimeProvider(MediaPlayer mp)2830         public TimeProvider(MediaPlayer mp) {
2831             mPlayer = mp;
2832             try {
2833                 getCurrentTimeUs(true, false);
2834             } catch (IllegalStateException e) {
2835                 // we assume starting position
2836                 mRefresh = true;
2837             }
2838 
2839             Looper looper;
2840             if ((looper = Looper.myLooper()) == null &&
2841                 (looper = Looper.getMainLooper()) == null) {
2842                 // Create our own looper here in case MP was created without one
2843                 mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread",
2844                       Process.THREAD_PRIORITY_FOREGROUND);
2845                 mHandlerThread.start();
2846                 looper = mHandlerThread.getLooper();
2847             }
2848             mEventHandler = new EventHandler(looper);
2849 
2850             mListeners = new MediaTimeProvider.OnMediaTimeListener[0];
2851             mTimes = new long[0];
2852             mLastTimeUs = 0;
2853             mTimeAdjustment = 0;
2854         }
2855 
scheduleNotification(int type, long delayUs)2856         private void scheduleNotification(int type, long delayUs) {
2857             // ignore time notifications until seek is handled
2858             if (mSeeking &&
2859                     (type == NOTIFY_TIME || type == REFRESH_AND_NOTIFY_TIME)) {
2860                 return;
2861             }
2862 
2863             if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs);
2864             mEventHandler.removeMessages(NOTIFY);
2865             Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0);
2866             mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000));
2867         }
2868 
2869         /** @hide */
close()2870         public void close() {
2871             mEventHandler.removeMessages(NOTIFY);
2872             if (mHandlerThread != null) {
2873                 mHandlerThread.quitSafely();
2874                 mHandlerThread = null;
2875             }
2876         }
2877 
2878         /** @hide */
finalize()2879         protected void finalize() {
2880             if (mHandlerThread != null) {
2881                 mHandlerThread.quitSafely();
2882             }
2883         }
2884 
2885         /** @hide */
onPaused(boolean paused)2886         public void onPaused(boolean paused) {
2887             synchronized(this) {
2888                 if (DEBUG) Log.d(TAG, "onPaused: " + paused);
2889                 if (mStopped) { // handle as seek if we were stopped
2890                     mStopped = false;
2891                     mSeeking = true;
2892                     scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2893                 } else {
2894                     mPausing = paused;  // special handling if player disappeared
2895                     mSeeking = false;
2896                     scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
2897                 }
2898             }
2899         }
2900 
2901         /** @hide */
onStopped()2902         public void onStopped() {
2903             synchronized(this) {
2904                 if (DEBUG) Log.d(TAG, "onStopped");
2905                 mPaused = true;
2906                 mStopped = true;
2907                 mSeeking = false;
2908                 scheduleNotification(NOTIFY_STOP, 0 /* delay */);
2909             }
2910         }
2911 
2912         /** @hide */
2913         @Override
onSeekComplete(MediaPlayer mp)2914         public void onSeekComplete(MediaPlayer mp) {
2915             synchronized(this) {
2916                 mStopped = false;
2917                 mSeeking = true;
2918                 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2919             }
2920         }
2921 
2922         /** @hide */
onNewPlayer()2923         public void onNewPlayer() {
2924             if (mRefresh) {
2925                 synchronized(this) {
2926                     mStopped = false;
2927                     mSeeking = true;
2928                     scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2929                 }
2930             }
2931         }
2932 
notifySeek()2933         private synchronized void notifySeek() {
2934             mSeeking = false;
2935             try {
2936                 long timeUs = getCurrentTimeUs(true, false);
2937                 if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs);
2938 
2939                 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
2940                     if (listener == null) {
2941                         break;
2942                     }
2943                     listener.onSeek(timeUs);
2944                 }
2945             } catch (IllegalStateException e) {
2946                 // we should not be there, but at least signal pause
2947                 if (DEBUG) Log.d(TAG, "onSeekComplete but no player");
2948                 mPausing = true;  // special handling if player disappeared
2949                 notifyTimedEvent(false /* refreshTime */);
2950             }
2951         }
2952 
notifyStop()2953         private synchronized void notifyStop() {
2954             for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
2955                 if (listener == null) {
2956                     break;
2957                 }
2958                 listener.onStop();
2959             }
2960         }
2961 
registerListener(MediaTimeProvider.OnMediaTimeListener listener)2962         private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) {
2963             int i = 0;
2964             for (; i < mListeners.length; i++) {
2965                 if (mListeners[i] == listener || mListeners[i] == null) {
2966                     break;
2967                 }
2968             }
2969 
2970             // new listener
2971             if (i >= mListeners.length) {
2972                 MediaTimeProvider.OnMediaTimeListener[] newListeners =
2973                     new MediaTimeProvider.OnMediaTimeListener[i + 1];
2974                 long[] newTimes = new long[i + 1];
2975                 System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length);
2976                 System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length);
2977                 mListeners = newListeners;
2978                 mTimes = newTimes;
2979             }
2980 
2981             if (mListeners[i] == null) {
2982                 mListeners[i] = listener;
2983                 mTimes[i] = MediaTimeProvider.NO_TIME;
2984             }
2985             return i;
2986         }
2987 
notifyAt( long timeUs, MediaTimeProvider.OnMediaTimeListener listener)2988         public void notifyAt(
2989                 long timeUs, MediaTimeProvider.OnMediaTimeListener listener) {
2990             synchronized(this) {
2991                 if (DEBUG) Log.d(TAG, "notifyAt " + timeUs);
2992                 mTimes[registerListener(listener)] = timeUs;
2993                 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2994             }
2995         }
2996 
scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener)2997         public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) {
2998             synchronized(this) {
2999                 if (DEBUG) Log.d(TAG, "scheduleUpdate");
3000                 int i = registerListener(listener);
3001 
3002                 if (mStopped) {
3003                     scheduleNotification(NOTIFY_STOP, 0 /* delay */);
3004                 } else {
3005                     mTimes[i] = 0;
3006                     scheduleNotification(NOTIFY_TIME, 0 /* delay */);
3007                 }
3008             }
3009         }
3010 
cancelNotifications( MediaTimeProvider.OnMediaTimeListener listener)3011         public void cancelNotifications(
3012                 MediaTimeProvider.OnMediaTimeListener listener) {
3013             synchronized(this) {
3014                 int i = 0;
3015                 for (; i < mListeners.length; i++) {
3016                     if (mListeners[i] == listener) {
3017                         System.arraycopy(mListeners, i + 1,
3018                                 mListeners, i, mListeners.length - i - 1);
3019                         System.arraycopy(mTimes, i + 1,
3020                                 mTimes, i, mTimes.length - i - 1);
3021                         mListeners[mListeners.length - 1] = null;
3022                         mTimes[mTimes.length - 1] = NO_TIME;
3023                         break;
3024                     } else if (mListeners[i] == null) {
3025                         break;
3026                     }
3027                 }
3028 
3029                 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
3030             }
3031         }
3032 
notifyTimedEvent(boolean refreshTime)3033         private synchronized void notifyTimedEvent(boolean refreshTime) {
3034             // figure out next callback
3035             long nowUs;
3036             try {
3037                 nowUs = getCurrentTimeUs(refreshTime, true);
3038             } catch (IllegalStateException e) {
3039                 // assume we paused until new player arrives
3040                 mRefresh = true;
3041                 mPausing = true; // this ensures that call succeeds
3042                 nowUs = getCurrentTimeUs(refreshTime, true);
3043             }
3044             long nextTimeUs = nowUs;
3045 
3046             if (mSeeking) {
3047                 // skip timed-event notifications until seek is complete
3048                 return;
3049             }
3050 
3051             if (DEBUG) {
3052                 StringBuilder sb = new StringBuilder();
3053                 sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ")
3054                         .append(nowUs).append(") from {");
3055                 boolean first = true;
3056                 for (long time: mTimes) {
3057                     if (time == NO_TIME) {
3058                         continue;
3059                     }
3060                     if (!first) sb.append(", ");
3061                     sb.append(time);
3062                     first = false;
3063                 }
3064                 sb.append("}");
3065                 Log.d(TAG, sb.toString());
3066             }
3067 
3068             Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners =
3069                 new Vector<MediaTimeProvider.OnMediaTimeListener>();
3070             for (int ix = 0; ix < mTimes.length; ix++) {
3071                 if (mListeners[ix] == null) {
3072                     break;
3073                 }
3074                 if (mTimes[ix] <= NO_TIME) {
3075                     // ignore, unless we were stopped
3076                 } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) {
3077                     activatedListeners.add(mListeners[ix]);
3078                     if (DEBUG) Log.d(TAG, "removed");
3079                     mTimes[ix] = NO_TIME;
3080                 } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) {
3081                     nextTimeUs = mTimes[ix];
3082                 }
3083             }
3084 
3085             if (nextTimeUs > nowUs && !mPaused) {
3086                 // schedule callback at nextTimeUs
3087                 if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs);
3088                 scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs);
3089             } else {
3090                 mEventHandler.removeMessages(NOTIFY);
3091                 // no more callbacks
3092             }
3093 
3094             for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) {
3095                 listener.onTimedEvent(nowUs);
3096             }
3097         }
3098 
getEstimatedTime(long nanoTime, boolean monotonic)3099         private long getEstimatedTime(long nanoTime, boolean monotonic) {
3100             if (mPaused) {
3101                 mLastReportedTime = mLastTimeUs + mTimeAdjustment;
3102             } else {
3103                 long timeSinceRead = (nanoTime - mLastNanoTime) / 1000;
3104                 mLastReportedTime = mLastTimeUs + timeSinceRead;
3105                 if (mTimeAdjustment > 0) {
3106                     long adjustment =
3107                         mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE;
3108                     if (adjustment <= 0) {
3109                         mTimeAdjustment = 0;
3110                     } else {
3111                         mLastReportedTime += adjustment;
3112                     }
3113                 }
3114             }
3115             return mLastReportedTime;
3116         }
3117 
getCurrentTimeUs(boolean refreshTime, boolean monotonic)3118         public long getCurrentTimeUs(boolean refreshTime, boolean monotonic)
3119                 throws IllegalStateException {
3120             synchronized (this) {
3121                 // we always refresh the time when the paused-state changes, because
3122                 // we expect to have received the pause-change event delayed.
3123                 if (mPaused && !refreshTime) {
3124                     return mLastReportedTime;
3125                 }
3126 
3127                 long nanoTime = System.nanoTime();
3128                 if (refreshTime ||
3129                         nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) {
3130                     try {
3131                         mLastTimeUs = mPlayer.getCurrentPosition() * 1000L;
3132                         mPaused = !mPlayer.isPlaying();
3133                         if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs);
3134                     } catch (IllegalStateException e) {
3135                         if (mPausing) {
3136                             // if we were pausing, get last estimated timestamp
3137                             mPausing = false;
3138                             getEstimatedTime(nanoTime, monotonic);
3139                             mPaused = true;
3140                             if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime);
3141                             return mLastReportedTime;
3142                         }
3143                         // TODO get time when prepared
3144                         throw e;
3145                     }
3146                     mLastNanoTime = nanoTime;
3147                     if (monotonic && mLastTimeUs < mLastReportedTime) {
3148                         /* have to adjust time */
3149                         mTimeAdjustment = mLastReportedTime - mLastTimeUs;
3150                         if (mTimeAdjustment > 1000000) {
3151                             // schedule seeked event if time jumped significantly
3152                             // TODO: do this properly by introducing an exception
3153                             mStopped = false;
3154                             mSeeking = true;
3155                             scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
3156                         }
3157                     } else {
3158                         mTimeAdjustment = 0;
3159                     }
3160                 }
3161 
3162                 return getEstimatedTime(nanoTime, monotonic);
3163             }
3164         }
3165 
3166         private class EventHandler extends Handler {
EventHandler(Looper looper)3167             public EventHandler(Looper looper) {
3168                 super(looper);
3169             }
3170 
3171             @Override
handleMessage(Message msg)3172             public void handleMessage(Message msg) {
3173                 if (msg.what == NOTIFY) {
3174                     switch (msg.arg1) {
3175                     case NOTIFY_TIME:
3176                         notifyTimedEvent(false /* refreshTime */);
3177                         break;
3178                     case REFRESH_AND_NOTIFY_TIME:
3179                         notifyTimedEvent(true /* refreshTime */);
3180                         break;
3181                     case NOTIFY_STOP:
3182                         notifyStop();
3183                         break;
3184                     case NOTIFY_SEEK:
3185                         notifySeek();
3186                         break;
3187                     }
3188                 }
3189             }
3190         }
3191     }
3192 }
3193