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