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