MediaPlayer.java revision d486f9656a6f9d6c056d84fce39f3db8d1614e1d
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.media;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.res.AssetFileDescriptor;
25import android.net.Proxy;
26import android.net.ProxyProperties;
27import android.net.Uri;
28import android.os.Handler;
29import android.os.HandlerThread;
30import android.os.Looper;
31import android.os.Message;
32import android.os.Parcel;
33import android.os.Parcelable;
34import android.os.ParcelFileDescriptor;
35import android.os.Process;
36import android.os.PowerManager;
37import android.util.Log;
38import android.view.Surface;
39import android.view.SurfaceHolder;
40import android.graphics.Bitmap;
41import android.graphics.SurfaceTexture;
42import android.media.AudioManager;
43import android.media.MediaFormat;
44import android.media.MediaTimeProvider;
45import android.media.MediaTimeProvider.OnMediaTimeListener;
46import android.media.SubtitleController;
47import android.media.SubtitleData;
48
49import java.io.File;
50import java.io.FileDescriptor;
51import java.io.FileInputStream;
52import java.io.IOException;
53import java.io.InputStream;
54import java.lang.Runnable;
55import java.net.InetSocketAddress;
56import java.util.Map;
57import java.util.Scanner;
58import java.util.Set;
59import java.util.Vector;
60import 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 */
529public 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");
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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
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
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     */
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     */
1022    public void setDataSource(FileDescriptor fd, long offset, long length)
1023            throws IOException, IllegalArgumentException, IllegalStateException {
1024        disableProxyListener();
1025        _setDataSource(fd, offset, length);
1026    }
1027
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     */
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     */
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     */
1062    public  void start() throws IllegalStateException {
1063        stayAwake(true);
1064        _start();
1065    }
1066
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     */
1075    public void stop() throws IllegalStateException {
1076        stayAwake(false);
1077        _stop();
1078    }
1079
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     */
1088    public void pause() throws IllegalStateException {
1089        stayAwake(false);
1090        _pause();
1091    }
1092
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     */
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     */
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
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
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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
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     */
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
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
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     */
1545    private native final int native_setMetadataFilter(Parcel request);
1546
1547    private static native final void native_init();
1548    private native final void native_setup(Object mediaplayer_this);
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         */
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         */
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         */
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
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 */
1619        TrackInfo(int type, MediaFormat format) {
1620            mTrackType = type;
1621            mFormat = format;
1622        }
1623
1624        /**
1625         * {@inheritDoc}
1626         */
1627        @Override
1628        public int describeContents() {
1629            return 0;
1630        }
1631
1632        /**
1633         * {@inheritDoc}
1634         */
1635        @Override
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     */
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
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     */
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 */
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
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        for (int i = 0; i < mInbandSubtitleTracks.length; i++) {
1776            if (mInbandSubtitleTracks[i] == track) {
1777                Log.v(TAG, "Selecting subtitle track " + i);
1778                mSelectedSubtitleTrackIndex = i;
1779                try {
1780                    selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, true);
1781                } catch (IllegalStateException e) {
1782                }
1783                setOnSubtitleDataListener(mSubtitleDataListener);
1784                break;
1785            }
1786        }
1787        // no need to select out-of-band tracks
1788    }
1789
1790    /** @hide */
1791    public void addSubtitleSource(InputStream is, MediaFormat format)
1792            throws IllegalStateException
1793    {
1794        final InputStream fIs = is;
1795        final MediaFormat fFormat = format;
1796
1797        // Ensure all input streams are closed.  It is also a handy
1798        // way to implement timeouts in the future.
1799        synchronized(mOpenSubtitleSources) {
1800            mOpenSubtitleSources.add(is);
1801        }
1802
1803        // process each subtitle in its own thread
1804        final HandlerThread thread = new HandlerThread("SubtitleReadThread",
1805              Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
1806        thread.start();
1807        Handler handler = new Handler(thread.getLooper());
1808        handler.post(new Runnable() {
1809            private int addTrack() {
1810                if (fIs == null || mSubtitleController == null) {
1811                    return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
1812                }
1813
1814                SubtitleTrack track = mSubtitleController.addTrack(fFormat);
1815                if (track == null) {
1816                    return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
1817                }
1818
1819                // TODO: do the conversion in the subtitle track
1820                Scanner scanner = new Scanner(fIs, "UTF-8");
1821                String contents = scanner.useDelimiter("\\A").next();
1822                synchronized(mOpenSubtitleSources) {
1823                    mOpenSubtitleSources.remove(fIs);
1824                }
1825                scanner.close();
1826                mOutOfBandSubtitleTracks.add(track);
1827                track.onData(contents, true /* eos */, ~0 /* runID: keep forever */);
1828                return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
1829            }
1830
1831            public void run() {
1832                int res = addTrack();
1833                if (mEventHandler != null) {
1834                    Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
1835                    mEventHandler.sendMessage(m);
1836                }
1837                thread.getLooper().quitSafely();
1838            }
1839        });
1840    }
1841
1842    private void scanInternalSubtitleTracks() {
1843        if (mSubtitleController == null) {
1844            Log.e(TAG, "Should have subtitle controller already set");
1845            return;
1846        }
1847
1848        TrackInfo[] tracks = getInbandTrackInfo();
1849        SubtitleTrack[] inbandTracks = new SubtitleTrack[tracks.length];
1850        for (int i=0; i < tracks.length; i++) {
1851            if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
1852                if (i < mInbandSubtitleTracks.length) {
1853                    inbandTracks[i] = mInbandSubtitleTracks[i];
1854                } else {
1855                    SubtitleTrack track = mSubtitleController.addTrack(
1856                            tracks[i].getFormat());
1857                    inbandTracks[i] = track;
1858                }
1859            }
1860        }
1861        mInbandSubtitleTracks = inbandTracks;
1862        mSubtitleController.selectDefaultTrack();
1863    }
1864
1865    /* TODO: Limit the total number of external timed text source to a reasonable number.
1866     */
1867    /**
1868     * Adds an external timed text source file.
1869     *
1870     * Currently supported format is SubRip with the file extension .srt, case insensitive.
1871     * Note that a single external timed text source may contain multiple tracks in it.
1872     * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1873     * additional tracks become available after this method call.
1874     *
1875     * @param path The file path of external timed text source file.
1876     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1877     * @throws IOException if the file cannot be accessed or is corrupted.
1878     * @throws IllegalArgumentException if the mimeType is not supported.
1879     * @throws IllegalStateException if called in an invalid state.
1880     */
1881    public void addTimedTextSource(String path, String mimeType)
1882            throws IOException, IllegalArgumentException, IllegalStateException {
1883        if (!availableMimeTypeForExternalSource(mimeType)) {
1884            final String msg = "Illegal mimeType for timed text source: " + mimeType;
1885            throw new IllegalArgumentException(msg);
1886        }
1887
1888        File file = new File(path);
1889        if (file.exists()) {
1890            FileInputStream is = new FileInputStream(file);
1891            FileDescriptor fd = is.getFD();
1892            addTimedTextSource(fd, mimeType);
1893            is.close();
1894        } else {
1895            // We do not support the case where the path is not a file.
1896            throw new IOException(path);
1897        }
1898    }
1899
1900    /**
1901     * Adds an external timed text source file (Uri).
1902     *
1903     * Currently supported format is SubRip with the file extension .srt, case insensitive.
1904     * Note that a single external timed text source may contain multiple tracks in it.
1905     * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1906     * additional tracks become available after this method call.
1907     *
1908     * @param context the Context to use when resolving the Uri
1909     * @param uri the Content URI of the data you want to play
1910     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1911     * @throws IOException if the file cannot be accessed or is corrupted.
1912     * @throws IllegalArgumentException if the mimeType is not supported.
1913     * @throws IllegalStateException if called in an invalid state.
1914     */
1915    public void addTimedTextSource(Context context, Uri uri, String mimeType)
1916            throws IOException, IllegalArgumentException, IllegalStateException {
1917        String scheme = uri.getScheme();
1918        if(scheme == null || scheme.equals("file")) {
1919            addTimedTextSource(uri.getPath(), mimeType);
1920            return;
1921        }
1922
1923        AssetFileDescriptor fd = null;
1924        try {
1925            ContentResolver resolver = context.getContentResolver();
1926            fd = resolver.openAssetFileDescriptor(uri, "r");
1927            if (fd == null) {
1928                return;
1929            }
1930            addTimedTextSource(fd.getFileDescriptor(), mimeType);
1931            return;
1932        } catch (SecurityException ex) {
1933        } catch (IOException ex) {
1934        } finally {
1935            if (fd != null) {
1936                fd.close();
1937            }
1938        }
1939    }
1940
1941    /**
1942     * Adds an external timed text source file (FileDescriptor).
1943     *
1944     * It is the caller's responsibility to close the file descriptor.
1945     * It is safe to do so as soon as this call returns.
1946     *
1947     * Currently supported format is SubRip. Note that a single external timed text source may
1948     * contain multiple tracks in it. One can find the total number of available tracks
1949     * using {@link #getTrackInfo()} to see what additional tracks become available
1950     * after this method call.
1951     *
1952     * @param fd the FileDescriptor for the file you want to play
1953     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1954     * @throws IllegalArgumentException if the mimeType is not supported.
1955     * @throws IllegalStateException if called in an invalid state.
1956     */
1957    public void addTimedTextSource(FileDescriptor fd, String mimeType)
1958            throws IllegalArgumentException, IllegalStateException {
1959        // intentionally less than LONG_MAX
1960        addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
1961    }
1962
1963    /**
1964     * Adds an external timed text file (FileDescriptor).
1965     *
1966     * It is the caller's responsibility to close the file descriptor.
1967     * It is safe to do so as soon as this call returns.
1968     *
1969     * Currently supported format is SubRip. Note that a single external timed text source may
1970     * contain multiple tracks in it. One can find the total number of available tracks
1971     * using {@link #getTrackInfo()} to see what additional tracks become available
1972     * after this method call.
1973     *
1974     * @param fd the FileDescriptor for the file you want to play
1975     * @param offset the offset into the file where the data to be played starts, in bytes
1976     * @param length the length in bytes of the data to be played
1977     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1978     * @throws IllegalArgumentException if the mimeType is not supported.
1979     * @throws IllegalStateException if called in an invalid state.
1980     */
1981    public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mimeType)
1982            throws IllegalArgumentException, IllegalStateException {
1983        if (!availableMimeTypeForExternalSource(mimeType)) {
1984            throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mimeType);
1985        }
1986
1987        Parcel request = Parcel.obtain();
1988        Parcel reply = Parcel.obtain();
1989        try {
1990            request.writeInterfaceToken(IMEDIA_PLAYER);
1991            request.writeInt(INVOKE_ID_ADD_EXTERNAL_SOURCE_FD);
1992            request.writeFileDescriptor(fd);
1993            request.writeLong(offset);
1994            request.writeLong(length);
1995            request.writeString(mimeType);
1996            invoke(request, reply);
1997        } finally {
1998            request.recycle();
1999            reply.recycle();
2000        }
2001    }
2002
2003    /**
2004     * Selects a track.
2005     * <p>
2006     * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
2007     * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
2008     * If a MediaPlayer is not in Started state, it just marks the track to be played.
2009     * </p>
2010     * <p>
2011     * In any valid state, if it is called multiple times on the same type of track (ie. Video,
2012     * Audio, Timed Text), the most recent one will be chosen.
2013     * </p>
2014     * <p>
2015     * The first audio and video tracks are selected by default if available, even though
2016     * this method is not called. However, no timed text track will be selected until
2017     * this function is called.
2018     * </p>
2019     * <p>
2020     * Currently, only timed text tracks or audio tracks can be selected via this method.
2021     * In addition, the support for selecting an audio track at runtime is pretty limited
2022     * in that an audio track can only be selected in the <em>Prepared</em> state.
2023     * </p>
2024     * @param index the index of the track to be selected. The valid range of the index
2025     * is 0..total number of track - 1. The total number of tracks as well as the type of
2026     * each individual track can be found by calling {@link #getTrackInfo()} method.
2027     * @throws IllegalStateException if called in an invalid state.
2028     *
2029     * @see android.media.MediaPlayer#getTrackInfo
2030     */
2031    public void selectTrack(int index) throws IllegalStateException {
2032        selectOrDeselectTrack(index, true /* select */);
2033    }
2034
2035    /**
2036     * Deselect a track.
2037     * <p>
2038     * Currently, the track must be a timed text track and no audio or video tracks can be
2039     * deselected. If the timed text track identified by index has not been
2040     * selected before, it throws an exception.
2041     * </p>
2042     * @param index the index of the track to be deselected. The valid range of the index
2043     * is 0..total number of tracks - 1. The total number of tracks as well as the type of
2044     * each individual track can be found by calling {@link #getTrackInfo()} method.
2045     * @throws IllegalStateException if called in an invalid state.
2046     *
2047     * @see android.media.MediaPlayer#getTrackInfo
2048     */
2049    public void deselectTrack(int index) throws IllegalStateException {
2050        selectOrDeselectTrack(index, false /* select */);
2051    }
2052
2053    private void selectOrDeselectTrack(int index, boolean select)
2054            throws IllegalStateException {
2055        // handle subtitle track through subtitle controller
2056        SubtitleTrack track = null;
2057        if (index < mInbandSubtitleTracks.length) {
2058            track = mInbandSubtitleTracks[index];
2059        } else if (index < mInbandSubtitleTracks.length + mOutOfBandSubtitleTracks.size()) {
2060            track = mOutOfBandSubtitleTracks.get(index - mInbandSubtitleTracks.length);
2061        }
2062
2063        if (mSubtitleController != null && track != null) {
2064            if (select) {
2065                mSubtitleController.selectTrack(track);
2066            } else if (mSubtitleController.getSelectedTrack() == track) {
2067                mSubtitleController.selectTrack(null);
2068            } else {
2069                Log.w(TAG, "trying to deselect track that was not selected");
2070            }
2071            return;
2072        }
2073
2074        selectOrDeselectInbandTrack(index, select);
2075    }
2076
2077    private void selectOrDeselectInbandTrack(int index, boolean select)
2078            throws IllegalStateException {
2079        Parcel request = Parcel.obtain();
2080        Parcel reply = Parcel.obtain();
2081        try {
2082            request.writeInterfaceToken(IMEDIA_PLAYER);
2083            request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
2084            request.writeInt(index);
2085            invoke(request, reply);
2086        } finally {
2087            request.recycle();
2088            reply.recycle();
2089        }
2090    }
2091
2092
2093    /**
2094     * @param reply Parcel with audio/video duration info for battery
2095                    tracking usage
2096     * @return The status code.
2097     * {@hide}
2098     */
2099    public native static int native_pullBatteryData(Parcel reply);
2100
2101    /**
2102     * Sets the target UDP re-transmit endpoint for the low level player.
2103     * Generally, the address portion of the endpoint is an IP multicast
2104     * address, although a unicast address would be equally valid.  When a valid
2105     * retransmit endpoint has been set, the media player will not decode and
2106     * render the media presentation locally.  Instead, the player will attempt
2107     * to re-multiplex its media data using the Android@Home RTP profile and
2108     * re-transmit to the target endpoint.  Receiver devices (which may be
2109     * either the same as the transmitting device or different devices) may
2110     * instantiate, prepare, and start a receiver player using a setDataSource
2111     * URL of the form...
2112     *
2113     * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
2114     *
2115     * to receive, decode and render the re-transmitted content.
2116     *
2117     * setRetransmitEndpoint may only be called before setDataSource has been
2118     * called; while the player is in the Idle state.
2119     *
2120     * @param endpoint the address and UDP port of the re-transmission target or
2121     * null if no re-transmission is to be performed.
2122     * @throws IllegalStateException if it is called in an invalid state
2123     * @throws IllegalArgumentException if the retransmit endpoint is supplied,
2124     * but invalid.
2125     *
2126     * {@hide} pending API council
2127     */
2128    public void setRetransmitEndpoint(InetSocketAddress endpoint)
2129            throws IllegalStateException, IllegalArgumentException
2130    {
2131        String addrString = null;
2132        int port = 0;
2133
2134        if (null != endpoint) {
2135            addrString = endpoint.getAddress().getHostAddress();
2136            port = endpoint.getPort();
2137        }
2138
2139        int ret = native_setRetransmitEndpoint(addrString, port);
2140        if (ret != 0) {
2141            throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
2142        }
2143    }
2144
2145    private native final int native_setRetransmitEndpoint(String addrString, int port);
2146
2147    @Override
2148    protected void finalize() { native_finalize(); }
2149
2150    /* Do not change these values without updating their counterparts
2151     * in include/media/mediaplayer.h!
2152     */
2153    private static final int MEDIA_NOP = 0; // interface test message
2154    private static final int MEDIA_PREPARED = 1;
2155    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
2156    private static final int MEDIA_BUFFERING_UPDATE = 3;
2157    private static final int MEDIA_SEEK_COMPLETE = 4;
2158    private static final int MEDIA_SET_VIDEO_SIZE = 5;
2159    private static final int MEDIA_STARTED = 6;
2160    private static final int MEDIA_PAUSED = 7;
2161    private static final int MEDIA_STOPPED = 8;
2162    private static final int MEDIA_TIMED_TEXT = 99;
2163    private static final int MEDIA_ERROR = 100;
2164    private static final int MEDIA_INFO = 200;
2165    private static final int MEDIA_SUBTITLE_DATA = 201;
2166
2167    private TimeProvider mTimeProvider;
2168
2169    /** @hide */
2170    public MediaTimeProvider getMediaTimeProvider() {
2171        if (mTimeProvider == null) {
2172            mTimeProvider = new TimeProvider(this);
2173        }
2174        return mTimeProvider;
2175    }
2176
2177    private class EventHandler extends Handler
2178    {
2179        private MediaPlayer mMediaPlayer;
2180
2181        public EventHandler(MediaPlayer mp, Looper looper) {
2182            super(looper);
2183            mMediaPlayer = mp;
2184        }
2185
2186        @Override
2187        public void handleMessage(Message msg) {
2188            if (mMediaPlayer.mNativeContext == 0) {
2189                Log.w(TAG, "mediaplayer went away with unhandled events");
2190                return;
2191            }
2192            switch(msg.what) {
2193            case MEDIA_PREPARED:
2194                scanInternalSubtitleTracks();
2195                if (mOnPreparedListener != null)
2196                    mOnPreparedListener.onPrepared(mMediaPlayer);
2197                return;
2198
2199            case MEDIA_PLAYBACK_COMPLETE:
2200                if (mOnCompletionListener != null)
2201                    mOnCompletionListener.onCompletion(mMediaPlayer);
2202                stayAwake(false);
2203                return;
2204
2205            case MEDIA_STOPPED:
2206                if (mTimeProvider != null) {
2207                    mTimeProvider.onStopped();
2208                }
2209                break;
2210
2211            case MEDIA_STARTED:
2212            case MEDIA_PAUSED:
2213                if (mTimeProvider != null) {
2214                    mTimeProvider.onPaused(msg.what == MEDIA_PAUSED);
2215                }
2216                break;
2217
2218            case MEDIA_BUFFERING_UPDATE:
2219                if (mOnBufferingUpdateListener != null)
2220                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
2221                return;
2222
2223            case MEDIA_SEEK_COMPLETE:
2224              if (mOnSeekCompleteListener != null) {
2225                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
2226              }
2227              if (mTimeProvider != null) {
2228                  mTimeProvider.onSeekComplete(mMediaPlayer);
2229              }
2230              return;
2231
2232            case MEDIA_SET_VIDEO_SIZE:
2233              if (mOnVideoSizeChangedListener != null)
2234                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
2235              return;
2236
2237            case MEDIA_ERROR:
2238                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
2239                boolean error_was_handled = false;
2240                if (mOnErrorListener != null) {
2241                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
2242                }
2243                if (mOnCompletionListener != null && ! error_was_handled) {
2244                    mOnCompletionListener.onCompletion(mMediaPlayer);
2245                }
2246                stayAwake(false);
2247                return;
2248
2249            case MEDIA_INFO:
2250                switch (msg.arg1) {
2251                case MEDIA_INFO_VIDEO_TRACK_LAGGING:
2252                    Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
2253                    break;
2254                case MEDIA_INFO_METADATA_UPDATE:
2255                    scanInternalSubtitleTracks();
2256                    // fall through
2257
2258                case MEDIA_INFO_EXTERNAL_METADATA_UPDATE:
2259                    msg.arg1 = MEDIA_INFO_METADATA_UPDATE;
2260                    // update default track selection
2261                    mSubtitleController.selectDefaultTrack();
2262                    break;
2263                }
2264
2265                if (mOnInfoListener != null) {
2266                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
2267                }
2268                // No real default action so far.
2269                return;
2270            case MEDIA_TIMED_TEXT:
2271                if (mOnTimedTextListener == null)
2272                    return;
2273                if (msg.obj == null) {
2274                    mOnTimedTextListener.onTimedText(mMediaPlayer, null);
2275                } else {
2276                    if (msg.obj instanceof Parcel) {
2277                        Parcel parcel = (Parcel)msg.obj;
2278                        TimedText text = new TimedText(parcel);
2279                        parcel.recycle();
2280                        mOnTimedTextListener.onTimedText(mMediaPlayer, text);
2281                    }
2282                }
2283                return;
2284
2285            case MEDIA_SUBTITLE_DATA:
2286                if (mOnSubtitleDataListener == null) {
2287                    return;
2288                }
2289                if (msg.obj instanceof Parcel) {
2290                    Parcel parcel = (Parcel) msg.obj;
2291                    SubtitleData data = new SubtitleData(parcel);
2292                    parcel.recycle();
2293                    mOnSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
2294                }
2295                return;
2296
2297            case MEDIA_NOP: // interface test message - ignore
2298                break;
2299
2300            default:
2301                Log.e(TAG, "Unknown message type " + msg.what);
2302                return;
2303            }
2304        }
2305    }
2306
2307    /*
2308     * Called from native code when an interesting event happens.  This method
2309     * just uses the EventHandler system to post the event back to the main app thread.
2310     * We use a weak reference to the original MediaPlayer object so that the native
2311     * code is safe from the object disappearing from underneath it.  (This is
2312     * the cookie passed to native_setup().)
2313     */
2314    private static void postEventFromNative(Object mediaplayer_ref,
2315                                            int what, int arg1, int arg2, Object obj)
2316    {
2317        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
2318        if (mp == null) {
2319            return;
2320        }
2321
2322        if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
2323            // this acquires the wakelock if needed, and sets the client side state
2324            mp.start();
2325        }
2326        if (mp.mEventHandler != null) {
2327            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
2328            mp.mEventHandler.sendMessage(m);
2329        }
2330    }
2331
2332    /**
2333     * Interface definition for a callback to be invoked when the media
2334     * source is ready for playback.
2335     */
2336    public interface OnPreparedListener
2337    {
2338        /**
2339         * Called when the media file is ready for playback.
2340         *
2341         * @param mp the MediaPlayer that is ready for playback
2342         */
2343        void onPrepared(MediaPlayer mp);
2344    }
2345
2346    /**
2347     * Register a callback to be invoked when the media source is ready
2348     * for playback.
2349     *
2350     * @param listener the callback that will be run
2351     */
2352    public void setOnPreparedListener(OnPreparedListener listener)
2353    {
2354        mOnPreparedListener = listener;
2355    }
2356
2357    private OnPreparedListener mOnPreparedListener;
2358
2359    /**
2360     * Interface definition for a callback to be invoked when playback of
2361     * a media source has completed.
2362     */
2363    public interface OnCompletionListener
2364    {
2365        /**
2366         * Called when the end of a media source is reached during playback.
2367         *
2368         * @param mp the MediaPlayer that reached the end of the file
2369         */
2370        void onCompletion(MediaPlayer mp);
2371    }
2372
2373    /**
2374     * Register a callback to be invoked when the end of a media source
2375     * has been reached during playback.
2376     *
2377     * @param listener the callback that will be run
2378     */
2379    public void setOnCompletionListener(OnCompletionListener listener)
2380    {
2381        mOnCompletionListener = listener;
2382    }
2383
2384    private OnCompletionListener mOnCompletionListener;
2385
2386    /**
2387     * Interface definition of a callback to be invoked indicating buffering
2388     * status of a media resource being streamed over the network.
2389     */
2390    public interface OnBufferingUpdateListener
2391    {
2392        /**
2393         * Called to update status in buffering a media stream received through
2394         * progressive HTTP download. The received buffering percentage
2395         * indicates how much of the content has been buffered or played.
2396         * For example a buffering update of 80 percent when half the content
2397         * has already been played indicates that the next 30 percent of the
2398         * content to play has been buffered.
2399         *
2400         * @param mp      the MediaPlayer the update pertains to
2401         * @param percent the percentage (0-100) of the content
2402         *                that has been buffered or played thus far
2403         */
2404        void onBufferingUpdate(MediaPlayer mp, int percent);
2405    }
2406
2407    /**
2408     * Register a callback to be invoked when the status of a network
2409     * stream's buffer has changed.
2410     *
2411     * @param listener the callback that will be run.
2412     */
2413    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
2414    {
2415        mOnBufferingUpdateListener = listener;
2416    }
2417
2418    private OnBufferingUpdateListener mOnBufferingUpdateListener;
2419
2420    /**
2421     * Interface definition of a callback to be invoked indicating
2422     * the completion of a seek operation.
2423     */
2424    public interface OnSeekCompleteListener
2425    {
2426        /**
2427         * Called to indicate the completion of a seek operation.
2428         *
2429         * @param mp the MediaPlayer that issued the seek operation
2430         */
2431        public void onSeekComplete(MediaPlayer mp);
2432    }
2433
2434    /**
2435     * Register a callback to be invoked when a seek operation has been
2436     * completed.
2437     *
2438     * @param listener the callback that will be run
2439     */
2440    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
2441    {
2442        mOnSeekCompleteListener = listener;
2443    }
2444
2445    private OnSeekCompleteListener mOnSeekCompleteListener;
2446
2447    /**
2448     * Interface definition of a callback to be invoked when the
2449     * video size is first known or updated
2450     */
2451    public interface OnVideoSizeChangedListener
2452    {
2453        /**
2454         * Called to indicate the video size
2455         *
2456         * The video size (width and height) could be 0 if there was no video,
2457         * no display surface was set, or the value was not determined yet.
2458         *
2459         * @param mp        the MediaPlayer associated with this callback
2460         * @param width     the width of the video
2461         * @param height    the height of the video
2462         */
2463        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
2464    }
2465
2466    /**
2467     * Register a callback to be invoked when the video size is
2468     * known or updated.
2469     *
2470     * @param listener the callback that will be run
2471     */
2472    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
2473    {
2474        mOnVideoSizeChangedListener = listener;
2475    }
2476
2477    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
2478
2479    /**
2480     * Interface definition of a callback to be invoked when a
2481     * timed text is available for display.
2482     */
2483    public interface OnTimedTextListener
2484    {
2485        /**
2486         * Called to indicate an avaliable timed text
2487         *
2488         * @param mp             the MediaPlayer associated with this callback
2489         * @param text           the timed text sample which contains the text
2490         *                       needed to be displayed and the display format.
2491         */
2492        public void onTimedText(MediaPlayer mp, TimedText text);
2493    }
2494
2495    /**
2496     * Register a callback to be invoked when a timed text is available
2497     * for display.
2498     *
2499     * @param listener the callback that will be run
2500     */
2501    public void setOnTimedTextListener(OnTimedTextListener listener)
2502    {
2503        mOnTimedTextListener = listener;
2504    }
2505
2506    private OnTimedTextListener mOnTimedTextListener;
2507
2508    /**
2509     * Interface definition of a callback to be invoked when a
2510     * track has data available.
2511     *
2512     * @hide
2513     */
2514    public interface OnSubtitleDataListener
2515    {
2516        public void onSubtitleData(MediaPlayer mp, SubtitleData data);
2517    }
2518
2519    /**
2520     * Register a callback to be invoked when a track has data available.
2521     *
2522     * @param listener the callback that will be run
2523     *
2524     * @hide
2525     */
2526    public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
2527    {
2528        mOnSubtitleDataListener = listener;
2529    }
2530
2531    private OnSubtitleDataListener mOnSubtitleDataListener;
2532
2533    /* Do not change these values without updating their counterparts
2534     * in include/media/mediaplayer.h!
2535     */
2536    /** Unspecified media player error.
2537     * @see android.media.MediaPlayer.OnErrorListener
2538     */
2539    public static final int MEDIA_ERROR_UNKNOWN = 1;
2540
2541    /** Media server died. In this case, the application must release the
2542     * MediaPlayer object and instantiate a new one.
2543     * @see android.media.MediaPlayer.OnErrorListener
2544     */
2545    public static final int MEDIA_ERROR_SERVER_DIED = 100;
2546
2547    /** The video is streamed and its container is not valid for progressive
2548     * playback i.e the video's index (e.g moov atom) is not at the start of the
2549     * file.
2550     * @see android.media.MediaPlayer.OnErrorListener
2551     */
2552    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
2553
2554    /** File or network related operation errors. */
2555    public static final int MEDIA_ERROR_IO = -1004;
2556    /** Bitstream is not conforming to the related coding standard or file spec. */
2557    public static final int MEDIA_ERROR_MALFORMED = -1007;
2558    /** Bitstream is conforming to the related coding standard or file spec, but
2559     * the media framework does not support the feature. */
2560    public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
2561    /** Some operation takes too long to complete, usually more than 3-5 seconds. */
2562    public static final int MEDIA_ERROR_TIMED_OUT = -110;
2563
2564    /**
2565     * Interface definition of a callback to be invoked when there
2566     * has been an error during an asynchronous operation (other errors
2567     * will throw exceptions at method call time).
2568     */
2569    public interface OnErrorListener
2570    {
2571        /**
2572         * Called to indicate an error.
2573         *
2574         * @param mp      the MediaPlayer the error pertains to
2575         * @param what    the type of error that has occurred:
2576         * <ul>
2577         * <li>{@link #MEDIA_ERROR_UNKNOWN}
2578         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
2579         * </ul>
2580         * @param extra an extra code, specific to the error. Typically
2581         * implementation dependent.
2582         * <ul>
2583         * <li>{@link #MEDIA_ERROR_IO}
2584         * <li>{@link #MEDIA_ERROR_MALFORMED}
2585         * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
2586         * <li>{@link #MEDIA_ERROR_TIMED_OUT}
2587         * </ul>
2588         * @return True if the method handled the error, false if it didn't.
2589         * Returning false, or not having an OnErrorListener at all, will
2590         * cause the OnCompletionListener to be called.
2591         */
2592        boolean onError(MediaPlayer mp, int what, int extra);
2593    }
2594
2595    /**
2596     * Register a callback to be invoked when an error has happened
2597     * during an asynchronous operation.
2598     *
2599     * @param listener the callback that will be run
2600     */
2601    public void setOnErrorListener(OnErrorListener listener)
2602    {
2603        mOnErrorListener = listener;
2604    }
2605
2606    private OnErrorListener mOnErrorListener;
2607
2608
2609    /* Do not change these values without updating their counterparts
2610     * in include/media/mediaplayer.h!
2611     */
2612    /** Unspecified media player info.
2613     * @see android.media.MediaPlayer.OnInfoListener
2614     */
2615    public static final int MEDIA_INFO_UNKNOWN = 1;
2616
2617    /** The player was started because it was used as the next player for another
2618     * player, which just completed playback.
2619     * @see android.media.MediaPlayer.OnInfoListener
2620     * @hide
2621     */
2622    public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
2623
2624    /** The player just pushed the very first video frame for rendering.
2625     * @see android.media.MediaPlayer.OnInfoListener
2626     */
2627    public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
2628
2629    /** The video is too complex for the decoder: it can't decode frames fast
2630     *  enough. Possibly only the audio plays fine at this stage.
2631     * @see android.media.MediaPlayer.OnInfoListener
2632     */
2633    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
2634
2635    /** MediaPlayer is temporarily pausing playback internally in order to
2636     * buffer more data.
2637     * @see android.media.MediaPlayer.OnInfoListener
2638     */
2639    public static final int MEDIA_INFO_BUFFERING_START = 701;
2640
2641    /** MediaPlayer is resuming playback after filling buffers.
2642     * @see android.media.MediaPlayer.OnInfoListener
2643     */
2644    public static final int MEDIA_INFO_BUFFERING_END = 702;
2645
2646    /** Bad interleaving means that a media has been improperly interleaved or
2647     * not interleaved at all, e.g has all the video samples first then all the
2648     * audio ones. Video is playing but a lot of disk seeks may be happening.
2649     * @see android.media.MediaPlayer.OnInfoListener
2650     */
2651    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
2652
2653    /** The media cannot be seeked (e.g live stream)
2654     * @see android.media.MediaPlayer.OnInfoListener
2655     */
2656    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
2657
2658    /** A new set of metadata is available.
2659     * @see android.media.MediaPlayer.OnInfoListener
2660     */
2661    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
2662
2663    /** A new set of external-only metadata is available.  Used by
2664     *  JAVA framework to avoid triggering track scanning.
2665     * @hide
2666     */
2667    public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
2668
2669    /** Failed to handle timed text track properly.
2670     * @see android.media.MediaPlayer.OnInfoListener
2671     *
2672     * {@hide}
2673     */
2674    public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
2675
2676    /** Subtitle track was not supported by the media framework.
2677     * @see android.media.MediaPlayer.OnInfoListener
2678     */
2679    public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
2680
2681    /** Reading the subtitle track takes too long.
2682     * @see android.media.MediaPlayer.OnInfoListener
2683     */
2684    public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
2685
2686    /**
2687     * Interface definition of a callback to be invoked to communicate some
2688     * info and/or warning about the media or its playback.
2689     */
2690    public interface OnInfoListener
2691    {
2692        /**
2693         * Called to indicate an info or a warning.
2694         *
2695         * @param mp      the MediaPlayer the info pertains to.
2696         * @param what    the type of info or warning.
2697         * <ul>
2698         * <li>{@link #MEDIA_INFO_UNKNOWN}
2699         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
2700         * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
2701         * <li>{@link #MEDIA_INFO_BUFFERING_START}
2702         * <li>{@link #MEDIA_INFO_BUFFERING_END}
2703         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
2704         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
2705         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
2706         * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE}
2707         * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT}
2708         * </ul>
2709         * @param extra an extra code, specific to the info. Typically
2710         * implementation dependent.
2711         * @return True if the method handled the info, false if it didn't.
2712         * Returning false, or not having an OnErrorListener at all, will
2713         * cause the info to be discarded.
2714         */
2715        boolean onInfo(MediaPlayer mp, int what, int extra);
2716    }
2717
2718    /**
2719     * Register a callback to be invoked when an info/warning is available.
2720     *
2721     * @param listener the callback that will be run
2722     */
2723    public void setOnInfoListener(OnInfoListener listener)
2724    {
2725        mOnInfoListener = listener;
2726    }
2727
2728    private OnInfoListener mOnInfoListener;
2729
2730    /*
2731     * Test whether a given video scaling mode is supported.
2732     */
2733    private boolean isVideoScalingModeSupported(int mode) {
2734        return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
2735                mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
2736    }
2737
2738    private Context mProxyContext = null;
2739    private ProxyReceiver mProxyReceiver = null;
2740
2741    private void setupProxyListener(Context context) {
2742        IntentFilter filter = new IntentFilter();
2743        filter.addAction(Proxy.PROXY_CHANGE_ACTION);
2744        mProxyReceiver = new ProxyReceiver();
2745        mProxyContext = context;
2746
2747        Intent currentProxy =
2748            context.getApplicationContext().registerReceiver(mProxyReceiver, filter);
2749
2750        if (currentProxy != null) {
2751            handleProxyBroadcast(currentProxy);
2752        }
2753    }
2754
2755    private void disableProxyListener() {
2756        if (mProxyReceiver == null) {
2757            return;
2758        }
2759
2760        Context appContext = mProxyContext.getApplicationContext();
2761        if (appContext != null) {
2762            appContext.unregisterReceiver(mProxyReceiver);
2763        }
2764
2765        mProxyReceiver = null;
2766        mProxyContext = null;
2767    }
2768
2769    private void handleProxyBroadcast(Intent intent) {
2770        ProxyProperties props =
2771            (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO);
2772
2773        if (props == null || props.getHost() == null) {
2774            updateProxyConfig(null);
2775        } else {
2776            updateProxyConfig(props);
2777        }
2778    }
2779
2780    private class ProxyReceiver extends BroadcastReceiver {
2781        @Override
2782        public void onReceive(Context context, Intent intent) {
2783            if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) {
2784                handleProxyBroadcast(intent);
2785            }
2786        }
2787    }
2788
2789    private native void updateProxyConfig(ProxyProperties props);
2790
2791    /** @hide */
2792    static class TimeProvider implements MediaPlayer.OnSeekCompleteListener,
2793            MediaTimeProvider {
2794        private static final String TAG = "MTP";
2795        private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L;
2796        private static final long MAX_EARLY_CALLBACK_US = 1000;
2797        private static final long TIME_ADJUSTMENT_RATE = 2;  /* meaning 1/2 */
2798        private long mLastTimeUs = 0;
2799        private MediaPlayer mPlayer;
2800        private boolean mPaused = true;
2801        private boolean mStopped = true;
2802        private long mLastReportedTime;
2803        private long mTimeAdjustment;
2804        // since we are expecting only a handful listeners per stream, there is
2805        // no need for log(N) search performance
2806        private MediaTimeProvider.OnMediaTimeListener mListeners[];
2807        private long mTimes[];
2808        private long mLastNanoTime;
2809        private Handler mEventHandler;
2810        private boolean mRefresh = false;
2811        private boolean mPausing = false;
2812        private static final int NOTIFY = 1;
2813        private static final int NOTIFY_TIME = 0;
2814        private static final int REFRESH_AND_NOTIFY_TIME = 1;
2815        private static final int NOTIFY_STOP = 2;
2816        private static final int NOTIFY_SEEK = 3;
2817        private HandlerThread mHandlerThread;
2818
2819        /** @hide */
2820        public boolean DEBUG = false;
2821
2822        public TimeProvider(MediaPlayer mp) {
2823            mPlayer = mp;
2824            try {
2825                getCurrentTimeUs(true, false);
2826            } catch (IllegalStateException e) {
2827                // we assume starting position
2828                mRefresh = true;
2829            }
2830
2831            Looper looper;
2832            if ((looper = Looper.myLooper()) == null &&
2833                (looper = Looper.getMainLooper()) == null) {
2834                // Create our own looper here in case MP was created without one
2835                mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread",
2836                      Process.THREAD_PRIORITY_FOREGROUND);
2837                mHandlerThread.start();
2838                looper = mHandlerThread.getLooper();
2839            }
2840            mEventHandler = new EventHandler(looper);
2841
2842            mListeners = new MediaTimeProvider.OnMediaTimeListener[0];
2843            mTimes = new long[0];
2844            mLastTimeUs = 0;
2845            mTimeAdjustment = 0;
2846        }
2847
2848        private void scheduleNotification(int type, long delayUs) {
2849            if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs);
2850            mEventHandler.removeMessages(NOTIFY);
2851            Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0);
2852            mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000));
2853        }
2854
2855        /** @hide */
2856        public void close() {
2857            mEventHandler.removeMessages(NOTIFY);
2858            if (mHandlerThread != null) {
2859                mHandlerThread.quitSafely();
2860                mHandlerThread = null;
2861            }
2862        }
2863
2864        /** @hide */
2865        protected void finalize() {
2866            if (mHandlerThread != null) {
2867                mHandlerThread.quitSafely();
2868            }
2869        }
2870
2871        /** @hide */
2872        public void onPaused(boolean paused) {
2873            synchronized(this) {
2874                if (DEBUG) Log.d(TAG, "onPaused: " + paused);
2875                if (mStopped) { // handle as seek if we were stopped
2876                    mStopped = false;
2877                    scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2878                } else {
2879                    mPausing = paused;  // special handling if player disappeared
2880                    scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
2881                }
2882            }
2883        }
2884
2885        /** @hide */
2886        public void onStopped() {
2887            synchronized(this) {
2888                if (DEBUG) Log.d(TAG, "onStopped");
2889                mPaused = true;
2890                mStopped = true;
2891                scheduleNotification(NOTIFY_STOP, 0 /* delay */);
2892            }
2893        }
2894
2895        /** @hide */
2896        @Override
2897        public void onSeekComplete(MediaPlayer mp) {
2898            synchronized(this) {
2899                mStopped = false;
2900                scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2901            }
2902        }
2903
2904        /** @hide */
2905        public void onNewPlayer() {
2906            if (mRefresh) {
2907                synchronized(this) {
2908                    scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2909                }
2910            }
2911        }
2912
2913        private synchronized void notifySeek() {
2914            try {
2915                long timeUs = getCurrentTimeUs(true, false);
2916                if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs);
2917
2918                for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
2919                    if (listener == null) {
2920                        break;
2921                    }
2922                    listener.onSeek(timeUs);
2923                }
2924            } catch (IllegalStateException e) {
2925                // we should not be there, but at least signal pause
2926                if (DEBUG) Log.d(TAG, "onSeekComplete but no player");
2927                mPausing = true;  // special handling if player disappeared
2928                notifyTimedEvent(false /* refreshTime */);
2929            }
2930        }
2931
2932        private synchronized void notifyStop() {
2933            for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
2934                if (listener == null) {
2935                    break;
2936                }
2937                listener.onStop();
2938            }
2939        }
2940
2941        private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) {
2942            int i = 0;
2943            for (; i < mListeners.length; i++) {
2944                if (mListeners[i] == listener || mListeners[i] == null) {
2945                    break;
2946                }
2947            }
2948
2949            // new listener
2950            if (i >= mListeners.length) {
2951                MediaTimeProvider.OnMediaTimeListener[] newListeners =
2952                    new MediaTimeProvider.OnMediaTimeListener[i + 1];
2953                long[] newTimes = new long[i + 1];
2954                System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length);
2955                System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length);
2956                mListeners = newListeners;
2957                mTimes = newTimes;
2958            }
2959
2960            if (mListeners[i] == null) {
2961                mListeners[i] = listener;
2962                mTimes[i] = MediaTimeProvider.NO_TIME;
2963            }
2964            return i;
2965        }
2966
2967        public void notifyAt(
2968                long timeUs, MediaTimeProvider.OnMediaTimeListener listener) {
2969            synchronized(this) {
2970                if (DEBUG) Log.d(TAG, "notifyAt " + timeUs);
2971                mTimes[registerListener(listener)] = timeUs;
2972                scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2973            }
2974        }
2975
2976        public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) {
2977            synchronized(this) {
2978                if (DEBUG) Log.d(TAG, "scheduleUpdate");
2979                int i = registerListener(listener);
2980
2981                if (mStopped) {
2982                    scheduleNotification(NOTIFY_STOP, 0 /* delay */);
2983                } else {
2984                    mTimes[i] = 0;
2985                    scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2986                }
2987            }
2988        }
2989
2990        public void cancelNotifications(
2991                MediaTimeProvider.OnMediaTimeListener listener) {
2992            synchronized(this) {
2993                int i = 0;
2994                for (; i < mListeners.length; i++) {
2995                    if (mListeners[i] == listener) {
2996                        System.arraycopy(mListeners, i + 1,
2997                                mListeners, i, mListeners.length - i - 1);
2998                        System.arraycopy(mTimes, i + 1,
2999                                mTimes, i, mTimes.length - i - 1);
3000                        mListeners[mListeners.length - 1] = null;
3001                        mTimes[mTimes.length - 1] = NO_TIME;
3002                        break;
3003                    } else if (mListeners[i] == null) {
3004                        break;
3005                    }
3006                }
3007
3008                scheduleNotification(NOTIFY_TIME, 0 /* delay */);
3009            }
3010        }
3011
3012        private synchronized void notifyTimedEvent(boolean refreshTime) {
3013            // figure out next callback
3014            long nowUs;
3015            try {
3016                nowUs = getCurrentTimeUs(refreshTime, true);
3017            } catch (IllegalStateException e) {
3018                // assume we paused until new player arrives
3019                mRefresh = true;
3020                mPausing = true; // this ensures that call succeeds
3021                nowUs = getCurrentTimeUs(refreshTime, true);
3022            }
3023            long nextTimeUs = nowUs;
3024
3025            if (DEBUG) {
3026                StringBuilder sb = new StringBuilder();
3027                sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ")
3028                        .append(nowUs).append(") from {");
3029                boolean first = true;
3030                for (long time: mTimes) {
3031                    if (time == NO_TIME) {
3032                        continue;
3033                    }
3034                    if (!first) sb.append(", ");
3035                    sb.append(time);
3036                    first = false;
3037                }
3038                sb.append("}");
3039                Log.d(TAG, sb.toString());
3040            }
3041
3042            Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners =
3043                new Vector<MediaTimeProvider.OnMediaTimeListener>();
3044            for (int ix = 0; ix < mTimes.length; ix++) {
3045                if (mListeners[ix] == null) {
3046                    break;
3047                }
3048                if (mTimes[ix] <= NO_TIME) {
3049                    // ignore, unless we were stopped
3050                } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) {
3051                    activatedListeners.add(mListeners[ix]);
3052                    if (DEBUG) Log.d(TAG, "removed");
3053                    mTimes[ix] = NO_TIME;
3054                } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) {
3055                    nextTimeUs = mTimes[ix];
3056                }
3057            }
3058
3059            if (nextTimeUs > nowUs && !mPaused) {
3060                // schedule callback at nextTimeUs
3061                if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs);
3062                scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs);
3063            } else {
3064                mEventHandler.removeMessages(NOTIFY);
3065                // no more callbacks
3066            }
3067
3068            for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) {
3069                listener.onTimedEvent(nowUs);
3070            }
3071        }
3072
3073        private long getEstimatedTime(long nanoTime, boolean monotonic) {
3074            if (mPaused) {
3075                mLastReportedTime = mLastTimeUs + mTimeAdjustment;
3076            } else {
3077                long timeSinceRead = (nanoTime - mLastNanoTime) / 1000;
3078                mLastReportedTime = mLastTimeUs + timeSinceRead;
3079                if (mTimeAdjustment > 0) {
3080                    long adjustment =
3081                        mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE;
3082                    if (adjustment <= 0) {
3083                        mTimeAdjustment = 0;
3084                    } else {
3085                        mLastReportedTime += adjustment;
3086                    }
3087                }
3088            }
3089            return mLastReportedTime;
3090        }
3091
3092        public long getCurrentTimeUs(boolean refreshTime, boolean monotonic)
3093                throws IllegalStateException {
3094            synchronized (this) {
3095                // we always refresh the time when the paused-state changes, because
3096                // we expect to have received the pause-change event delayed.
3097                if (mPaused && !refreshTime) {
3098                    return mLastReportedTime;
3099                }
3100
3101                long nanoTime = System.nanoTime();
3102                if (refreshTime ||
3103                        nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) {
3104                    try {
3105                        mLastTimeUs = mPlayer.getCurrentPosition() * 1000;
3106                        mPaused = !mPlayer.isPlaying();
3107                        if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs);
3108                    } catch (IllegalStateException e) {
3109                        if (mPausing) {
3110                            // if we were pausing, get last estimated timestamp
3111                            mPausing = false;
3112                            getEstimatedTime(nanoTime, monotonic);
3113                            mPaused = true;
3114                            if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime);
3115                            return mLastReportedTime;
3116                        }
3117                        // TODO get time when prepared
3118                        throw e;
3119                    }
3120                    mLastNanoTime = nanoTime;
3121                    if (monotonic && mLastTimeUs < mLastReportedTime) {
3122                        /* have to adjust time */
3123                        mTimeAdjustment = mLastReportedTime - mLastTimeUs;
3124                    } else {
3125                        mTimeAdjustment = 0;
3126                    }
3127                }
3128
3129                return getEstimatedTime(nanoTime, monotonic);
3130            }
3131        }
3132
3133        private class EventHandler extends Handler {
3134            public EventHandler(Looper looper) {
3135                super(looper);
3136            }
3137
3138            @Override
3139            public void handleMessage(Message msg) {
3140                if (msg.what == NOTIFY) {
3141                    switch (msg.arg1) {
3142                    case NOTIFY_TIME:
3143                        notifyTimedEvent(false /* refreshTime */);
3144                        break;
3145                    case REFRESH_AND_NOTIFY_TIME:
3146                        notifyTimedEvent(true /* refreshTime */);
3147                        break;
3148                    case NOTIFY_STOP:
3149                        notifyStop();
3150                        break;
3151                    case NOTIFY_SEEK:
3152                        notifySeek();
3153                        break;
3154                    }
3155                }
3156            }
3157        }
3158    }
3159}
3160