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