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