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