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