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