MediaPlayer.java revision a67a4439cacdaa04cb53566b77053694b26d06ad
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        if (mTimeProvider != null) {
1355            mTimeProvider.close();
1356            mTimeProvider = null;
1357        }
1358        mOnSubtitleDataListener = null;
1359        _release();
1360    }
1361
1362    private native void _release();
1363
1364    /**
1365     * Resets the MediaPlayer to its uninitialized state. After calling
1366     * this method, you will have to initialize it again by setting the
1367     * data source and calling prepare().
1368     */
1369    public void reset() {
1370        mSelectedSubtitleTrackIndex = -1;
1371        synchronized(mOpenSubtitleSources) {
1372            for (final InputStream is: mOpenSubtitleSources) {
1373                try {
1374                    is.close();
1375                } catch (IOException e) {
1376                }
1377            }
1378            mOpenSubtitleSources.clear();
1379        }
1380        mOutOfBandSubtitleTracks.clear();
1381        mInbandSubtitleTracks = new SubtitleTrack[0];
1382        if (mSubtitleController != null) {
1383            mSubtitleController.reset();
1384        }
1385        if (mTimeProvider != null) {
1386            mTimeProvider.close();
1387            mTimeProvider = null;
1388        }
1389
1390        stayAwake(false);
1391        _reset();
1392        // make sure none of the listeners get called anymore
1393        if (mEventHandler != null) {
1394            mEventHandler.removeCallbacksAndMessages(null);
1395        }
1396
1397        disableProxyListener();
1398    }
1399
1400    private native void _reset();
1401
1402    /**
1403     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
1404     * for a list of stream types. Must call this method before prepare() or
1405     * prepareAsync() in order for the target stream type to become effective
1406     * thereafter.
1407     *
1408     * @param streamtype the audio stream type
1409     * @see android.media.AudioManager
1410     */
1411    public native void setAudioStreamType(int streamtype);
1412
1413    /**
1414     * Sets the player to be looping or non-looping.
1415     *
1416     * @param looping whether to loop or not
1417     */
1418    public native void setLooping(boolean looping);
1419
1420    /**
1421     * Checks whether the MediaPlayer is looping or non-looping.
1422     *
1423     * @return true if the MediaPlayer is currently looping, false otherwise
1424     */
1425    public native boolean isLooping();
1426
1427    /**
1428     * Sets the volume on this player.
1429     * This API is recommended for balancing the output of audio streams
1430     * within an application. Unless you are writing an application to
1431     * control user settings, this API should be used in preference to
1432     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
1433     * a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
1434     * UI controls should be scaled logarithmically.
1435     *
1436     * @param leftVolume left volume scalar
1437     * @param rightVolume right volume scalar
1438     */
1439    /*
1440     * FIXME: Merge this into javadoc comment above when setVolume(float) is not @hide.
1441     * The single parameter form below is preferred if the channel volumes don't need
1442     * to be set independently.
1443     */
1444    public native void setVolume(float leftVolume, float rightVolume);
1445
1446    /**
1447     * Similar, excepts sets volume of all channels to same value.
1448     * @hide
1449     */
1450    public void setVolume(float volume) {
1451        setVolume(volume, volume);
1452    }
1453
1454    /**
1455     * Sets the audio session ID.
1456     *
1457     * @param sessionId the audio session ID.
1458     * The audio session ID is a system wide unique identifier for the audio stream played by
1459     * this MediaPlayer instance.
1460     * The primary use of the audio session ID  is to associate audio effects to a particular
1461     * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
1462     * this effect will be applied only to the audio content of media players within the same
1463     * audio session and not to the output mix.
1464     * When created, a MediaPlayer instance automatically generates its own audio session ID.
1465     * However, it is possible to force this player to be part of an already existing audio session
1466     * by calling this method.
1467     * This method must be called before one of the overloaded <code> setDataSource </code> methods.
1468     * @throws IllegalStateException if it is called in an invalid state
1469     */
1470    public native void setAudioSessionId(int sessionId)  throws IllegalArgumentException, IllegalStateException;
1471
1472    /**
1473     * Returns the audio session ID.
1474     *
1475     * @return the audio session ID. {@see #setAudioSessionId(int)}
1476     * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
1477     */
1478    public native int getAudioSessionId();
1479
1480    /**
1481     * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1482     * effect which can be applied on any sound source that directs a certain amount of its
1483     * energy to this effect. This amount is defined by setAuxEffectSendLevel().
1484     * {@see #setAuxEffectSendLevel(float)}.
1485     * <p>After creating an auxiliary effect (e.g.
1486     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1487     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1488     * to attach the player to the effect.
1489     * <p>To detach the effect from the player, call this method with a null effect id.
1490     * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1491     * methods.
1492     * @param effectId system wide unique id of the effect to attach
1493     */
1494    public native void attachAuxEffect(int effectId);
1495
1496
1497    /**
1498     * Sets the send level of the player to the attached auxiliary effect
1499     * {@see #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1500     * <p>By default the send level is 0, so even if an effect is attached to the player
1501     * this method must be called for the effect to be applied.
1502     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1503     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1504     * so an appropriate conversion from linear UI input x to level is:
1505     * x == 0 -> level = 0
1506     * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1507     * @param level send level scalar
1508     */
1509    public native void setAuxEffectSendLevel(float level);
1510
1511    /*
1512     * @param request Parcel destinated to the media player. The
1513     *                Interface token must be set to the IMediaPlayer
1514     *                one to be routed correctly through the system.
1515     * @param reply[out] Parcel that will contain the reply.
1516     * @return The status code.
1517     */
1518    private native final int native_invoke(Parcel request, Parcel reply);
1519
1520
1521    /*
1522     * @param update_only If true fetch only the set of metadata that have
1523     *                    changed since the last invocation of getMetadata.
1524     *                    The set is built using the unfiltered
1525     *                    notifications the native player sent to the
1526     *                    MediaPlayerService during that period of
1527     *                    time. If false, all the metadatas are considered.
1528     * @param apply_filter  If true, once the metadata set has been built based on
1529     *                     the value update_only, the current filter is applied.
1530     * @param reply[out] On return contains the serialized
1531     *                   metadata. Valid only if the call was successful.
1532     * @return The status code.
1533     */
1534    private native final boolean native_getMetadata(boolean update_only,
1535                                                    boolean apply_filter,
1536                                                    Parcel reply);
1537
1538    /*
1539     * @param request Parcel with the 2 serialized lists of allowed
1540     *                metadata types followed by the one to be
1541     *                dropped. Each list starts with an integer
1542     *                indicating the number of metadata type elements.
1543     * @return The status code.
1544     */
1545    private native final int native_setMetadataFilter(Parcel request);
1546
1547    private static native final void native_init();
1548    private native final void native_setup(Object mediaplayer_this);
1549    private native final void native_finalize();
1550
1551    /**
1552     * Class for MediaPlayer to return each audio/video/subtitle track's metadata.
1553     *
1554     * @see android.media.MediaPlayer#getTrackInfo
1555     */
1556    static public class TrackInfo implements Parcelable {
1557        /**
1558         * Gets the track type.
1559         * @return TrackType which indicates if the track is video, audio, timed text.
1560         */
1561        public int getTrackType() {
1562            return mTrackType;
1563        }
1564
1565        /**
1566         * Gets the language code of the track.
1567         * @return a language code in either way of ISO-639-1 or ISO-639-2.
1568         * When the language is unknown or could not be determined,
1569         * ISO-639-2 language code, "und", is returned.
1570         */
1571        public String getLanguage() {
1572            String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
1573            return language == null ? "und" : language;
1574        }
1575
1576        /**
1577         * Gets the {@link MediaFormat} of the track.  If the format is
1578         * unknown or could not be determined, null is returned.
1579         */
1580        public MediaFormat getFormat() {
1581            if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1582                return mFormat;
1583            }
1584            return null;
1585        }
1586
1587        public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
1588        public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
1589        public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
1590        public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
1591        /** @hide */
1592        public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
1593
1594        final int mTrackType;
1595        final MediaFormat mFormat;
1596
1597        TrackInfo(Parcel in) {
1598            mTrackType = in.readInt();
1599            // TODO: parcel in the full MediaFormat
1600            String language = in.readString();
1601
1602            if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT) {
1603                mFormat = MediaFormat.createSubtitleFormat(
1604                    MEDIA_MIMETYPE_TEXT_SUBRIP, language);
1605            } else {
1606                mFormat = new MediaFormat();
1607                mFormat.setString(MediaFormat.KEY_LANGUAGE, language);
1608            }
1609        }
1610
1611        /** @hide */
1612        TrackInfo(int type, MediaFormat format) {
1613            mTrackType = type;
1614            mFormat = format;
1615        }
1616
1617        /**
1618         * {@inheritDoc}
1619         */
1620        @Override
1621        public int describeContents() {
1622            return 0;
1623        }
1624
1625        /**
1626         * {@inheritDoc}
1627         */
1628        @Override
1629        public void writeToParcel(Parcel dest, int flags) {
1630            dest.writeInt(mTrackType);
1631            dest.writeString(getLanguage());
1632        }
1633
1634        /**
1635         * Used to read a TrackInfo from a Parcel.
1636         */
1637        static final Parcelable.Creator<TrackInfo> CREATOR
1638                = new Parcelable.Creator<TrackInfo>() {
1639                    @Override
1640                    public TrackInfo createFromParcel(Parcel in) {
1641                        return new TrackInfo(in);
1642                    }
1643
1644                    @Override
1645                    public TrackInfo[] newArray(int size) {
1646                        return new TrackInfo[size];
1647                    }
1648                };
1649
1650    };
1651
1652    /**
1653     * Returns an array of track information.
1654     *
1655     * @return Array of track info. The total number of tracks is the array length.
1656     * Must be called again if an external timed text source has been added after any of the
1657     * addTimedTextSource methods are called.
1658     * @throws IllegalStateException if it is called in an invalid state.
1659     */
1660    public TrackInfo[] getTrackInfo() throws IllegalStateException {
1661        TrackInfo trackInfo[] = getInbandTrackInfo();
1662        // add out-of-band tracks
1663        TrackInfo allTrackInfo[] = new TrackInfo[trackInfo.length + mOutOfBandSubtitleTracks.size()];
1664        System.arraycopy(trackInfo, 0, allTrackInfo, 0, trackInfo.length);
1665        int i = trackInfo.length;
1666        for (SubtitleTrack track: mOutOfBandSubtitleTracks) {
1667            allTrackInfo[i] = new TrackInfo(TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE, track.getFormat());
1668            ++i;
1669        }
1670        return allTrackInfo;
1671    }
1672
1673    private TrackInfo[] getInbandTrackInfo() throws IllegalStateException {
1674        Parcel request = Parcel.obtain();
1675        Parcel reply = Parcel.obtain();
1676        try {
1677            request.writeInterfaceToken(IMEDIA_PLAYER);
1678            request.writeInt(INVOKE_ID_GET_TRACK_INFO);
1679            invoke(request, reply);
1680            TrackInfo trackInfo[] = reply.createTypedArray(TrackInfo.CREATOR);
1681            return trackInfo;
1682        } finally {
1683            request.recycle();
1684            reply.recycle();
1685        }
1686    }
1687
1688    /* Do not change these values without updating their counterparts
1689     * in include/media/stagefright/MediaDefs.h and media/libstagefright/MediaDefs.cpp!
1690     */
1691    /**
1692     * MIME type for SubRip (SRT) container. Used in addTimedTextSource APIs.
1693     */
1694    public static final String MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
1695
1696    /*
1697     * A helper function to check if the mime type is supported by media framework.
1698     */
1699    private static boolean availableMimeTypeForExternalSource(String mimeType) {
1700        if (mimeType == MEDIA_MIMETYPE_TEXT_SUBRIP) {
1701            return true;
1702        }
1703        return false;
1704    }
1705
1706    private SubtitleController mSubtitleController;
1707
1708    /** @hide */
1709    public void setSubtitleAnchor(
1710            SubtitleController controller,
1711            SubtitleController.Anchor anchor) {
1712        // TODO: create SubtitleController in MediaPlayer
1713        mSubtitleController = controller;
1714        mSubtitleController.setAnchor(anchor);
1715    }
1716
1717    private SubtitleTrack[] mInbandSubtitleTracks;
1718    private int mSelectedSubtitleTrackIndex = -1;
1719    private Vector<SubtitleTrack> mOutOfBandSubtitleTracks;
1720    private Vector<InputStream> mOpenSubtitleSources;
1721
1722    private OnSubtitleDataListener mSubtitleDataListener = new OnSubtitleDataListener() {
1723        @Override
1724        public void onSubtitleData(MediaPlayer mp, SubtitleData data) {
1725            int index = data.getTrackIndex();
1726            if (index >= mInbandSubtitleTracks.length) {
1727                return;
1728            }
1729            SubtitleTrack track = mInbandSubtitleTracks[index];
1730            if (track != null) {
1731                try {
1732                    long runID = data.getStartTimeUs() + 1;
1733                    // TODO: move conversion into track
1734                    track.onData(new String(data.getData(), "UTF-8"), true /* eos */, runID);
1735                    track.setRunDiscardTimeMs(
1736                            runID,
1737                            (data.getStartTimeUs() + data.getDurationUs()) / 1000);
1738                } catch (java.io.UnsupportedEncodingException e) {
1739                    Log.w(TAG, "subtitle data for track " + index + " is not UTF-8 encoded: " + e);
1740                }
1741            }
1742        }
1743    };
1744
1745    /** @hide */
1746    @Override
1747    public void onSubtitleTrackSelected(SubtitleTrack track) {
1748        if (mSelectedSubtitleTrackIndex >= 0) {
1749            deselectTrack(mSelectedSubtitleTrackIndex);
1750        }
1751        mSelectedSubtitleTrackIndex = -1;
1752        setOnSubtitleDataListener(null);
1753        for (int i = 0; i < mInbandSubtitleTracks.length; i++) {
1754            if (mInbandSubtitleTracks[i] == track) {
1755                Log.v(TAG, "Selecting subtitle track " + i);
1756                selectTrack(i);
1757                mSelectedSubtitleTrackIndex = i;
1758                setOnSubtitleDataListener(mSubtitleDataListener);
1759                break;
1760            }
1761        }
1762        // no need to select out-of-band tracks
1763    }
1764
1765    /** @hide */
1766    public void addSubtitleSource(InputStream is, MediaFormat format)
1767            throws IllegalStateException
1768    {
1769        final InputStream fIs = is;
1770        final MediaFormat fFormat = format;
1771
1772        // Ensure all input streams are closed.  It is also a handy
1773        // way to implement timeouts in the future.
1774        synchronized(mOpenSubtitleSources) {
1775            mOpenSubtitleSources.add(is);
1776        }
1777
1778        // process each subtitle in its own thread
1779        final HandlerThread thread = new HandlerThread("SubtitleReadThread",
1780              Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
1781        thread.start();
1782        Handler handler = new Handler(thread.getLooper());
1783        handler.post(new Runnable() {
1784            private int addTrack() {
1785                if (fIs == null || mSubtitleController == null) {
1786                    return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
1787                }
1788
1789                SubtitleTrack track = mSubtitleController.addTrack(fFormat);
1790                if (track == null) {
1791                    return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
1792                }
1793
1794                // TODO: do the conversion in the subtitle track
1795                Scanner scanner = new Scanner(fIs, "UTF-8");
1796                String contents = scanner.useDelimiter("\\A").next();
1797                synchronized(mOpenSubtitleSources) {
1798                    mOpenSubtitleSources.remove(fIs);
1799                }
1800                scanner.close();
1801                mOutOfBandSubtitleTracks.add(track);
1802                track.onData(contents, true /* eos */, ~0 /* runID: keep forever */);
1803                // update default track selection
1804                mSubtitleController.selectDefaultTrack();
1805                return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
1806            }
1807
1808            public void run() {
1809                int res = addTrack();
1810                if (mEventHandler != null) {
1811                    Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
1812                    mEventHandler.sendMessage(m);
1813                }
1814                thread.getLooper().quitSafely();
1815            }
1816        });
1817    }
1818
1819    private void scanInternalSubtitleTracks() {
1820        if (mSubtitleController == null) {
1821            Log.e(TAG, "Should have subtitle controller already set");
1822            return;
1823        }
1824
1825        TrackInfo[] tracks = getInbandTrackInfo();
1826        SubtitleTrack[] inbandTracks = new SubtitleTrack[tracks.length];
1827        for (int i=0; i < tracks.length; i++) {
1828            if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
1829                if (i < mInbandSubtitleTracks.length) {
1830                    inbandTracks[i] = mInbandSubtitleTracks[i];
1831                } else {
1832                    MediaFormat format = MediaFormat.createSubtitleFormat(
1833                            "text/vtt", tracks[i].getLanguage());
1834                    SubtitleTrack track = mSubtitleController.addTrack(format);
1835                    inbandTracks[i] = track;
1836                }
1837            }
1838        }
1839        mInbandSubtitleTracks = inbandTracks;
1840        mSubtitleController.selectDefaultTrack();
1841    }
1842
1843    /* TODO: Limit the total number of external timed text source to a reasonable number.
1844     */
1845    /**
1846     * Adds an external timed text source file.
1847     *
1848     * Currently supported format is SubRip with the file extension .srt, case insensitive.
1849     * Note that a single external timed text source may contain multiple tracks in it.
1850     * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1851     * additional tracks become available after this method call.
1852     *
1853     * @param path The file path of external timed text source file.
1854     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1855     * @throws IOException if the file cannot be accessed or is corrupted.
1856     * @throws IllegalArgumentException if the mimeType is not supported.
1857     * @throws IllegalStateException if called in an invalid state.
1858     */
1859    public void addTimedTextSource(String path, String mimeType)
1860            throws IOException, IllegalArgumentException, IllegalStateException {
1861        if (!availableMimeTypeForExternalSource(mimeType)) {
1862            final String msg = "Illegal mimeType for timed text source: " + mimeType;
1863            throw new IllegalArgumentException(msg);
1864        }
1865
1866        File file = new File(path);
1867        if (file.exists()) {
1868            FileInputStream is = new FileInputStream(file);
1869            FileDescriptor fd = is.getFD();
1870            addTimedTextSource(fd, mimeType);
1871            is.close();
1872        } else {
1873            // We do not support the case where the path is not a file.
1874            throw new IOException(path);
1875        }
1876    }
1877
1878    /**
1879     * Adds an external timed text source file (Uri).
1880     *
1881     * Currently supported format is SubRip with the file extension .srt, case insensitive.
1882     * Note that a single external timed text source may contain multiple tracks in it.
1883     * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
1884     * additional tracks become available after this method call.
1885     *
1886     * @param context the Context to use when resolving the Uri
1887     * @param uri the Content URI of the data you want to play
1888     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1889     * @throws IOException if the file cannot be accessed or is corrupted.
1890     * @throws IllegalArgumentException if the mimeType is not supported.
1891     * @throws IllegalStateException if called in an invalid state.
1892     */
1893    public void addTimedTextSource(Context context, Uri uri, String mimeType)
1894            throws IOException, IllegalArgumentException, IllegalStateException {
1895        String scheme = uri.getScheme();
1896        if(scheme == null || scheme.equals("file")) {
1897            addTimedTextSource(uri.getPath(), mimeType);
1898            return;
1899        }
1900
1901        AssetFileDescriptor fd = null;
1902        try {
1903            ContentResolver resolver = context.getContentResolver();
1904            fd = resolver.openAssetFileDescriptor(uri, "r");
1905            if (fd == null) {
1906                return;
1907            }
1908            addTimedTextSource(fd.getFileDescriptor(), mimeType);
1909            return;
1910        } catch (SecurityException ex) {
1911        } catch (IOException ex) {
1912        } finally {
1913            if (fd != null) {
1914                fd.close();
1915            }
1916        }
1917    }
1918
1919    /**
1920     * Adds an external timed text source file (FileDescriptor).
1921     *
1922     * It is the caller's responsibility to close the file descriptor.
1923     * It is safe to do so as soon as this call returns.
1924     *
1925     * Currently supported format is SubRip. Note that a single external timed text source may
1926     * contain multiple tracks in it. One can find the total number of available tracks
1927     * using {@link #getTrackInfo()} to see what additional tracks become available
1928     * after this method call.
1929     *
1930     * @param fd the FileDescriptor for the file you want to play
1931     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1932     * @throws IllegalArgumentException if the mimeType is not supported.
1933     * @throws IllegalStateException if called in an invalid state.
1934     */
1935    public void addTimedTextSource(FileDescriptor fd, String mimeType)
1936            throws IllegalArgumentException, IllegalStateException {
1937        // intentionally less than LONG_MAX
1938        addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
1939    }
1940
1941    /**
1942     * Adds an external timed text file (FileDescriptor).
1943     *
1944     * It is the caller's responsibility to close the file descriptor.
1945     * It is safe to do so as soon as this call returns.
1946     *
1947     * Currently supported format is SubRip. Note that a single external timed text source may
1948     * contain multiple tracks in it. One can find the total number of available tracks
1949     * using {@link #getTrackInfo()} to see what additional tracks become available
1950     * after this method call.
1951     *
1952     * @param fd the FileDescriptor for the file you want to play
1953     * @param offset the offset into the file where the data to be played starts, in bytes
1954     * @param length the length in bytes of the data to be played
1955     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
1956     * @throws IllegalArgumentException if the mimeType is not supported.
1957     * @throws IllegalStateException if called in an invalid state.
1958     */
1959    public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mimeType)
1960            throws IllegalArgumentException, IllegalStateException {
1961        if (!availableMimeTypeForExternalSource(mimeType)) {
1962            throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mimeType);
1963        }
1964
1965        Parcel request = Parcel.obtain();
1966        Parcel reply = Parcel.obtain();
1967        try {
1968            request.writeInterfaceToken(IMEDIA_PLAYER);
1969            request.writeInt(INVOKE_ID_ADD_EXTERNAL_SOURCE_FD);
1970            request.writeFileDescriptor(fd);
1971            request.writeLong(offset);
1972            request.writeLong(length);
1973            request.writeString(mimeType);
1974            invoke(request, reply);
1975        } finally {
1976            request.recycle();
1977            reply.recycle();
1978        }
1979    }
1980
1981    /**
1982     * Selects a track.
1983     * <p>
1984     * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
1985     * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
1986     * If a MediaPlayer is not in Started state, it just marks the track to be played.
1987     * </p>
1988     * <p>
1989     * In any valid state, if it is called multiple times on the same type of track (ie. Video,
1990     * Audio, Timed Text), the most recent one will be chosen.
1991     * </p>
1992     * <p>
1993     * The first audio and video tracks are selected by default if available, even though
1994     * this method is not called. However, no timed text track will be selected until
1995     * this function is called.
1996     * </p>
1997     * <p>
1998     * Currently, only timed text tracks or audio tracks can be selected via this method.
1999     * In addition, the support for selecting an audio track at runtime is pretty limited
2000     * in that an audio track can only be selected in the <em>Prepared</em> state.
2001     * </p>
2002     * @param index the index of the track to be selected. The valid range of the index
2003     * is 0..total number of track - 1. The total number of tracks as well as the type of
2004     * each individual track can be found by calling {@link #getTrackInfo()} method.
2005     * @throws IllegalStateException if called in an invalid state.
2006     *
2007     * @see android.media.MediaPlayer#getTrackInfo
2008     */
2009    public void selectTrack(int index) throws IllegalStateException {
2010        selectOrDeselectTrack(index, true /* select */);
2011    }
2012
2013    /**
2014     * Deselect a track.
2015     * <p>
2016     * Currently, the track must be a timed text track and no audio or video tracks can be
2017     * deselected. If the timed text track identified by index has not been
2018     * selected before, it throws an exception.
2019     * </p>
2020     * @param index the index of the track to be deselected. The valid range of the index
2021     * is 0..total number of tracks - 1. The total number of tracks as well as the type of
2022     * each individual track can be found by calling {@link #getTrackInfo()} method.
2023     * @throws IllegalStateException if called in an invalid state.
2024     *
2025     * @see android.media.MediaPlayer#getTrackInfo
2026     */
2027    public void deselectTrack(int index) throws IllegalStateException {
2028        selectOrDeselectTrack(index, false /* select */);
2029    }
2030
2031    private void selectOrDeselectTrack(int index, boolean select)
2032            throws IllegalStateException {
2033        // ignore out-of-band tracks
2034        TrackInfo[] trackInfo = getInbandTrackInfo();
2035        if (index >= trackInfo.length &&
2036                index < trackInfo.length + mOutOfBandSubtitleTracks.size()) {
2037            return;
2038        }
2039
2040        Parcel request = Parcel.obtain();
2041        Parcel reply = Parcel.obtain();
2042        try {
2043            request.writeInterfaceToken(IMEDIA_PLAYER);
2044            request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
2045            request.writeInt(index);
2046            invoke(request, reply);
2047        } finally {
2048            request.recycle();
2049            reply.recycle();
2050        }
2051    }
2052
2053
2054    /**
2055     * @param reply Parcel with audio/video duration info for battery
2056                    tracking usage
2057     * @return The status code.
2058     * {@hide}
2059     */
2060    public native static int native_pullBatteryData(Parcel reply);
2061
2062    /**
2063     * Sets the target UDP re-transmit endpoint for the low level player.
2064     * Generally, the address portion of the endpoint is an IP multicast
2065     * address, although a unicast address would be equally valid.  When a valid
2066     * retransmit endpoint has been set, the media player will not decode and
2067     * render the media presentation locally.  Instead, the player will attempt
2068     * to re-multiplex its media data using the Android@Home RTP profile and
2069     * re-transmit to the target endpoint.  Receiver devices (which may be
2070     * either the same as the transmitting device or different devices) may
2071     * instantiate, prepare, and start a receiver player using a setDataSource
2072     * URL of the form...
2073     *
2074     * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
2075     *
2076     * to receive, decode and render the re-transmitted content.
2077     *
2078     * setRetransmitEndpoint may only be called before setDataSource has been
2079     * called; while the player is in the Idle state.
2080     *
2081     * @param endpoint the address and UDP port of the re-transmission target or
2082     * null if no re-transmission is to be performed.
2083     * @throws IllegalStateException if it is called in an invalid state
2084     * @throws IllegalArgumentException if the retransmit endpoint is supplied,
2085     * but invalid.
2086     *
2087     * {@hide} pending API council
2088     */
2089    public void setRetransmitEndpoint(InetSocketAddress endpoint)
2090            throws IllegalStateException, IllegalArgumentException
2091    {
2092        String addrString = null;
2093        int port = 0;
2094
2095        if (null != endpoint) {
2096            addrString = endpoint.getAddress().getHostAddress();
2097            port = endpoint.getPort();
2098        }
2099
2100        int ret = native_setRetransmitEndpoint(addrString, port);
2101        if (ret != 0) {
2102            throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
2103        }
2104    }
2105
2106    private native final int native_setRetransmitEndpoint(String addrString, int port);
2107
2108    @Override
2109    protected void finalize() { native_finalize(); }
2110
2111    /* Do not change these values without updating their counterparts
2112     * in include/media/mediaplayer.h!
2113     */
2114    private static final int MEDIA_NOP = 0; // interface test message
2115    private static final int MEDIA_PREPARED = 1;
2116    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
2117    private static final int MEDIA_BUFFERING_UPDATE = 3;
2118    private static final int MEDIA_SEEK_COMPLETE = 4;
2119    private static final int MEDIA_SET_VIDEO_SIZE = 5;
2120    private static final int MEDIA_STARTED = 6;
2121    private static final int MEDIA_PAUSED = 7;
2122    private static final int MEDIA_STOPPED = 8;
2123    private static final int MEDIA_TIMED_TEXT = 99;
2124    private static final int MEDIA_ERROR = 100;
2125    private static final int MEDIA_INFO = 200;
2126    private static final int MEDIA_SUBTITLE_DATA = 201;
2127
2128    private TimeProvider mTimeProvider;
2129
2130    /** @hide */
2131    public MediaTimeProvider getMediaTimeProvider() {
2132        if (mTimeProvider == null) {
2133            mTimeProvider = new TimeProvider(this);
2134        }
2135        return mTimeProvider;
2136    }
2137
2138    private class EventHandler extends Handler
2139    {
2140        private MediaPlayer mMediaPlayer;
2141
2142        public EventHandler(MediaPlayer mp, Looper looper) {
2143            super(looper);
2144            mMediaPlayer = mp;
2145        }
2146
2147        @Override
2148        public void handleMessage(Message msg) {
2149            if (mMediaPlayer.mNativeContext == 0) {
2150                Log.w(TAG, "mediaplayer went away with unhandled events");
2151                return;
2152            }
2153            switch(msg.what) {
2154            case MEDIA_PREPARED:
2155                scanInternalSubtitleTracks();
2156                if (mOnPreparedListener != null)
2157                    mOnPreparedListener.onPrepared(mMediaPlayer);
2158                return;
2159
2160            case MEDIA_PLAYBACK_COMPLETE:
2161                if (mOnCompletionListener != null)
2162                    mOnCompletionListener.onCompletion(mMediaPlayer);
2163                stayAwake(false);
2164                return;
2165
2166            case MEDIA_STOPPED:
2167                if (mTimeProvider != null) {
2168                    mTimeProvider.onStopped();
2169                }
2170                break;
2171
2172            case MEDIA_STARTED:
2173            case MEDIA_PAUSED:
2174                if (mTimeProvider != null) {
2175                    mTimeProvider.onPaused(msg.what == MEDIA_PAUSED);
2176                }
2177                break;
2178
2179            case MEDIA_BUFFERING_UPDATE:
2180                if (mOnBufferingUpdateListener != null)
2181                    mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
2182                return;
2183
2184            case MEDIA_SEEK_COMPLETE:
2185              if (mOnSeekCompleteListener != null) {
2186                  mOnSeekCompleteListener.onSeekComplete(mMediaPlayer);
2187              }
2188              if (mTimeProvider != null) {
2189                  mTimeProvider.onSeekComplete(mMediaPlayer);
2190              }
2191              return;
2192
2193            case MEDIA_SET_VIDEO_SIZE:
2194              if (mOnVideoSizeChangedListener != null)
2195                  mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2);
2196              return;
2197
2198            case MEDIA_ERROR:
2199                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
2200                boolean error_was_handled = false;
2201                if (mOnErrorListener != null) {
2202                    error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
2203                }
2204                if (mOnCompletionListener != null && ! error_was_handled) {
2205                    mOnCompletionListener.onCompletion(mMediaPlayer);
2206                }
2207                stayAwake(false);
2208                return;
2209
2210            case MEDIA_INFO:
2211                switch (msg.arg1) {
2212                case MEDIA_INFO_VIDEO_TRACK_LAGGING:
2213                    Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
2214                    break;
2215                case MEDIA_INFO_METADATA_UPDATE:
2216                    scanInternalSubtitleTracks();
2217                    break;
2218                case MEDIA_INFO_EXTERNAL_METADATA_UPDATE:
2219                    msg.arg1 = MEDIA_INFO_METADATA_UPDATE;
2220                    break;
2221                }
2222
2223                if (mOnInfoListener != null) {
2224                    mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
2225                }
2226                // No real default action so far.
2227                return;
2228            case MEDIA_TIMED_TEXT:
2229                if (mOnTimedTextListener == null)
2230                    return;
2231                if (msg.obj == null) {
2232                    mOnTimedTextListener.onTimedText(mMediaPlayer, null);
2233                } else {
2234                    if (msg.obj instanceof Parcel) {
2235                        Parcel parcel = (Parcel)msg.obj;
2236                        TimedText text = new TimedText(parcel);
2237                        parcel.recycle();
2238                        mOnTimedTextListener.onTimedText(mMediaPlayer, text);
2239                    }
2240                }
2241                return;
2242
2243            case MEDIA_SUBTITLE_DATA:
2244                if (mOnSubtitleDataListener == null) {
2245                    return;
2246                }
2247                if (msg.obj instanceof Parcel) {
2248                    Parcel parcel = (Parcel) msg.obj;
2249                    SubtitleData data = new SubtitleData(parcel);
2250                    parcel.recycle();
2251                    mOnSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
2252                }
2253                return;
2254
2255            case MEDIA_NOP: // interface test message - ignore
2256                break;
2257
2258            default:
2259                Log.e(TAG, "Unknown message type " + msg.what);
2260                return;
2261            }
2262        }
2263    }
2264
2265    /*
2266     * Called from native code when an interesting event happens.  This method
2267     * just uses the EventHandler system to post the event back to the main app thread.
2268     * We use a weak reference to the original MediaPlayer object so that the native
2269     * code is safe from the object disappearing from underneath it.  (This is
2270     * the cookie passed to native_setup().)
2271     */
2272    private static void postEventFromNative(Object mediaplayer_ref,
2273                                            int what, int arg1, int arg2, Object obj)
2274    {
2275        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
2276        if (mp == null) {
2277            return;
2278        }
2279
2280        if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
2281            // this acquires the wakelock if needed, and sets the client side state
2282            mp.start();
2283        }
2284        if (mp.mEventHandler != null) {
2285            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
2286            mp.mEventHandler.sendMessage(m);
2287        }
2288    }
2289
2290    /**
2291     * Interface definition for a callback to be invoked when the media
2292     * source is ready for playback.
2293     */
2294    public interface OnPreparedListener
2295    {
2296        /**
2297         * Called when the media file is ready for playback.
2298         *
2299         * @param mp the MediaPlayer that is ready for playback
2300         */
2301        void onPrepared(MediaPlayer mp);
2302    }
2303
2304    /**
2305     * Register a callback to be invoked when the media source is ready
2306     * for playback.
2307     *
2308     * @param listener the callback that will be run
2309     */
2310    public void setOnPreparedListener(OnPreparedListener listener)
2311    {
2312        mOnPreparedListener = listener;
2313    }
2314
2315    private OnPreparedListener mOnPreparedListener;
2316
2317    /**
2318     * Interface definition for a callback to be invoked when playback of
2319     * a media source has completed.
2320     */
2321    public interface OnCompletionListener
2322    {
2323        /**
2324         * Called when the end of a media source is reached during playback.
2325         *
2326         * @param mp the MediaPlayer that reached the end of the file
2327         */
2328        void onCompletion(MediaPlayer mp);
2329    }
2330
2331    /**
2332     * Register a callback to be invoked when the end of a media source
2333     * has been reached during playback.
2334     *
2335     * @param listener the callback that will be run
2336     */
2337    public void setOnCompletionListener(OnCompletionListener listener)
2338    {
2339        mOnCompletionListener = listener;
2340    }
2341
2342    private OnCompletionListener mOnCompletionListener;
2343
2344    /**
2345     * Interface definition of a callback to be invoked indicating buffering
2346     * status of a media resource being streamed over the network.
2347     */
2348    public interface OnBufferingUpdateListener
2349    {
2350        /**
2351         * Called to update status in buffering a media stream received through
2352         * progressive HTTP download. The received buffering percentage
2353         * indicates how much of the content has been buffered or played.
2354         * For example a buffering update of 80 percent when half the content
2355         * has already been played indicates that the next 30 percent of the
2356         * content to play has been buffered.
2357         *
2358         * @param mp      the MediaPlayer the update pertains to
2359         * @param percent the percentage (0-100) of the content
2360         *                that has been buffered or played thus far
2361         */
2362        void onBufferingUpdate(MediaPlayer mp, int percent);
2363    }
2364
2365    /**
2366     * Register a callback to be invoked when the status of a network
2367     * stream's buffer has changed.
2368     *
2369     * @param listener the callback that will be run.
2370     */
2371    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
2372    {
2373        mOnBufferingUpdateListener = listener;
2374    }
2375
2376    private OnBufferingUpdateListener mOnBufferingUpdateListener;
2377
2378    /**
2379     * Interface definition of a callback to be invoked indicating
2380     * the completion of a seek operation.
2381     */
2382    public interface OnSeekCompleteListener
2383    {
2384        /**
2385         * Called to indicate the completion of a seek operation.
2386         *
2387         * @param mp the MediaPlayer that issued the seek operation
2388         */
2389        public void onSeekComplete(MediaPlayer mp);
2390    }
2391
2392    /**
2393     * Register a callback to be invoked when a seek operation has been
2394     * completed.
2395     *
2396     * @param listener the callback that will be run
2397     */
2398    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
2399    {
2400        mOnSeekCompleteListener = listener;
2401    }
2402
2403    private OnSeekCompleteListener mOnSeekCompleteListener;
2404
2405    /**
2406     * Interface definition of a callback to be invoked when the
2407     * video size is first known or updated
2408     */
2409    public interface OnVideoSizeChangedListener
2410    {
2411        /**
2412         * Called to indicate the video size
2413         *
2414         * The video size (width and height) could be 0 if there was no video,
2415         * no display surface was set, or the value was not determined yet.
2416         *
2417         * @param mp        the MediaPlayer associated with this callback
2418         * @param width     the width of the video
2419         * @param height    the height of the video
2420         */
2421        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
2422    }
2423
2424    /**
2425     * Register a callback to be invoked when the video size is
2426     * known or updated.
2427     *
2428     * @param listener the callback that will be run
2429     */
2430    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
2431    {
2432        mOnVideoSizeChangedListener = listener;
2433    }
2434
2435    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
2436
2437    /**
2438     * Interface definition of a callback to be invoked when a
2439     * timed text is available for display.
2440     */
2441    public interface OnTimedTextListener
2442    {
2443        /**
2444         * Called to indicate an avaliable timed text
2445         *
2446         * @param mp             the MediaPlayer associated with this callback
2447         * @param text           the timed text sample which contains the text
2448         *                       needed to be displayed and the display format.
2449         */
2450        public void onTimedText(MediaPlayer mp, TimedText text);
2451    }
2452
2453    /**
2454     * Register a callback to be invoked when a timed text is available
2455     * for display.
2456     *
2457     * @param listener the callback that will be run
2458     */
2459    public void setOnTimedTextListener(OnTimedTextListener listener)
2460    {
2461        mOnTimedTextListener = listener;
2462    }
2463
2464    private OnTimedTextListener mOnTimedTextListener;
2465
2466    /**
2467     * Interface definition of a callback to be invoked when a
2468     * track has data available.
2469     *
2470     * @hide
2471     */
2472    public interface OnSubtitleDataListener
2473    {
2474        public void onSubtitleData(MediaPlayer mp, SubtitleData data);
2475    }
2476
2477    /**
2478     * Register a callback to be invoked when a track has data available.
2479     *
2480     * @param listener the callback that will be run
2481     *
2482     * @hide
2483     */
2484    public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
2485    {
2486        mOnSubtitleDataListener = listener;
2487    }
2488
2489    private OnSubtitleDataListener mOnSubtitleDataListener;
2490
2491    /* Do not change these values without updating their counterparts
2492     * in include/media/mediaplayer.h!
2493     */
2494    /** Unspecified media player error.
2495     * @see android.media.MediaPlayer.OnErrorListener
2496     */
2497    public static final int MEDIA_ERROR_UNKNOWN = 1;
2498
2499    /** Media server died. In this case, the application must release the
2500     * MediaPlayer object and instantiate a new one.
2501     * @see android.media.MediaPlayer.OnErrorListener
2502     */
2503    public static final int MEDIA_ERROR_SERVER_DIED = 100;
2504
2505    /** The video is streamed and its container is not valid for progressive
2506     * playback i.e the video's index (e.g moov atom) is not at the start of the
2507     * file.
2508     * @see android.media.MediaPlayer.OnErrorListener
2509     */
2510    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
2511
2512    /** File or network related operation errors. */
2513    public static final int MEDIA_ERROR_IO = -1004;
2514    /** Bitstream is not conforming to the related coding standard or file spec. */
2515    public static final int MEDIA_ERROR_MALFORMED = -1007;
2516    /** Bitstream is conforming to the related coding standard or file spec, but
2517     * the media framework does not support the feature. */
2518    public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
2519    /** Some operation takes too long to complete, usually more than 3-5 seconds. */
2520    public static final int MEDIA_ERROR_TIMED_OUT = -110;
2521
2522    /**
2523     * Interface definition of a callback to be invoked when there
2524     * has been an error during an asynchronous operation (other errors
2525     * will throw exceptions at method call time).
2526     */
2527    public interface OnErrorListener
2528    {
2529        /**
2530         * Called to indicate an error.
2531         *
2532         * @param mp      the MediaPlayer the error pertains to
2533         * @param what    the type of error that has occurred:
2534         * <ul>
2535         * <li>{@link #MEDIA_ERROR_UNKNOWN}
2536         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
2537         * </ul>
2538         * @param extra an extra code, specific to the error. Typically
2539         * implementation dependent.
2540         * <ul>
2541         * <li>{@link #MEDIA_ERROR_IO}
2542         * <li>{@link #MEDIA_ERROR_MALFORMED}
2543         * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
2544         * <li>{@link #MEDIA_ERROR_TIMED_OUT}
2545         * </ul>
2546         * @return True if the method handled the error, false if it didn't.
2547         * Returning false, or not having an OnErrorListener at all, will
2548         * cause the OnCompletionListener to be called.
2549         */
2550        boolean onError(MediaPlayer mp, int what, int extra);
2551    }
2552
2553    /**
2554     * Register a callback to be invoked when an error has happened
2555     * during an asynchronous operation.
2556     *
2557     * @param listener the callback that will be run
2558     */
2559    public void setOnErrorListener(OnErrorListener listener)
2560    {
2561        mOnErrorListener = listener;
2562    }
2563
2564    private OnErrorListener mOnErrorListener;
2565
2566
2567    /* Do not change these values without updating their counterparts
2568     * in include/media/mediaplayer.h!
2569     */
2570    /** Unspecified media player info.
2571     * @see android.media.MediaPlayer.OnInfoListener
2572     */
2573    public static final int MEDIA_INFO_UNKNOWN = 1;
2574
2575    /** The player was started because it was used as the next player for another
2576     * player, which just completed playback.
2577     * @see android.media.MediaPlayer.OnInfoListener
2578     * @hide
2579     */
2580    public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
2581
2582    /** The player just pushed the very first video frame for rendering.
2583     * @see android.media.MediaPlayer.OnInfoListener
2584     */
2585    public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
2586
2587    /** The video is too complex for the decoder: it can't decode frames fast
2588     *  enough. Possibly only the audio plays fine at this stage.
2589     * @see android.media.MediaPlayer.OnInfoListener
2590     */
2591    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
2592
2593    /** MediaPlayer is temporarily pausing playback internally in order to
2594     * buffer more data.
2595     * @see android.media.MediaPlayer.OnInfoListener
2596     */
2597    public static final int MEDIA_INFO_BUFFERING_START = 701;
2598
2599    /** MediaPlayer is resuming playback after filling buffers.
2600     * @see android.media.MediaPlayer.OnInfoListener
2601     */
2602    public static final int MEDIA_INFO_BUFFERING_END = 702;
2603
2604    /** Bad interleaving means that a media has been improperly interleaved or
2605     * not interleaved at all, e.g has all the video samples first then all the
2606     * audio ones. Video is playing but a lot of disk seeks may be happening.
2607     * @see android.media.MediaPlayer.OnInfoListener
2608     */
2609    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
2610
2611    /** The media cannot be seeked (e.g live stream)
2612     * @see android.media.MediaPlayer.OnInfoListener
2613     */
2614    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
2615
2616    /** A new set of metadata is available.
2617     * @see android.media.MediaPlayer.OnInfoListener
2618     */
2619    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
2620
2621    /** A new set of external-only metadata is available.  Used by
2622     *  JAVA framework to avoid triggering track scanning.
2623     * @hide
2624     */
2625    public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
2626
2627    /** Failed to handle timed text track properly.
2628     * @see android.media.MediaPlayer.OnInfoListener
2629     *
2630     * {@hide}
2631     */
2632    public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
2633
2634    /** Subtitle track was not supported by the media framework.
2635     * @see android.media.MediaPlayer.OnInfoListener
2636     */
2637    public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
2638
2639    /** Reading the subtitle track takes too long.
2640     * @see android.media.MediaPlayer.OnInfoListener
2641     */
2642    public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
2643
2644    /**
2645     * Interface definition of a callback to be invoked to communicate some
2646     * info and/or warning about the media or its playback.
2647     */
2648    public interface OnInfoListener
2649    {
2650        /**
2651         * Called to indicate an info or a warning.
2652         *
2653         * @param mp      the MediaPlayer the info pertains to.
2654         * @param what    the type of info or warning.
2655         * <ul>
2656         * <li>{@link #MEDIA_INFO_UNKNOWN}
2657         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
2658         * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
2659         * <li>{@link #MEDIA_INFO_BUFFERING_START}
2660         * <li>{@link #MEDIA_INFO_BUFFERING_END}
2661         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
2662         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
2663         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
2664         * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE}
2665         * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT}
2666         * </ul>
2667         * @param extra an extra code, specific to the info. Typically
2668         * implementation dependent.
2669         * @return True if the method handled the info, false if it didn't.
2670         * Returning false, or not having an OnErrorListener at all, will
2671         * cause the info to be discarded.
2672         */
2673        boolean onInfo(MediaPlayer mp, int what, int extra);
2674    }
2675
2676    /**
2677     * Register a callback to be invoked when an info/warning is available.
2678     *
2679     * @param listener the callback that will be run
2680     */
2681    public void setOnInfoListener(OnInfoListener listener)
2682    {
2683        mOnInfoListener = listener;
2684    }
2685
2686    private OnInfoListener mOnInfoListener;
2687
2688    /*
2689     * Test whether a given video scaling mode is supported.
2690     */
2691    private boolean isVideoScalingModeSupported(int mode) {
2692        return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
2693                mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
2694    }
2695
2696    private Context mProxyContext = null;
2697    private ProxyReceiver mProxyReceiver = null;
2698
2699    private void setupProxyListener(Context context) {
2700        IntentFilter filter = new IntentFilter();
2701        filter.addAction(Proxy.PROXY_CHANGE_ACTION);
2702        mProxyReceiver = new ProxyReceiver();
2703        mProxyContext = context;
2704
2705        Intent currentProxy =
2706            context.getApplicationContext().registerReceiver(mProxyReceiver, filter);
2707
2708        if (currentProxy != null) {
2709            handleProxyBroadcast(currentProxy);
2710        }
2711    }
2712
2713    private void disableProxyListener() {
2714        if (mProxyReceiver == null) {
2715            return;
2716        }
2717
2718        Context appContext = mProxyContext.getApplicationContext();
2719        if (appContext != null) {
2720            appContext.unregisterReceiver(mProxyReceiver);
2721        }
2722
2723        mProxyReceiver = null;
2724        mProxyContext = null;
2725    }
2726
2727    private void handleProxyBroadcast(Intent intent) {
2728        ProxyProperties props =
2729            (ProxyProperties)intent.getExtra(Proxy.EXTRA_PROXY_INFO);
2730
2731        if (props == null || props.getHost() == null) {
2732            updateProxyConfig(null);
2733        } else {
2734            updateProxyConfig(props);
2735        }
2736    }
2737
2738    private class ProxyReceiver extends BroadcastReceiver {
2739        @Override
2740        public void onReceive(Context context, Intent intent) {
2741            if (intent.getAction().equals(Proxy.PROXY_CHANGE_ACTION)) {
2742                handleProxyBroadcast(intent);
2743            }
2744        }
2745    }
2746
2747    private native void updateProxyConfig(ProxyProperties props);
2748
2749    /** @hide */
2750    static class TimeProvider implements MediaPlayer.OnSeekCompleteListener,
2751            MediaTimeProvider {
2752        private static final String TAG = "MTP";
2753        private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L;
2754        private static final long MAX_EARLY_CALLBACK_US = 1000;
2755        private static final long TIME_ADJUSTMENT_RATE = 2;  /* meaning 1/2 */
2756        private long mLastTimeUs = 0;
2757        private MediaPlayer mPlayer;
2758        private boolean mPaused = true;
2759        private boolean mStopped = true;
2760        private long mLastReportedTime;
2761        private long mTimeAdjustment;
2762        // since we are expecting only a handful listeners per stream, there is
2763        // no need for log(N) search performance
2764        private MediaTimeProvider.OnMediaTimeListener mListeners[];
2765        private long mTimes[];
2766        private long mLastNanoTime;
2767        private Handler mEventHandler;
2768        private boolean mRefresh = false;
2769        private boolean mPausing = false;
2770        private static final int NOTIFY = 1;
2771        private static final int NOTIFY_TIME = 0;
2772        private static final int REFRESH_AND_NOTIFY_TIME = 1;
2773        private static final int NOTIFY_STOP = 2;
2774        private static final int NOTIFY_SEEK = 3;
2775        private HandlerThread mHandlerThread;
2776
2777        /** @hide */
2778        public boolean DEBUG = false;
2779
2780        public TimeProvider(MediaPlayer mp) {
2781            mPlayer = mp;
2782            try {
2783                getCurrentTimeUs(true, false);
2784            } catch (IllegalStateException e) {
2785                // we assume starting position
2786                mRefresh = true;
2787            }
2788
2789            Looper looper;
2790            if ((looper = Looper.myLooper()) == null &&
2791                (looper = Looper.getMainLooper()) == null) {
2792                // Create our own looper here in case MP was created without one
2793                mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread",
2794                      Process.THREAD_PRIORITY_FOREGROUND);
2795                mHandlerThread.start();
2796                looper = mHandlerThread.getLooper();
2797            }
2798            mEventHandler = new EventHandler(looper);
2799
2800            mListeners = new MediaTimeProvider.OnMediaTimeListener[0];
2801            mTimes = new long[0];
2802            mLastTimeUs = 0;
2803            mTimeAdjustment = 0;
2804        }
2805
2806        private void scheduleNotification(int type, long delayUs) {
2807            if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs);
2808            mEventHandler.removeMessages(NOTIFY);
2809            Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0);
2810            mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000));
2811        }
2812
2813        /** @hide */
2814        public void close() {
2815            mEventHandler.removeMessages(NOTIFY);
2816            if (mHandlerThread != null) {
2817                mHandlerThread.quitSafely();
2818                mHandlerThread = null;
2819            }
2820        }
2821
2822        /** @hide */
2823        protected void finalize() {
2824            if (mHandlerThread != null) {
2825                mHandlerThread.quitSafely();
2826            }
2827        }
2828
2829        /** @hide */
2830        public void onPaused(boolean paused) {
2831            synchronized(this) {
2832                if (DEBUG) Log.d(TAG, "onPaused: " + paused);
2833                if (mStopped) { // handle as seek if we were stopped
2834                    mStopped = false;
2835                    scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2836                } else {
2837                    mPausing = paused;  // special handling if player disappeared
2838                    scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
2839                }
2840            }
2841        }
2842
2843        /** @hide */
2844        public void onStopped() {
2845            synchronized(this) {
2846                if (DEBUG) Log.d(TAG, "onStopped");
2847                mPaused = true;
2848                mStopped = true;
2849                scheduleNotification(NOTIFY_STOP, 0 /* delay */);
2850            }
2851        }
2852
2853        /** @hide */
2854        @Override
2855        public void onSeekComplete(MediaPlayer mp) {
2856            synchronized(this) {
2857                mStopped = false;
2858                scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2859            }
2860        }
2861
2862        /** @hide */
2863        public void onNewPlayer() {
2864            if (mRefresh) {
2865                synchronized(this) {
2866                    scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
2867                }
2868            }
2869        }
2870
2871        private synchronized void notifySeek() {
2872            try {
2873                long timeUs = getCurrentTimeUs(true, false);
2874                if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs);
2875
2876                for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
2877                    if (listener == null) {
2878                        break;
2879                    }
2880                    listener.onSeek(timeUs);
2881                }
2882            } catch (IllegalStateException e) {
2883                // we should not be there, but at least signal pause
2884                if (DEBUG) Log.d(TAG, "onSeekComplete but no player");
2885                mPausing = true;  // special handling if player disappeared
2886                notifyTimedEvent(false /* refreshTime */);
2887            }
2888        }
2889
2890        private synchronized void notifyStop() {
2891            for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
2892                if (listener == null) {
2893                    break;
2894                }
2895                listener.onStop();
2896            }
2897        }
2898
2899        private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) {
2900            int i = 0;
2901            for (; i < mListeners.length; i++) {
2902                if (mListeners[i] == listener || mListeners[i] == null) {
2903                    break;
2904                }
2905            }
2906
2907            // new listener
2908            if (i >= mListeners.length) {
2909                MediaTimeProvider.OnMediaTimeListener[] newListeners =
2910                    new MediaTimeProvider.OnMediaTimeListener[i + 1];
2911                long[] newTimes = new long[i + 1];
2912                System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length);
2913                System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length);
2914                mListeners = newListeners;
2915                mTimes = newTimes;
2916            }
2917
2918            if (mListeners[i] == null) {
2919                mListeners[i] = listener;
2920                mTimes[i] = MediaTimeProvider.NO_TIME;
2921            }
2922            return i;
2923        }
2924
2925        public void notifyAt(
2926                long timeUs, MediaTimeProvider.OnMediaTimeListener listener) {
2927            synchronized(this) {
2928                if (DEBUG) Log.d(TAG, "notifyAt " + timeUs);
2929                mTimes[registerListener(listener)] = timeUs;
2930                scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2931            }
2932        }
2933
2934        public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) {
2935            synchronized(this) {
2936                if (DEBUG) Log.d(TAG, "scheduleUpdate");
2937                int i = registerListener(listener);
2938
2939                if (mStopped) {
2940                    scheduleNotification(NOTIFY_STOP, 0 /* delay */);
2941                } else {
2942                    mTimes[i] = 0;
2943                    scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2944                }
2945            }
2946        }
2947
2948        public void cancelNotifications(
2949                MediaTimeProvider.OnMediaTimeListener listener) {
2950            synchronized(this) {
2951                int i = 0;
2952                for (; i < mListeners.length; i++) {
2953                    if (mListeners[i] == listener) {
2954                        System.arraycopy(mListeners, i + 1,
2955                                mListeners, i, mListeners.length - i - 1);
2956                        System.arraycopy(mTimes, i + 1,
2957                                mTimes, i, mTimes.length - i - 1);
2958                        mListeners[mListeners.length - 1] = null;
2959                        mTimes[mTimes.length - 1] = NO_TIME;
2960                        break;
2961                    } else if (mListeners[i] == null) {
2962                        break;
2963                    }
2964                }
2965
2966                scheduleNotification(NOTIFY_TIME, 0 /* delay */);
2967            }
2968        }
2969
2970        private synchronized void notifyTimedEvent(boolean refreshTime) {
2971            // figure out next callback
2972            long nowUs;
2973            try {
2974                nowUs = getCurrentTimeUs(refreshTime, true);
2975            } catch (IllegalStateException e) {
2976                // assume we paused until new player arrives
2977                mRefresh = true;
2978                mPausing = true; // this ensures that call succeeds
2979                nowUs = getCurrentTimeUs(refreshTime, true);
2980            }
2981            long nextTimeUs = nowUs;
2982
2983            if (DEBUG) {
2984                StringBuilder sb = new StringBuilder();
2985                sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ")
2986                        .append(nowUs).append(") from {");
2987                boolean first = true;
2988                for (long time: mTimes) {
2989                    if (time == NO_TIME) {
2990                        continue;
2991                    }
2992                    if (!first) sb.append(", ");
2993                    sb.append(time);
2994                    first = false;
2995                }
2996                sb.append("}");
2997                Log.d(TAG, sb.toString());
2998            }
2999
3000            Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners =
3001                new Vector<MediaTimeProvider.OnMediaTimeListener>();
3002            for (int ix = 0; ix < mTimes.length; ix++) {
3003                if (mListeners[ix] == null) {
3004                    break;
3005                }
3006                if (mTimes[ix] <= NO_TIME) {
3007                    // ignore, unless we were stopped
3008                } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) {
3009                    activatedListeners.add(mListeners[ix]);
3010                    if (DEBUG) Log.d(TAG, "removed");
3011                    mTimes[ix] = NO_TIME;
3012                } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) {
3013                    nextTimeUs = mTimes[ix];
3014                }
3015            }
3016
3017            if (nextTimeUs > nowUs && !mPaused) {
3018                // schedule callback at nextTimeUs
3019                if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs);
3020                scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs);
3021            } else {
3022                mEventHandler.removeMessages(NOTIFY);
3023                // no more callbacks
3024            }
3025
3026            for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) {
3027                listener.onTimedEvent(nowUs);
3028            }
3029        }
3030
3031        private long getEstimatedTime(long nanoTime, boolean monotonic) {
3032            if (mPaused) {
3033                mLastReportedTime = mLastTimeUs + mTimeAdjustment;
3034            } else {
3035                long timeSinceRead = (nanoTime - mLastNanoTime) / 1000;
3036                mLastReportedTime = mLastTimeUs + timeSinceRead;
3037                if (mTimeAdjustment > 0) {
3038                    long adjustment =
3039                        mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE;
3040                    if (adjustment <= 0) {
3041                        mTimeAdjustment = 0;
3042                    } else {
3043                        mLastReportedTime += adjustment;
3044                    }
3045                }
3046            }
3047            return mLastReportedTime;
3048        }
3049
3050        public long getCurrentTimeUs(boolean refreshTime, boolean monotonic)
3051                throws IllegalStateException {
3052            synchronized (this) {
3053                // we always refresh the time when the paused-state changes, because
3054                // we expect to have received the pause-change event delayed.
3055                if (mPaused && !refreshTime) {
3056                    return mLastReportedTime;
3057                }
3058
3059                long nanoTime = System.nanoTime();
3060                if (refreshTime ||
3061                        nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) {
3062                    try {
3063                        mLastTimeUs = mPlayer.getCurrentPosition() * 1000;
3064                        mPaused = !mPlayer.isPlaying();
3065                        if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs);
3066                    } catch (IllegalStateException e) {
3067                        if (mPausing) {
3068                            // if we were pausing, get last estimated timestamp
3069                            mPausing = false;
3070                            getEstimatedTime(nanoTime, monotonic);
3071                            mPaused = true;
3072                            if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime);
3073                            return mLastReportedTime;
3074                        }
3075                        // TODO get time when prepared
3076                        throw e;
3077                    }
3078                    mLastNanoTime = nanoTime;
3079                    if (monotonic && mLastTimeUs < mLastReportedTime) {
3080                        /* have to adjust time */
3081                        mTimeAdjustment = mLastReportedTime - mLastTimeUs;
3082                    } else {
3083                        mTimeAdjustment = 0;
3084                    }
3085                }
3086
3087                return getEstimatedTime(nanoTime, monotonic);
3088            }
3089        }
3090
3091        private class EventHandler extends Handler {
3092            public EventHandler(Looper looper) {
3093                super(looper);
3094            }
3095
3096            @Override
3097            public void handleMessage(Message msg) {
3098                if (msg.what == NOTIFY) {
3099                    switch (msg.arg1) {
3100                    case NOTIFY_TIME:
3101                        notifyTimedEvent(false /* refreshTime */);
3102                        break;
3103                    case REFRESH_AND_NOTIFY_TIME:
3104                        notifyTimedEvent(true /* refreshTime */);
3105                        break;
3106                    case NOTIFY_STOP:
3107                        notifyStop();
3108                        break;
3109                    case NOTIFY_SEEK:
3110                        notifySeek();
3111                        break;
3112                    }
3113                }
3114            }
3115        }
3116    }
3117}
3118