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