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