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