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