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