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