MediaPlayer.java revision 0b52e95c3fe5e8de93276678d7db9a17b217622e
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.annotation.IntDef;
20import android.annotation.NonNull;
21import android.annotation.Nullable;
22import android.app.ActivityThread;
23import android.content.ContentProvider;
24import android.content.ContentResolver;
25import android.content.Context;
26import android.content.res.AssetFileDescriptor;
27import android.net.Uri;
28import android.os.Bundle;
29import android.os.Handler;
30import android.os.HandlerThread;
31import android.os.IBinder;
32import android.os.Looper;
33import android.os.Message;
34import android.os.Parcel;
35import android.os.Parcelable;
36import android.os.Process;
37import android.os.PowerManager;
38import android.os.SystemProperties;
39import android.provider.Settings;
40import android.system.ErrnoException;
41import android.system.OsConstants;
42import android.util.Log;
43import android.util.Pair;
44import android.view.Surface;
45import android.view.SurfaceHolder;
46import android.widget.VideoView;
47import android.graphics.SurfaceTexture;
48import android.media.AudioManager;
49import android.media.BufferingParams;
50import android.media.MediaDrm;
51import android.media.MediaFormat;
52import android.media.MediaTimeProvider;
53import android.media.PlaybackParams;
54import android.media.SubtitleController;
55import android.media.SubtitleController.Anchor;
56import android.media.SubtitleData;
57import android.media.SubtitleTrack.RenderingWidget;
58import android.media.SyncParams;
59
60import com.android.internal.util.Preconditions;
61
62import libcore.io.IoBridge;
63import libcore.io.Libcore;
64import libcore.io.Streams;
65
66import java.io.ByteArrayOutputStream;
67import java.io.File;
68import java.io.FileDescriptor;
69import java.io.FileInputStream;
70import java.io.IOException;
71import java.io.InputStream;
72import java.lang.Runnable;
73import java.lang.annotation.Retention;
74import java.lang.annotation.RetentionPolicy;
75import java.lang.ref.WeakReference;
76import java.net.HttpURLConnection;
77import java.net.InetSocketAddress;
78import java.net.URL;
79import java.nio.ByteOrder;
80import java.util.Arrays;
81import java.util.BitSet;
82import java.util.HashMap;
83import java.util.Map;
84import java.util.Scanner;
85import java.util.Set;
86import java.util.UUID;
87import java.util.Vector;
88
89
90/**
91 * MediaPlayer class can be used to control playback
92 * of audio/video files and streams. An example on how to use the methods in
93 * this class can be found in {@link android.widget.VideoView}.
94 *
95 * <p>Topics covered here are:
96 * <ol>
97 * <li><a href="#StateDiagram">State Diagram</a>
98 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
99 * <li><a href="#Permissions">Permissions</a>
100 * <li><a href="#Callbacks">Register informational and error callbacks</a>
101 * </ol>
102 *
103 * <div class="special reference">
104 * <h3>Developer Guides</h3>
105 * <p>For more information about how to use MediaPlayer, read the
106 * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p>
107 * </div>
108 *
109 * <a name="StateDiagram"></a>
110 * <h3>State Diagram</h3>
111 *
112 * <p>Playback control of audio/video files and streams is managed as a state
113 * machine. The following diagram shows the life cycle and the states of a
114 * MediaPlayer object driven by the supported playback control operations.
115 * The ovals represent the states a MediaPlayer object may reside
116 * in. The arcs represent the playback control operations that drive the object
117 * state transition. There are two types of arcs. The arcs with a single arrow
118 * head represent synchronous method calls, while those with
119 * a double arrow head represent asynchronous method calls.</p>
120 *
121 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
122 *         alt="MediaPlayer State diagram"
123 *         border="0" /></p>
124 *
125 * <p>From this state diagram, one can see that a MediaPlayer object has the
126 *    following states:</p>
127 * <ul>
128 *     <li>When a MediaPlayer object is just created using <code>new</code> or
129 *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
130 *         {@link #release()} is called, it is in the <em>End</em> state. Between these
131 *         two states is the life cycle of the MediaPlayer object.
132 *         <ul>
133 *         <li>There is a subtle but important difference between a newly constructed
134 *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
135 *         is called. It is a programming error to invoke methods such
136 *         as {@link #getCurrentPosition()},
137 *         {@link #getDuration()}, {@link #getVideoHeight()},
138 *         {@link #getVideoWidth()}, {@link #setAudioAttributes(AudioAttributes)},
139 *         {@link #setLooping(boolean)},
140 *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
141 *         {@link #stop()}, {@link #seekTo(int, int)}, {@link #prepare()} or
142 *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
143 *         methods is called right after a MediaPlayer object is constructed,
144 *         the user supplied callback method OnErrorListener.onError() won't be
145 *         called by the internal player engine and the object state remains
146 *         unchanged; but if these methods are called right after {@link #reset()},
147 *         the user supplied callback method OnErrorListener.onError() will be
148 *         invoked by the internal player engine and the object will be
149 *         transfered to the <em>Error</em> state. </li>
150 *         <li>It is also recommended that once
151 *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
152 *         so that resources used by the internal player engine associated with the
153 *         MediaPlayer object can be released immediately. Resource may include
154 *         singleton resources such as hardware acceleration components and
155 *         failure to call {@link #release()} may cause subsequent instances of
156 *         MediaPlayer objects to fallback to software implementations or fail
157 *         altogether. Once the MediaPlayer
158 *         object is in the <em>End</em> state, it can no longer be used and
159 *         there is no way to bring it back to any other state. </li>
160 *         <li>Furthermore,
161 *         the MediaPlayer objects created using <code>new</code> is in the
162 *         <em>Idle</em> state, while those created with one
163 *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
164 *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
165 *         state if the creation using <code>create</code> method is successful.
166 *         </li>
167 *         </ul>
168 *         </li>
169 *     <li>In general, some playback control operation may fail due to various
170 *         reasons, such as unsupported audio/video format, poorly interleaved
171 *         audio/video, resolution too high, streaming timeout, and the like.
172 *         Thus, error reporting and recovery is an important concern under
173 *         these circumstances. Sometimes, due to programming errors, invoking a playback
174 *         control operation in an invalid state may also occur. Under all these
175 *         error conditions, the internal player engine invokes a user supplied
176 *         OnErrorListener.onError() method if an OnErrorListener has been
177 *         registered beforehand via
178 *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
179 *         <ul>
180 *         <li>It is important to note that once an error occurs, the
181 *         MediaPlayer object enters the <em>Error</em> state (except as noted
182 *         above), even if an error listener has not been registered by the application.</li>
183 *         <li>In order to reuse a MediaPlayer object that is in the <em>
184 *         Error</em> state and recover from the error,
185 *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
186 *         state.</li>
187 *         <li>It is good programming practice to have your application
188 *         register a OnErrorListener to look out for error notifications from
189 *         the internal player engine.</li>
190 *         <li>IllegalStateException is
191 *         thrown to prevent programming errors such as calling {@link #prepare()},
192 *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
193 *         </code> methods in an invalid state. </li>
194 *         </ul>
195 *         </li>
196 *     <li>Calling
197 *         {@link #setDataSource(FileDescriptor)}, or
198 *         {@link #setDataSource(String)}, or
199 *         {@link #setDataSource(Context, Uri)}, or
200 *         {@link #setDataSource(FileDescriptor, long, long)}, or
201 *         {@link #setDataSource(MediaDataSource)} transfers a
202 *         MediaPlayer object in the <em>Idle</em> state to the
203 *         <em>Initialized</em> state.
204 *         <ul>
205 *         <li>An IllegalStateException is thrown if
206 *         setDataSource() is called in any other state.</li>
207 *         <li>It is good programming
208 *         practice to always look out for <code>IllegalArgumentException</code>
209 *         and <code>IOException</code> that may be thrown from the overloaded
210 *         <code>setDataSource</code> methods.</li>
211 *         </ul>
212 *         </li>
213 *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
214 *         before playback can be started.
215 *         <ul>
216 *         <li>There are two ways (synchronous vs.
217 *         asynchronous) that the <em>Prepared</em> state can be reached:
218 *         either a call to {@link #prepare()} (synchronous) which
219 *         transfers the object to the <em>Prepared</em> state once the method call
220 *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
221 *         first transfers the object to the <em>Preparing</em> state after the
222 *         call returns (which occurs almost right way) while the internal
223 *         player engine continues working on the rest of preparation work
224 *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
225 *         the internal player engine then calls a user supplied callback method,
226 *         onPrepared() of the OnPreparedListener interface, if an
227 *         OnPreparedListener is registered beforehand via {@link
228 *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
229 *         <li>It is important to note that
230 *         the <em>Preparing</em> state is a transient state, and the behavior
231 *         of calling any method with side effect while a MediaPlayer object is
232 *         in the <em>Preparing</em> state is undefined.</li>
233 *         <li>An IllegalStateException is
234 *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
235 *         any other state.</li>
236 *         <li>While in the <em>Prepared</em> state, properties
237 *         such as audio/sound volume, screenOnWhilePlaying, looping can be
238 *         adjusted by invoking the corresponding set methods.</li>
239 *         </ul>
240 *         </li>
241 *     <li>To start the playback, {@link #start()} must be called. After
242 *         {@link #start()} returns successfully, the MediaPlayer object is in the
243 *         <em>Started</em> state. {@link #isPlaying()} can be called to test
244 *         whether the MediaPlayer object is in the <em>Started</em> state.
245 *         <ul>
246 *         <li>While in the <em>Started</em> state, the internal player engine calls
247 *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
248 *         method if a OnBufferingUpdateListener has been registered beforehand
249 *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
250 *         This callback allows applications to keep track of the buffering status
251 *         while streaming audio/video.</li>
252 *         <li>Calling {@link #start()} has not effect
253 *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
254 *         </ul>
255 *         </li>
256 *     <li>Playback can be paused and stopped, and the current playback position
257 *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
258 *         {@link #pause()} returns, the MediaPlayer object enters the
259 *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
260 *         state to the <em>Paused</em> state and vice versa happens
261 *         asynchronously in the player engine. It may take some time before
262 *         the state is updated in calls to {@link #isPlaying()}, and it can be
263 *         a number of seconds in the case of streamed content.
264 *         <ul>
265 *         <li>Calling {@link #start()} to resume playback for a paused
266 *         MediaPlayer object, and the resumed playback
267 *         position is the same as where it was paused. When the call to
268 *         {@link #start()} returns, the paused MediaPlayer object goes back to
269 *         the <em>Started</em> state.</li>
270 *         <li>Calling {@link #pause()} has no effect on
271 *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
272 *         </ul>
273 *         </li>
274 *     <li>Calling  {@link #stop()} stops playback and causes a
275 *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
276 *         </em> or <em>PlaybackCompleted</em> state to enter the
277 *         <em>Stopped</em> state.
278 *         <ul>
279 *         <li>Once in the <em>Stopped</em> state, playback cannot be started
280 *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
281 *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
282 *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
283 *         object that is already in the <em>Stopped</em> state.</li>
284 *         </ul>
285 *         </li>
286 *     <li>The playback position can be adjusted with a call to
287 *         {@link #seekTo(int, int)}.
288 *         <ul>
289 *         <li>Although the asynchronuous {@link #seekTo(int, int)}
290 *         call returns right away, the actual seek operation may take a while to
291 *         finish, especially for audio/video being streamed. When the actual
292 *         seek operation completes, the internal player engine calls a user
293 *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
294 *         has been registered beforehand via
295 *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
296 *         <li>Please
297 *         note that {@link #seekTo(int, int)} can also be called in the other states,
298 *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
299 *         </em> state. When {@link #seekTo(int, int)} is called in those states,
300 *         one video frame will be displayed if the stream has video and the requested
301 *         position is valid.
302 *         </li>
303 *         <li>Furthermore, the actual current playback position
304 *         can be retrieved with a call to {@link #getCurrentPosition()}, which
305 *         is helpful for applications such as a Music player that need to keep
306 *         track of the playback progress.</li>
307 *         </ul>
308 *         </li>
309 *     <li>When the playback reaches the end of stream, the playback completes.
310 *         <ul>
311 *         <li>If the looping mode was being set to <var>true</var>with
312 *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
313 *         the <em>Started</em> state.</li>
314 *         <li>If the looping mode was set to <var>false
315 *         </var>, the player engine calls a user supplied callback method,
316 *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
317 *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
318 *         The invoke of the callback signals that the object is now in the <em>
319 *         PlaybackCompleted</em> state.</li>
320 *         <li>While in the <em>PlaybackCompleted</em>
321 *         state, calling {@link #start()} can restart the playback from the
322 *         beginning of the audio/video source.</li>
323 * </ul>
324 *
325 *
326 * <a name="Valid_and_Invalid_States"></a>
327 * <h3>Valid and invalid states</h3>
328 *
329 * <table border="0" cellspacing="0" cellpadding="0">
330 * <tr><td>Method Name </p></td>
331 *     <td>Valid Sates </p></td>
332 *     <td>Invalid States </p></td>
333 *     <td>Comments </p></td></tr>
334 * <tr><td>attachAuxEffect </p></td>
335 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
336 *     <td>{Idle, Error} </p></td>
337 *     <td>This method must be called after setDataSource.
338 *     Calling it does not change the object state. </p></td></tr>
339 * <tr><td>getAudioSessionId </p></td>
340 *     <td>any </p></td>
341 *     <td>{} </p></td>
342 *     <td>This method can be called in any state and calling it does not change
343 *         the object state. </p></td></tr>
344 * <tr><td>getCurrentPosition </p></td>
345 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
346 *         PlaybackCompleted} </p></td>
347 *     <td>{Error}</p></td>
348 *     <td>Successful invoke of this method in a valid state does not change the
349 *         state. Calling this method in an invalid state transfers the object
350 *         to the <em>Error</em> state. </p></td></tr>
351 * <tr><td>getDuration </p></td>
352 *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
353 *     <td>{Idle, Initialized, Error} </p></td>
354 *     <td>Successful invoke of this method in a valid state does not change the
355 *         state. Calling this method in an invalid state transfers the object
356 *         to the <em>Error</em> state. </p></td></tr>
357 * <tr><td>getVideoHeight </p></td>
358 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
359 *         PlaybackCompleted}</p></td>
360 *     <td>{Error}</p></td>
361 *     <td>Successful invoke of this method in a valid state does not change the
362 *         state. Calling this method in an invalid state transfers the object
363 *         to the <em>Error</em> state.  </p></td></tr>
364 * <tr><td>getVideoWidth </p></td>
365 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
366 *         PlaybackCompleted}</p></td>
367 *     <td>{Error}</p></td>
368 *     <td>Successful invoke of this method in a valid state does not change
369 *         the state. Calling this method in an invalid state transfers the
370 *         object to the <em>Error</em> state. </p></td></tr>
371 * <tr><td>isPlaying </p></td>
372 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
373 *          PlaybackCompleted}</p></td>
374 *     <td>{Error}</p></td>
375 *     <td>Successful invoke of this method in a valid state does not change
376 *         the state. Calling this method in an invalid state transfers the
377 *         object to the <em>Error</em> state. </p></td></tr>
378 * <tr><td>pause </p></td>
379 *     <td>{Started, Paused, PlaybackCompleted}</p></td>
380 *     <td>{Idle, Initialized, Prepared, Stopped, Error}</p></td>
381 *     <td>Successful invoke of this method in a valid state transfers the
382 *         object to the <em>Paused</em> state. Calling this method in an
383 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
384 * <tr><td>prepare </p></td>
385 *     <td>{Initialized, Stopped} </p></td>
386 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
387 *     <td>Successful invoke of this method in a valid state transfers the
388 *         object to the <em>Prepared</em> state. Calling this method in an
389 *         invalid state throws an IllegalStateException.</p></td></tr>
390 * <tr><td>prepareAsync </p></td>
391 *     <td>{Initialized, Stopped} </p></td>
392 *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
393 *     <td>Successful invoke of this method in a valid state transfers the
394 *         object to the <em>Preparing</em> state. Calling this method in an
395 *         invalid state throws an IllegalStateException.</p></td></tr>
396 * <tr><td>release </p></td>
397 *     <td>any </p></td>
398 *     <td>{} </p></td>
399 *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
400 * <tr><td>reset </p></td>
401 *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
402 *         PlaybackCompleted, Error}</p></td>
403 *     <td>{}</p></td>
404 *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
405 * <tr><td>seekTo </p></td>
406 *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
407 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
408 *     <td>Successful invoke of this method in a valid state does not change
409 *         the state. Calling this method in an invalid state transfers the
410 *         object to the <em>Error</em> state. </p></td></tr>
411 * <tr><td>setAudioAttributes </p></td>
412 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
413 *          PlaybackCompleted}</p></td>
414 *     <td>{Error}</p></td>
415 *     <td>Successful invoke of this method does not change the state. In order for the
416 *         target audio attributes type to become effective, this method must be called before
417 *         prepare() or prepareAsync().</p></td></tr>
418 * <tr><td>setAudioSessionId </p></td>
419 *     <td>{Idle} </p></td>
420 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
421 *          Error} </p></td>
422 *     <td>This method must be called in idle state as the audio session ID must be known before
423 *         calling setDataSource. Calling it does not change the object state. </p></td></tr>
424 * <tr><td>setAudioStreamType (deprecated)</p></td>
425 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
426 *          PlaybackCompleted}</p></td>
427 *     <td>{Error}</p></td>
428 *     <td>Successful invoke of this method does not change the state. In order for the
429 *         target audio stream type to become effective, this method must be called before
430 *         prepare() or prepareAsync().</p></td></tr>
431 * <tr><td>setAuxEffectSendLevel </p></td>
432 *     <td>any</p></td>
433 *     <td>{} </p></td>
434 *     <td>Calling this method does not change the object state. </p></td></tr>
435 * <tr><td>setDataSource </p></td>
436 *     <td>{Idle} </p></td>
437 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
438 *          Error} </p></td>
439 *     <td>Successful invoke of this method in a valid state transfers the
440 *         object to the <em>Initialized</em> state. Calling this method in an
441 *         invalid state throws an IllegalStateException.</p></td></tr>
442 * <tr><td>setDisplay </p></td>
443 *     <td>any </p></td>
444 *     <td>{} </p></td>
445 *     <td>This method can be called in any state and calling it does not change
446 *         the object state. </p></td></tr>
447 * <tr><td>setSurface </p></td>
448 *     <td>any </p></td>
449 *     <td>{} </p></td>
450 *     <td>This method can be called in any state and calling it does not change
451 *         the object state. </p></td></tr>
452 * <tr><td>setVideoScalingMode </p></td>
453 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
454 *     <td>{Idle, Error}</p></td>
455 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
456 * <tr><td>setLooping </p></td>
457 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
458 *         PlaybackCompleted}</p></td>
459 *     <td>{Error}</p></td>
460 *     <td>Successful invoke of this method in a valid state does not change
461 *         the state. Calling this method in an
462 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
463 * <tr><td>isLooping </p></td>
464 *     <td>any </p></td>
465 *     <td>{} </p></td>
466 *     <td>This method can be called in any state and calling it does not change
467 *         the object state. </p></td></tr>
468 * <tr><td>setOnBufferingUpdateListener </p></td>
469 *     <td>any </p></td>
470 *     <td>{} </p></td>
471 *     <td>This method can be called in any state and calling it does not change
472 *         the object state. </p></td></tr>
473 * <tr><td>setOnCompletionListener </p></td>
474 *     <td>any </p></td>
475 *     <td>{} </p></td>
476 *     <td>This method can be called in any state and calling it does not change
477 *         the object state. </p></td></tr>
478 * <tr><td>setOnErrorListener </p></td>
479 *     <td>any </p></td>
480 *     <td>{} </p></td>
481 *     <td>This method can be called in any state and calling it does not change
482 *         the object state. </p></td></tr>
483 * <tr><td>setOnPreparedListener </p></td>
484 *     <td>any </p></td>
485 *     <td>{} </p></td>
486 *     <td>This method can be called in any state and calling it does not change
487 *         the object state. </p></td></tr>
488 * <tr><td>setOnSeekCompleteListener </p></td>
489 *     <td>any </p></td>
490 *     <td>{} </p></td>
491 *     <td>This method can be called in any state and calling it does not change
492 *         the object state. </p></td></tr>
493 * <tr><td>setBufferingParams</p></td>
494 *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, Error}</p></td>
495 *     <td>{Idle} </p></td>
496 *     <td>This method does not change the object state.
497 *         </p></td></tr>
498 * <tr><td>setPlaybackParams</p></td>
499 *     <td>{Initialized, Prepared, Started, Paused, PlaybackCompleted, Error}</p></td>
500 *     <td>{Idle, Stopped} </p></td>
501 *     <td>This method will change state in some cases, depending on when it's called.
502 *         </p></td></tr>
503 * <tr><td>setScreenOnWhilePlaying</></td>
504 *     <td>any </p></td>
505 *     <td>{} </p></td>
506 *     <td>This method can be called in any state and calling it does not change
507 *         the object state.  </p></td></tr>
508 * <tr><td>setVolume </p></td>
509 *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
510 *          PlaybackCompleted}</p></td>
511 *     <td>{Error}</p></td>
512 *     <td>Successful invoke of this method does not change the state.
513 * <tr><td>setWakeMode </p></td>
514 *     <td>any </p></td>
515 *     <td>{} </p></td>
516 *     <td>This method can be called in any state and calling it does not change
517 *         the object state.</p></td></tr>
518 * <tr><td>start </p></td>
519 *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
520 *     <td>{Idle, Initialized, Stopped, Error}</p></td>
521 *     <td>Successful invoke of this method in a valid state transfers the
522 *         object to the <em>Started</em> state. Calling this method in an
523 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
524 * <tr><td>stop </p></td>
525 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
526 *     <td>{Idle, Initialized, Error}</p></td>
527 *     <td>Successful invoke of this method in a valid state transfers the
528 *         object to the <em>Stopped</em> state. Calling this method in an
529 *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
530 * <tr><td>getTrackInfo </p></td>
531 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
532 *     <td>{Idle, Initialized, Error}</p></td>
533 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
534 * <tr><td>addTimedTextSource </p></td>
535 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
536 *     <td>{Idle, Initialized, Error}</p></td>
537 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
538 * <tr><td>selectTrack </p></td>
539 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
540 *     <td>{Idle, Initialized, Error}</p></td>
541 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
542 * <tr><td>deselectTrack </p></td>
543 *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
544 *     <td>{Idle, Initialized, Error}</p></td>
545 *     <td>Successful invoke of this method does not change the state.</p></td></tr>
546 *
547 * </table>
548 *
549 * <a name="Permissions"></a>
550 * <h3>Permissions</h3>
551 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
552 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
553 * element.
554 *
555 * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
556 * when used with network-based content.
557 *
558 * <a name="Callbacks"></a>
559 * <h3>Callbacks</h3>
560 * <p>Applications may want to register for informational and error
561 * events in order to be informed of some internal state update and
562 * possible runtime errors during playback or streaming. Registration for
563 * these events is done by properly setting the appropriate listeners (via calls
564 * to
565 * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
566 * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
567 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
568 * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
569 * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
570 * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
571 * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
572 * In order to receive the respective callback
573 * associated with these listeners, applications are required to create
574 * MediaPlayer objects on a thread with its own Looper running (main UI
575 * thread by default has a Looper running).
576 *
577 */
578public class MediaPlayer extends PlayerBase
579                         implements SubtitleController.Listener
580{
581    /**
582       Constant to retrieve only the new metadata since the last
583       call.
584       // FIXME: unhide.
585       // FIXME: add link to getMetadata(boolean, boolean)
586       {@hide}
587     */
588    public static final boolean METADATA_UPDATE_ONLY = true;
589
590    /**
591       Constant to retrieve all the metadata.
592       // FIXME: unhide.
593       // FIXME: add link to getMetadata(boolean, boolean)
594       {@hide}
595     */
596    public static final boolean METADATA_ALL = false;
597
598    /**
599       Constant to enable the metadata filter during retrieval.
600       // FIXME: unhide.
601       // FIXME: add link to getMetadata(boolean, boolean)
602       {@hide}
603     */
604    public static final boolean APPLY_METADATA_FILTER = true;
605
606    /**
607       Constant to disable the metadata filter during retrieval.
608       // FIXME: unhide.
609       // FIXME: add link to getMetadata(boolean, boolean)
610       {@hide}
611     */
612    public static final boolean BYPASS_METADATA_FILTER = false;
613
614    static {
615        System.loadLibrary("media_jni");
616        native_init();
617    }
618
619    private final static String TAG = "MediaPlayer";
620    // Name of the remote interface for the media player. Must be kept
621    // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
622    // macro invocation in IMediaPlayer.cpp
623    private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
624
625    private long mNativeContext; // accessed by native methods
626    private long mNativeSurfaceTexture;  // accessed by native methods
627    private int mListenerContext; // accessed by native methods
628    private SurfaceHolder mSurfaceHolder;
629    private EventHandler mEventHandler;
630    private PowerManager.WakeLock mWakeLock = null;
631    private boolean mScreenOnWhilePlaying;
632    private boolean mStayAwake;
633    private int mStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE;
634    private int mUsage = -1;
635    private boolean mBypassInterruptionPolicy;
636
637    // Modular DRM
638    private UUID mDrmUUID;
639    private final Object mDrmLock = new Object();
640    private DrmInfo mDrmInfo;
641    private boolean mDrmInfoResolved;
642    private boolean mActiveDrmScheme;
643    private boolean mDrmConfigAllowed;
644    private boolean mDrmProvisioningInProgress;
645    private boolean mPrepareDrmInProgress;
646    private ProvisioningThread mDrmProvisioningThread;
647
648    /**
649     * Default constructor. Consider using one of the create() methods for
650     * synchronously instantiating a MediaPlayer from a Uri or resource.
651     * <p>When done with the MediaPlayer, you should call  {@link #release()},
652     * to free the resources. If not released, too many MediaPlayer instances may
653     * result in an exception.</p>
654     */
655    public MediaPlayer() {
656        super(new AudioAttributes.Builder().build(),
657                AudioPlaybackConfiguration.PLAYER_TYPE_JAM_MEDIAPLAYER);
658
659        Looper looper;
660        if ((looper = Looper.myLooper()) != null) {
661            mEventHandler = new EventHandler(this, looper);
662        } else if ((looper = Looper.getMainLooper()) != null) {
663            mEventHandler = new EventHandler(this, looper);
664        } else {
665            mEventHandler = null;
666        }
667
668        mTimeProvider = new TimeProvider(this);
669        mOpenSubtitleSources = new Vector<InputStream>();
670
671        /* Native setup requires a weak reference to our object.
672         * It's easier to create it here than in C++.
673         */
674        native_setup(new WeakReference<MediaPlayer>(this));
675
676        baseRegisterPlayer();
677    }
678
679    /*
680     * Update the MediaPlayer SurfaceTexture.
681     * Call after setting a new display surface.
682     */
683    private native void _setVideoSurface(Surface surface);
684
685    /* Do not change these values (starting with INVOKE_ID) without updating
686     * their counterparts in include/media/mediaplayer.h!
687     */
688    private static final int INVOKE_ID_GET_TRACK_INFO = 1;
689    private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE = 2;
690    private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3;
691    private static final int INVOKE_ID_SELECT_TRACK = 4;
692    private static final int INVOKE_ID_DESELECT_TRACK = 5;
693    private static final int INVOKE_ID_SET_VIDEO_SCALE_MODE = 6;
694    private static final int INVOKE_ID_GET_SELECTED_TRACK = 7;
695
696    /**
697     * Create a request parcel which can be routed to the native media
698     * player using {@link #invoke(Parcel, Parcel)}. The Parcel
699     * returned has the proper InterfaceToken set. The caller should
700     * not overwrite that token, i.e it can only append data to the
701     * Parcel.
702     *
703     * @return A parcel suitable to hold a request for the native
704     * player.
705     * {@hide}
706     */
707    public Parcel newRequest() {
708        Parcel parcel = Parcel.obtain();
709        parcel.writeInterfaceToken(IMEDIA_PLAYER);
710        return parcel;
711    }
712
713    /**
714     * Invoke a generic method on the native player using opaque
715     * parcels for the request and reply. Both payloads' format is a
716     * convention between the java caller and the native player.
717     * Must be called after setDataSource to make sure a native player
718     * exists. On failure, a RuntimeException is thrown.
719     *
720     * @param request Parcel with the data for the extension. The
721     * caller must use {@link #newRequest()} to get one.
722     *
723     * @param reply Output parcel with the data returned by the
724     * native player.
725     * {@hide}
726     */
727    public void invoke(Parcel request, Parcel reply) {
728        int retcode = native_invoke(request, reply);
729        reply.setDataPosition(0);
730        if (retcode != 0) {
731            throw new RuntimeException("failure code: " + retcode);
732        }
733    }
734
735    /**
736     * Sets the {@link SurfaceHolder} to use for displaying the video
737     * portion of the media.
738     *
739     * Either a surface holder or surface must be set if a display or video sink
740     * is needed.  Not calling this method or {@link #setSurface(Surface)}
741     * when playing back a video will result in only the audio track being played.
742     * A null surface holder or surface will result in only the audio track being
743     * played.
744     *
745     * @param sh the SurfaceHolder to use for video display
746     * @throws IllegalStateException if the internal player engine has not been
747     * initialized or has been released.
748     */
749    public void setDisplay(SurfaceHolder sh) {
750        mSurfaceHolder = sh;
751        Surface surface;
752        if (sh != null) {
753            surface = sh.getSurface();
754        } else {
755            surface = null;
756        }
757        _setVideoSurface(surface);
758        updateSurfaceScreenOn();
759    }
760
761    /**
762     * Sets the {@link Surface} to be used as the sink for the video portion of
763     * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but
764     * does not support {@link #setScreenOnWhilePlaying(boolean)}.  Setting a
765     * Surface will un-set any Surface or SurfaceHolder that was previously set.
766     * A null surface will result in only the audio track being played.
767     *
768     * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
769     * returned from {@link SurfaceTexture#getTimestamp()} will have an
770     * unspecified zero point.  These timestamps cannot be directly compared
771     * between different media sources, different instances of the same media
772     * source, or multiple runs of the same program.  The timestamp is normally
773     * monotonically increasing and is unaffected by time-of-day adjustments,
774     * but it is reset when the position is set.
775     *
776     * @param surface The {@link Surface} to be used for the video portion of
777     * the media.
778     * @throws IllegalStateException if the internal player engine has not been
779     * initialized or has been released.
780     */
781    public void setSurface(Surface surface) {
782        if (mScreenOnWhilePlaying && surface != null) {
783            Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
784        }
785        mSurfaceHolder = null;
786        _setVideoSurface(surface);
787        updateSurfaceScreenOn();
788    }
789
790    /* Do not change these video scaling mode values below without updating
791     * their counterparts in system/window.h! Please do not forget to update
792     * {@link #isVideoScalingModeSupported} when new video scaling modes
793     * are added.
794     */
795    /**
796     * Specifies a video scaling mode. The content is stretched to the
797     * surface rendering area. When the surface has the same aspect ratio
798     * as the content, the aspect ratio of the content is maintained;
799     * otherwise, the aspect ratio of the content is not maintained when video
800     * is being rendered. Unlike {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING},
801     * there is no content cropping with this video scaling mode.
802     */
803    public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1;
804
805    /**
806     * Specifies a video scaling mode. The content is scaled, maintaining
807     * its aspect ratio. The whole surface area is always used. When the
808     * aspect ratio of the content is the same as the surface, no content
809     * is cropped; otherwise, content is cropped to fit the surface.
810     */
811    public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2;
812    /**
813     * Sets video scaling mode. To make the target video scaling mode
814     * effective during playback, this method must be called after
815     * data source is set. If not called, the default video
816     * scaling mode is {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}.
817     *
818     * <p> The supported video scaling modes are:
819     * <ul>
820     * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}
821     * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING}
822     * </ul>
823     *
824     * @param mode target video scaling mode. Must be one of the supported
825     * video scaling modes; otherwise, IllegalArgumentException will be thrown.
826     *
827     * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT
828     * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
829     */
830    public void setVideoScalingMode(int mode) {
831        if (!isVideoScalingModeSupported(mode)) {
832            final String msg = "Scaling mode " + mode + " is not supported";
833            throw new IllegalArgumentException(msg);
834        }
835        Parcel request = Parcel.obtain();
836        Parcel reply = Parcel.obtain();
837        try {
838            request.writeInterfaceToken(IMEDIA_PLAYER);
839            request.writeInt(INVOKE_ID_SET_VIDEO_SCALE_MODE);
840            request.writeInt(mode);
841            invoke(request, reply);
842        } finally {
843            request.recycle();
844            reply.recycle();
845        }
846    }
847
848    /**
849     * Convenience method to create a MediaPlayer for a given Uri.
850     * On success, {@link #prepare()} will already have been called and must not be called again.
851     * <p>When done with the MediaPlayer, you should call  {@link #release()},
852     * to free the resources. If not released, too many MediaPlayer instances will
853     * result in an exception.</p>
854     * <p>Note that since {@link #prepare()} is called automatically in this method,
855     * you cannot change the audio
856     * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
857     * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
858     *
859     * @param context the Context to use
860     * @param uri the Uri from which to get the datasource
861     * @return a MediaPlayer object, or null if creation failed
862     */
863    public static MediaPlayer create(Context context, Uri uri) {
864        return create (context, uri, null);
865    }
866
867    /**
868     * Convenience method to create a MediaPlayer for a given Uri.
869     * On success, {@link #prepare()} will already have been called and must not be called again.
870     * <p>When done with the MediaPlayer, you should call  {@link #release()},
871     * to free the resources. If not released, too many MediaPlayer instances will
872     * result in an exception.</p>
873     * <p>Note that since {@link #prepare()} is called automatically in this method,
874     * you cannot change the audio
875     * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
876     * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
877     *
878     * @param context the Context to use
879     * @param uri the Uri from which to get the datasource
880     * @param holder the SurfaceHolder to use for displaying the video
881     * @return a MediaPlayer object, or null if creation failed
882     */
883    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
884        int s = AudioSystem.newAudioSessionId();
885        return create(context, uri, holder, null, s > 0 ? s : 0);
886    }
887
888    /**
889     * Same factory method as {@link #create(Context, Uri, SurfaceHolder)} but that lets you specify
890     * the audio attributes and session ID to be used by the new MediaPlayer instance.
891     * @param context the Context to use
892     * @param uri the Uri from which to get the datasource
893     * @param holder the SurfaceHolder to use for displaying the video, may be null.
894     * @param audioAttributes the {@link AudioAttributes} to be used by the media player.
895     * @param audioSessionId the audio session ID to be used by the media player,
896     *     see {@link AudioManager#generateAudioSessionId()} to obtain a new session.
897     * @return a MediaPlayer object, or null if creation failed
898     */
899    public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder,
900            AudioAttributes audioAttributes, int audioSessionId) {
901
902        try {
903            MediaPlayer mp = new MediaPlayer();
904            final AudioAttributes aa = audioAttributes != null ? audioAttributes :
905                new AudioAttributes.Builder().build();
906            mp.setAudioAttributes(aa);
907            mp.setAudioSessionId(audioSessionId);
908            mp.setDataSource(context, uri);
909            if (holder != null) {
910                mp.setDisplay(holder);
911            }
912            mp.prepare();
913            return mp;
914        } catch (IOException ex) {
915            Log.d(TAG, "create failed:", ex);
916            // fall through
917        } catch (IllegalArgumentException ex) {
918            Log.d(TAG, "create failed:", ex);
919            // fall through
920        } catch (SecurityException ex) {
921            Log.d(TAG, "create failed:", ex);
922            // fall through
923        }
924
925        return null;
926    }
927
928    // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
929
930    /**
931     * Convenience method to create a MediaPlayer for a given resource id.
932     * On success, {@link #prepare()} will already have been called and must not be called again.
933     * <p>When done with the MediaPlayer, you should call  {@link #release()},
934     * to free the resources. If not released, too many MediaPlayer instances will
935     * result in an exception.</p>
936     * <p>Note that since {@link #prepare()} is called automatically in this method,
937     * you cannot change the audio
938     * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
939     * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
940     *
941     * @param context the Context to use
942     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
943     *              the resource to use as the datasource
944     * @return a MediaPlayer object, or null if creation failed
945     */
946    public static MediaPlayer create(Context context, int resid) {
947        int s = AudioSystem.newAudioSessionId();
948        return create(context, resid, null, s > 0 ? s : 0);
949    }
950
951    /**
952     * Same factory method as {@link #create(Context, int)} but that lets you specify the audio
953     * attributes and session ID to be used by the new MediaPlayer instance.
954     * @param context the Context to use
955     * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
956     *              the resource to use as the datasource
957     * @param audioAttributes the {@link AudioAttributes} to be used by the media player.
958     * @param audioSessionId the audio session ID to be used by the media player,
959     *     see {@link AudioManager#generateAudioSessionId()} to obtain a new session.
960     * @return a MediaPlayer object, or null if creation failed
961     */
962    public static MediaPlayer create(Context context, int resid,
963            AudioAttributes audioAttributes, int audioSessionId) {
964        try {
965            AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
966            if (afd == null) return null;
967
968            MediaPlayer mp = new MediaPlayer();
969
970            final AudioAttributes aa = audioAttributes != null ? audioAttributes :
971                new AudioAttributes.Builder().build();
972            mp.setAudioAttributes(aa);
973            mp.setAudioSessionId(audioSessionId);
974
975            mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
976            afd.close();
977            mp.prepare();
978            return mp;
979        } catch (IOException ex) {
980            Log.d(TAG, "create failed:", ex);
981            // fall through
982        } catch (IllegalArgumentException ex) {
983            Log.d(TAG, "create failed:", ex);
984           // fall through
985        } catch (SecurityException ex) {
986            Log.d(TAG, "create failed:", ex);
987            // fall through
988        }
989        return null;
990    }
991
992    /**
993     * Sets the data source as a content Uri.
994     *
995     * @param context the Context to use when resolving the Uri
996     * @param uri the Content URI of the data you want to play
997     * @throws IllegalStateException if it is called in an invalid state
998     */
999    public void setDataSource(@NonNull Context context, @NonNull Uri uri)
1000            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
1001        setDataSource(context, uri, null);
1002    }
1003
1004    /**
1005     * Sets the data source as a content Uri.
1006     *
1007     * @param context the Context to use when resolving the Uri
1008     * @param uri the Content URI of the data you want to play
1009     * @param headers the headers to be sent together with the request for the data
1010     *                Note that the cross domain redirection is allowed by default, but that can be
1011     *                changed with key/value pairs through the headers parameter with
1012     *                "android-allow-cross-domain-redirect" as the key and "0" or "1" as the value
1013     *                to disallow or allow cross domain redirection.
1014     * @throws IllegalStateException if it is called in an invalid state
1015     */
1016    public void setDataSource(@NonNull Context context, @NonNull Uri uri,
1017            @Nullable Map<String, String> headers) throws IOException, IllegalArgumentException,
1018                    SecurityException, IllegalStateException {
1019        // The context and URI usually belong to the calling user. Get a resolver for that user
1020        // and strip out the userId from the URI if present.
1021        final ContentResolver resolver = context.getContentResolver();
1022        final String scheme = uri.getScheme();
1023        final String authority = ContentProvider.getAuthorityWithoutUserId(uri.getAuthority());
1024        if (ContentResolver.SCHEME_FILE.equals(scheme)) {
1025            setDataSource(uri.getPath());
1026            return;
1027        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)
1028                && Settings.AUTHORITY.equals(authority)) {
1029            // Try cached ringtone first since the actual provider may not be
1030            // encryption aware, or it may be stored on CE media storage
1031            final int type = RingtoneManager.getDefaultType(uri);
1032            final Uri cacheUri = RingtoneManager.getCacheForType(type, context.getUserId());
1033            final Uri actualUri = RingtoneManager.getActualDefaultRingtoneUri(context, type);
1034            if (attemptDataSource(resolver, cacheUri)) {
1035                return;
1036            } else if (attemptDataSource(resolver, actualUri)) {
1037                return;
1038            } else {
1039                setDataSource(uri.toString(), headers);
1040            }
1041        } else {
1042            // Try requested Uri locally first, or fallback to media server
1043            if (attemptDataSource(resolver, uri)) {
1044                return;
1045            } else {
1046                setDataSource(uri.toString(), headers);
1047            }
1048        }
1049    }
1050
1051    private boolean attemptDataSource(ContentResolver resolver, Uri uri) {
1052        try (AssetFileDescriptor afd = resolver.openAssetFileDescriptor(uri, "r")) {
1053            setDataSource(afd);
1054            return true;
1055        } catch (NullPointerException | SecurityException | IOException ex) {
1056            Log.w(TAG, "Couldn't open " + uri + ": " + ex);
1057            return false;
1058        }
1059    }
1060
1061    /**
1062     * Sets the data source (file-path or http/rtsp URL) to use.
1063     *
1064     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
1065     * @throws IllegalStateException if it is called in an invalid state
1066     *
1067     * <p>When <code>path</code> refers to a local file, the file may actually be opened by a
1068     * process other than the calling application.  This implies that the pathname
1069     * should be an absolute path (as any other process runs with unspecified current working
1070     * directory), and that the pathname should reference a world-readable file.
1071     * As an alternative, the application could first open the file for reading,
1072     * and then use the file descriptor form {@link #setDataSource(FileDescriptor)}.
1073     */
1074    public void setDataSource(String path)
1075            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
1076        setDataSource(path, null, null);
1077    }
1078
1079    /**
1080     * Sets the data source (file-path or http/rtsp URL) to use.
1081     *
1082     * @param path the path of the file, or the http/rtsp URL of the stream you want to play
1083     * @param headers the headers associated with the http request for the stream you want to play
1084     * @throws IllegalStateException if it is called in an invalid state
1085     * @hide pending API council
1086     */
1087    public void setDataSource(String path, Map<String, String> headers)
1088            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException
1089    {
1090        String[] keys = null;
1091        String[] values = null;
1092
1093        if (headers != null) {
1094            keys = new String[headers.size()];
1095            values = new String[headers.size()];
1096
1097            int i = 0;
1098            for (Map.Entry<String, String> entry: headers.entrySet()) {
1099                keys[i] = entry.getKey();
1100                values[i] = entry.getValue();
1101                ++i;
1102            }
1103        }
1104        setDataSource(path, keys, values);
1105    }
1106
1107    private void setDataSource(String path, String[] keys, String[] values)
1108            throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
1109        final Uri uri = Uri.parse(path);
1110        final String scheme = uri.getScheme();
1111        if ("file".equals(scheme)) {
1112            path = uri.getPath();
1113        } else if (scheme != null) {
1114            // handle non-file sources
1115            nativeSetDataSource(
1116                MediaHTTPService.createHttpServiceBinderIfNecessary(path),
1117                path,
1118                keys,
1119                values);
1120            return;
1121        }
1122
1123        final File file = new File(path);
1124        if (file.exists()) {
1125            FileInputStream is = new FileInputStream(file);
1126            FileDescriptor fd = is.getFD();
1127            setDataSource(fd);
1128            is.close();
1129        } else {
1130            throw new IOException("setDataSource failed.");
1131        }
1132    }
1133
1134    private native void nativeSetDataSource(
1135        IBinder httpServiceBinder, String path, String[] keys, String[] values)
1136        throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
1137
1138    /**
1139     * Sets the data source (AssetFileDescriptor) to use. It is the caller's
1140     * responsibility to close the file descriptor. It is safe to do so as soon
1141     * as this call returns.
1142     *
1143     * @param afd the AssetFileDescriptor for the file you want to play
1144     * @throws IllegalStateException if it is called in an invalid state
1145     * @throws IllegalArgumentException if afd is not a valid AssetFileDescriptor
1146     * @throws IOException if afd can not be read
1147     */
1148    public void setDataSource(@NonNull AssetFileDescriptor afd)
1149            throws IOException, IllegalArgumentException, IllegalStateException {
1150        Preconditions.checkNotNull(afd);
1151        // Note: using getDeclaredLength so that our behavior is the same
1152        // as previous versions when the content provider is returning
1153        // a full file.
1154        if (afd.getDeclaredLength() < 0) {
1155            setDataSource(afd.getFileDescriptor());
1156        } else {
1157            setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
1158        }
1159    }
1160
1161    /**
1162     * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
1163     * to close the file descriptor. It is safe to do so as soon as this call returns.
1164     *
1165     * @param fd the FileDescriptor for the file you want to play
1166     * @throws IllegalStateException if it is called in an invalid state
1167     * @throws IllegalArgumentException if fd is not a valid FileDescriptor
1168     * @throws IOException if fd can not be read
1169     */
1170    public void setDataSource(FileDescriptor fd)
1171            throws IOException, IllegalArgumentException, IllegalStateException {
1172        // intentionally less than LONG_MAX
1173        setDataSource(fd, 0, 0x7ffffffffffffffL);
1174    }
1175
1176    /**
1177     * Sets the data source (FileDescriptor) to use.  The FileDescriptor must be
1178     * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
1179     * to close the file descriptor. It is safe to do so as soon as this call returns.
1180     *
1181     * @param fd the FileDescriptor for the file you want to play
1182     * @param offset the offset into the file where the data to be played starts, in bytes
1183     * @param length the length in bytes of the data to be played
1184     * @throws IllegalStateException if it is called in an invalid state
1185     * @throws IllegalArgumentException if fd is not a valid FileDescriptor
1186     * @throws IOException if fd can not be read
1187     */
1188    public void setDataSource(FileDescriptor fd, long offset, long length)
1189            throws IOException, IllegalArgumentException, IllegalStateException {
1190        _setDataSource(fd, offset, length);
1191    }
1192
1193    private native void _setDataSource(FileDescriptor fd, long offset, long length)
1194            throws IOException, IllegalArgumentException, IllegalStateException;
1195
1196    /**
1197     * Sets the data source (MediaDataSource) to use.
1198     *
1199     * @param dataSource the MediaDataSource for the media you want to play
1200     * @throws IllegalStateException if it is called in an invalid state
1201     * @throws IllegalArgumentException if dataSource is not a valid MediaDataSource
1202     */
1203    public void setDataSource(MediaDataSource dataSource)
1204            throws IllegalArgumentException, IllegalStateException {
1205        _setDataSource(dataSource);
1206    }
1207
1208    private native void _setDataSource(MediaDataSource dataSource)
1209          throws IllegalArgumentException, IllegalStateException;
1210
1211    /**
1212     * Prepares the player for playback, synchronously.
1213     *
1214     * After setting the datasource and the display surface, you need to either
1215     * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
1216     * which blocks until MediaPlayer is ready for playback.
1217     *
1218     * @throws IllegalStateException if it is called in an invalid state
1219     */
1220    public void prepare() throws IOException, IllegalStateException {
1221        _prepare();
1222        scanInternalSubtitleTracks();
1223    }
1224
1225    private native void _prepare() throws IOException, IllegalStateException;
1226
1227    /**
1228     * Prepares the player for playback, asynchronously.
1229     *
1230     * After setting the datasource and the display surface, you need to either
1231     * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
1232     * which returns immediately, rather than blocking until enough data has been
1233     * buffered.
1234     *
1235     * @throws IllegalStateException if it is called in an invalid state
1236     */
1237    public native void prepareAsync() throws IllegalStateException;
1238
1239    /**
1240     * Starts or resumes playback. If playback had previously been paused,
1241     * playback will continue from where it was paused. If playback had
1242     * been stopped, or never started before, playback will start at the
1243     * beginning.
1244     *
1245     * @throws IllegalStateException if it is called in an invalid state
1246     */
1247    public void start() throws IllegalStateException {
1248        baseStart();
1249        stayAwake(true);
1250        _start();
1251    }
1252
1253    private native void _start() throws IllegalStateException;
1254
1255
1256    private int getAudioStreamType() {
1257        if (mStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1258            mStreamType = _getAudioStreamType();
1259        }
1260        return mStreamType;
1261    }
1262
1263    private native int _getAudioStreamType() throws IllegalStateException;
1264
1265    /**
1266     * Stops playback after playback has been stopped or paused.
1267     *
1268     * @throws IllegalStateException if the internal player engine has not been
1269     * initialized.
1270     */
1271    public void stop() throws IllegalStateException {
1272        stayAwake(false);
1273        _stop();
1274        baseStop();
1275    }
1276
1277    private native void _stop() throws IllegalStateException;
1278
1279    /**
1280     * Pauses playback. Call start() to resume.
1281     *
1282     * @throws IllegalStateException if the internal player engine has not been
1283     * initialized.
1284     */
1285    public void pause() throws IllegalStateException {
1286        stayAwake(false);
1287        _pause();
1288        basePause();
1289    }
1290
1291    private native void _pause() throws IllegalStateException;
1292
1293    @Override
1294    void playerStart() {
1295        start();
1296    }
1297
1298    @Override
1299    void playerPause() {
1300        pause();
1301    }
1302
1303    @Override
1304    void playerStop() {
1305        stop();
1306    }
1307
1308    /**
1309     * Set the low-level power management behavior for this MediaPlayer.  This
1310     * can be used when the MediaPlayer is not playing through a SurfaceHolder
1311     * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
1312     * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
1313     *
1314     * <p>This function has the MediaPlayer access the low-level power manager
1315     * service to control the device's power usage while playing is occurring.
1316     * The parameter is a combination of {@link android.os.PowerManager} wake flags.
1317     * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
1318     * permission.
1319     * By default, no attempt is made to keep the device awake during playback.
1320     *
1321     * @param context the Context to use
1322     * @param mode    the power/wake mode to set
1323     * @see android.os.PowerManager
1324     */
1325    public void setWakeMode(Context context, int mode) {
1326        boolean washeld = false;
1327
1328        /* Disable persistant wakelocks in media player based on property */
1329        if (SystemProperties.getBoolean("audio.offload.ignore_setawake", false) == true) {
1330            Log.w(TAG, "IGNORING setWakeMode " + mode);
1331            return;
1332        }
1333
1334        if (mWakeLock != null) {
1335            if (mWakeLock.isHeld()) {
1336                washeld = true;
1337                mWakeLock.release();
1338            }
1339            mWakeLock = null;
1340        }
1341
1342        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
1343        mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
1344        mWakeLock.setReferenceCounted(false);
1345        if (washeld) {
1346            mWakeLock.acquire();
1347        }
1348    }
1349
1350    /**
1351     * Control whether we should use the attached SurfaceHolder to keep the
1352     * screen on while video playback is occurring.  This is the preferred
1353     * method over {@link #setWakeMode} where possible, since it doesn't
1354     * require that the application have permission for low-level wake lock
1355     * access.
1356     *
1357     * @param screenOn Supply true to keep the screen on, false to allow it
1358     * to turn off.
1359     */
1360    public void setScreenOnWhilePlaying(boolean screenOn) {
1361        if (mScreenOnWhilePlaying != screenOn) {
1362            if (screenOn && mSurfaceHolder == null) {
1363                Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
1364            }
1365            mScreenOnWhilePlaying = screenOn;
1366            updateSurfaceScreenOn();
1367        }
1368    }
1369
1370    private void stayAwake(boolean awake) {
1371        if (mWakeLock != null) {
1372            if (awake && !mWakeLock.isHeld()) {
1373                mWakeLock.acquire();
1374            } else if (!awake && mWakeLock.isHeld()) {
1375                mWakeLock.release();
1376            }
1377        }
1378        mStayAwake = awake;
1379        updateSurfaceScreenOn();
1380    }
1381
1382    private void updateSurfaceScreenOn() {
1383        if (mSurfaceHolder != null) {
1384            mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1385        }
1386    }
1387
1388    /**
1389     * Returns the width of the video.
1390     *
1391     * @return the width of the video, or 0 if there is no video,
1392     * no display surface was set, or the width has not been determined
1393     * yet. The OnVideoSizeChangedListener can be registered via
1394     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1395     * to provide a notification when the width is available.
1396     */
1397    public native int getVideoWidth();
1398
1399    /**
1400     * Returns the height of the video.
1401     *
1402     * @return the height of the video, or 0 if there is no video,
1403     * no display surface was set, or the height has not been determined
1404     * yet. The OnVideoSizeChangedListener can be registered via
1405     * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
1406     * to provide a notification when the height is available.
1407     */
1408    public native int getVideoHeight();
1409
1410    /**
1411     *  Returns Analytics/Metrics data about the current video in this player.
1412     *
1413     * @return the a map of attributes and values available for this video
1414     * player or null if no metrics are available.
1415     */
1416    public native Bundle getMetrics();
1417
1418    /**
1419     * Checks whether the MediaPlayer is playing.
1420     *
1421     * @return true if currently playing, false otherwise
1422     * @throws IllegalStateException if the internal player engine has not been
1423     * initialized or has been released.
1424     */
1425    public native boolean isPlaying();
1426
1427    /**
1428     * Gets the default buffering management params.
1429     * Calling it only after {@code setDataSource} has been called.
1430     * Each type of data source might have different set of default params.
1431     *
1432     * @return the default buffering management params supported by the source component.
1433     * @throws IllegalStateException if the internal player engine has not been
1434     * initialized, or {@code setDataSource} has not been called.
1435     */
1436    @NonNull
1437    public native BufferingParams getDefaultBufferingParams();
1438
1439    /**
1440     * Gets the current buffering management params used by the source component.
1441     * Calling it only after {@code setDataSource} has been called.
1442     *
1443     * @return the current buffering management params used by the source component.
1444     * @throws IllegalStateException if the internal player engine has not been
1445     * initialized, or {@code setDataSource} has not been called.
1446     */
1447    @NonNull
1448    public native BufferingParams getBufferingParams();
1449
1450    /**
1451     * Sets buffering management params.
1452     * The object sets its internal BufferingParams to the input, except that the input is
1453     * invalid or not supported.
1454     * Call it only after {@code setDataSource} has been called.
1455     * Users should only use supported mode returned by {@link #getDefaultBufferingParams()}
1456     * or its downsized version as described in {@link BufferingParams}.
1457     *
1458     * @param params the buffering management params.
1459     *
1460     * @throws IllegalStateException if the internal player engine has not been
1461     * initialized or has been released, or {@code setDataSource} has not been called.
1462     * @throws IllegalArgumentException if params is invalid or not supported.
1463     */
1464    public native void setBufferingParams(@NonNull BufferingParams params);
1465
1466    /**
1467     * Change playback speed of audio by resampling the audio.
1468     * <p>
1469     * Specifies resampling as audio mode for variable rate playback, i.e.,
1470     * resample the waveform based on the requested playback rate to get
1471     * a new waveform, and play back the new waveform at the original sampling
1472     * frequency.
1473     * When rate is larger than 1.0, pitch becomes higher.
1474     * When rate is smaller than 1.0, pitch becomes lower.
1475     *
1476     * @hide
1477     */
1478    public static final int PLAYBACK_RATE_AUDIO_MODE_RESAMPLE = 2;
1479
1480    /**
1481     * Change playback speed of audio without changing its pitch.
1482     * <p>
1483     * Specifies time stretching as audio mode for variable rate playback.
1484     * Time stretching changes the duration of the audio samples without
1485     * affecting its pitch.
1486     * <p>
1487     * This mode is only supported for a limited range of playback speed factors,
1488     * e.g. between 1/2x and 2x.
1489     *
1490     * @hide
1491     */
1492    public static final int PLAYBACK_RATE_AUDIO_MODE_STRETCH = 1;
1493
1494    /**
1495     * Change playback speed of audio without changing its pitch, and
1496     * possibly mute audio if time stretching is not supported for the playback
1497     * speed.
1498     * <p>
1499     * Try to keep audio pitch when changing the playback rate, but allow the
1500     * system to determine how to change audio playback if the rate is out
1501     * of range.
1502     *
1503     * @hide
1504     */
1505    public static final int PLAYBACK_RATE_AUDIO_MODE_DEFAULT = 0;
1506
1507    /** @hide */
1508    @IntDef(
1509        value = {
1510            PLAYBACK_RATE_AUDIO_MODE_DEFAULT,
1511            PLAYBACK_RATE_AUDIO_MODE_STRETCH,
1512            PLAYBACK_RATE_AUDIO_MODE_RESAMPLE,
1513    })
1514    @Retention(RetentionPolicy.SOURCE)
1515    public @interface PlaybackRateAudioMode {}
1516
1517    /**
1518     * Sets playback rate and audio mode.
1519     *
1520     * @param rate the ratio between desired playback rate and normal one.
1521     * @param audioMode audio playback mode. Must be one of the supported
1522     * audio modes.
1523     *
1524     * @throws IllegalStateException if the internal player engine has not been
1525     * initialized.
1526     * @throws IllegalArgumentException if audioMode is not supported.
1527     *
1528     * @hide
1529     */
1530    @NonNull
1531    public PlaybackParams easyPlaybackParams(float rate, @PlaybackRateAudioMode int audioMode) {
1532        PlaybackParams params = new PlaybackParams();
1533        params.allowDefaults();
1534        switch (audioMode) {
1535        case PLAYBACK_RATE_AUDIO_MODE_DEFAULT:
1536            params.setSpeed(rate).setPitch(1.0f);
1537            break;
1538        case PLAYBACK_RATE_AUDIO_MODE_STRETCH:
1539            params.setSpeed(rate).setPitch(1.0f)
1540                    .setAudioFallbackMode(params.AUDIO_FALLBACK_MODE_FAIL);
1541            break;
1542        case PLAYBACK_RATE_AUDIO_MODE_RESAMPLE:
1543            params.setSpeed(rate).setPitch(rate);
1544            break;
1545        default:
1546            final String msg = "Audio playback mode " + audioMode + " is not supported";
1547            throw new IllegalArgumentException(msg);
1548        }
1549        return params;
1550    }
1551
1552    /**
1553     * Sets playback rate using {@link PlaybackParams}. The object sets its internal
1554     * PlaybackParams to the input, except that the object remembers previous speed
1555     * when input speed is zero. This allows the object to resume at previous speed
1556     * when start() is called. Calling it before the object is prepared does not change
1557     * the object state. After the object is prepared, calling it with zero speed is
1558     * equivalent to calling pause(). After the object is prepared, calling it with
1559     * non-zero speed is equivalent to calling start().
1560     *
1561     * @param params the playback params.
1562     *
1563     * @throws IllegalStateException if the internal player engine has not been
1564     * initialized or has been released.
1565     * @throws IllegalArgumentException if params is not supported.
1566     */
1567    public native void setPlaybackParams(@NonNull PlaybackParams params);
1568
1569    /**
1570     * Gets the playback params, containing the current playback rate.
1571     *
1572     * @return the playback params.
1573     * @throws IllegalStateException if the internal player engine has not been
1574     * initialized.
1575     */
1576    @NonNull
1577    public native PlaybackParams getPlaybackParams();
1578
1579    /**
1580     * Sets A/V sync mode.
1581     *
1582     * @param params the A/V sync params to apply
1583     *
1584     * @throws IllegalStateException if the internal player engine has not been
1585     * initialized.
1586     * @throws IllegalArgumentException if params are not supported.
1587     */
1588    public native void setSyncParams(@NonNull SyncParams params);
1589
1590    /**
1591     * Gets the A/V sync mode.
1592     *
1593     * @return the A/V sync params
1594     *
1595     * @throws IllegalStateException if the internal player engine has not been
1596     * initialized.
1597     */
1598    @NonNull
1599    public native SyncParams getSyncParams();
1600
1601    /**
1602     * Seek modes used in method seekTo(int, int) to move media position
1603     * to a specified location.
1604     *
1605     * Do not change these mode values without updating their counterparts
1606     * in include/media/IMediaSource.h!
1607     */
1608    /**
1609     * This mode is used with {@link #seekTo(int, int)} to move media position to
1610     * a sync (or key) frame associated with a data source that is located
1611     * right before or at the given time.
1612     *
1613     * @see #seekTo(int, int)
1614     */
1615    public static final int SEEK_PREVIOUS_SYNC    = 0x00;
1616    /**
1617     * This mode is used with {@link #seekTo(int, int)} to move media position to
1618     * a sync (or key) frame associated with a data source that is located
1619     * right after or at the given time.
1620     *
1621     * @see #seekTo(int, int)
1622     */
1623    public static final int SEEK_NEXT_SYNC        = 0x01;
1624    /**
1625     * This mode is used with {@link #seekTo(int, int)} to move media position to
1626     * a sync (or key) frame associated with a data source that is located
1627     * closest to (in time) or at the given time.
1628     *
1629     * @see #seekTo(int, int)
1630     */
1631    public static final int SEEK_CLOSEST_SYNC     = 0x02;
1632    /**
1633     * This mode is used with {@link #seekTo(int, int)} to move media position to
1634     * a frame (not necessarily a key frame) associated with a data source that
1635     * is located closest to or at the given time.
1636     *
1637     * @see #seekTo(int, int)
1638     */
1639    public static final int SEEK_CLOSEST          = 0x03;
1640
1641    /** @hide */
1642    @IntDef(
1643        value = {
1644            SEEK_PREVIOUS_SYNC,
1645            SEEK_NEXT_SYNC,
1646            SEEK_CLOSEST_SYNC,
1647            SEEK_CLOSEST,
1648    })
1649    @Retention(RetentionPolicy.SOURCE)
1650    public @interface SeekMode {}
1651
1652    private native final void _seekTo(int msec, int mode);
1653
1654    /**
1655     * Moves the media to specified time position by considering the given mode.
1656     * <p>
1657     * When seekTo is finished, the user will be notified via OnSeekComplete supplied by the user.
1658     * There is at most one active seekTo processed at any time. If there is a to-be-completed
1659     * seekTo, new seekTo requests will be queued in such a way that only the last request
1660     * is kept. When current seekTo is completed, the queued request will be processed if
1661     * that request is different from just-finished seekTo operation, i.e., the requested
1662     * position or mode is different.
1663     *
1664     * @param msec the offset in milliseconds from the start to seek to.
1665     * When seeking to the given time position, there is no guarantee that the data source
1666     * has a frame located at the position. When this happens, a frame nearby will be rendered.
1667     * If msec is negative, time position zero will be used.
1668     * If msec is larger than duration, duration will be used.
1669     * @param mode the mode indicating where exactly to seek to.
1670     * Use {@link #SEEK_PREVIOUS_SYNC} if one wants to seek to a sync frame
1671     * that has a timestamp earlier than or the same as msec. Use
1672     * {@link #SEEK_NEXT_SYNC} if one wants to seek to a sync frame
1673     * that has a timestamp later than or the same as msec. Use
1674     * {@link #SEEK_CLOSEST_SYNC} if one wants to seek to a sync frame
1675     * that has a timestamp closest to or the same as msec. Use
1676     * {@link #SEEK_CLOSEST} if one wants to seek to a frame that may
1677     * or may not be a sync frame but is closest to or the same as msec.
1678     * {@link #SEEK_CLOSEST} often has larger performance overhead compared
1679     * to the other options if there is no sync frame located at msec.
1680     * @throws IllegalStateException if the internal player engine has not been
1681     * initialized
1682     * @throws IllegalArgumentException if the mode is invalid.
1683     */
1684    public void seekTo(int msec, @SeekMode int mode) throws IllegalStateException {
1685        if (mode < SEEK_PREVIOUS_SYNC || mode > SEEK_CLOSEST) {
1686            final String msg = "Illegal seek mode: " + mode;
1687            throw new IllegalArgumentException(msg);
1688        }
1689        _seekTo(msec, mode);
1690    }
1691
1692    /**
1693     * Seeks to specified time position.
1694     * Same as {@link #seekTo(int, int)} with {@code mode = SEEK_PREVIOUS_SYNC}.
1695     *
1696     * @param msec the offset in milliseconds from the start to seek to
1697     * @throws IllegalStateException if the internal player engine has not been
1698     * initialized
1699     */
1700    public void seekTo(int msec) throws IllegalStateException {
1701        seekTo(msec, SEEK_PREVIOUS_SYNC /* mode */);
1702    }
1703
1704    /**
1705     * Get current playback position as a {@link MediaTimestamp}.
1706     * <p>
1707     * The MediaTimestamp represents how the media time correlates to the system time in
1708     * a linear fashion using an anchor and a clock rate. During regular playback, the media
1709     * time moves fairly constantly (though the anchor frame may be rebased to a current
1710     * system time, the linear correlation stays steady). Therefore, this method does not
1711     * need to be called often.
1712     * <p>
1713     * To help users get current playback position, this method always anchors the timestamp
1714     * to the current {@link System#nanoTime system time}, so
1715     * {@link MediaTimestamp#getAnchorMediaTimeUs} can be used as current playback position.
1716     *
1717     * @return a MediaTimestamp object if a timestamp is available, or {@code null} if no timestamp
1718     *         is available, e.g. because the media player has not been initialized.
1719     *
1720     * @see MediaTimestamp
1721     */
1722    @Nullable
1723    public MediaTimestamp getTimestamp()
1724    {
1725        try {
1726            // TODO: get the timestamp from native side
1727            return new MediaTimestamp(
1728                    getCurrentPosition() * 1000L,
1729                    System.nanoTime(),
1730                    isPlaying() ? getPlaybackParams().getSpeed() : 0.f);
1731        } catch (IllegalStateException e) {
1732            return null;
1733        }
1734    }
1735
1736    /**
1737     * Gets the current playback position.
1738     *
1739     * @return the current position in milliseconds
1740     */
1741    public native int getCurrentPosition();
1742
1743    /**
1744     * Gets the duration of the file.
1745     *
1746     * @return the duration in milliseconds, if no duration is available
1747     *         (for example, if streaming live content), -1 is returned.
1748     */
1749    public native int getDuration();
1750
1751    /**
1752     * Gets the media metadata.
1753     *
1754     * @param update_only controls whether the full set of available
1755     * metadata is returned or just the set that changed since the
1756     * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
1757     * #METADATA_ALL}.
1758     *
1759     * @param apply_filter if true only metadata that matches the
1760     * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
1761     * #BYPASS_METADATA_FILTER}.
1762     *
1763     * @return The metadata, possibly empty. null if an error occured.
1764     // FIXME: unhide.
1765     * {@hide}
1766     */
1767    public Metadata getMetadata(final boolean update_only,
1768                                final boolean apply_filter) {
1769        Parcel reply = Parcel.obtain();
1770        Metadata data = new Metadata();
1771
1772        if (!native_getMetadata(update_only, apply_filter, reply)) {
1773            reply.recycle();
1774            return null;
1775        }
1776
1777        // Metadata takes over the parcel, don't recycle it unless
1778        // there is an error.
1779        if (!data.parse(reply)) {
1780            reply.recycle();
1781            return null;
1782        }
1783        return data;
1784    }
1785
1786    /**
1787     * Set a filter for the metadata update notification and update
1788     * retrieval. The caller provides 2 set of metadata keys, allowed
1789     * and blocked. The blocked set always takes precedence over the
1790     * allowed one.
1791     * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
1792     * shorthands to allow/block all or no metadata.
1793     *
1794     * By default, there is no filter set.
1795     *
1796     * @param allow Is the set of metadata the client is interested
1797     *              in receiving new notifications for.
1798     * @param block Is the set of metadata the client is not interested
1799     *              in receiving new notifications for.
1800     * @return The call status code.
1801     *
1802     // FIXME: unhide.
1803     * {@hide}
1804     */
1805    public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
1806        // Do our serialization manually instead of calling
1807        // Parcel.writeArray since the sets are made of the same type
1808        // we avoid paying the price of calling writeValue (used by
1809        // writeArray) which burns an extra int per element to encode
1810        // the type.
1811        Parcel request =  newRequest();
1812
1813        // The parcel starts already with an interface token. There
1814        // are 2 filters. Each one starts with a 4bytes number to
1815        // store the len followed by a number of int (4 bytes as well)
1816        // representing the metadata type.
1817        int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
1818
1819        if (request.dataCapacity() < capacity) {
1820            request.setDataCapacity(capacity);
1821        }
1822
1823        request.writeInt(allow.size());
1824        for(Integer t: allow) {
1825            request.writeInt(t);
1826        }
1827        request.writeInt(block.size());
1828        for(Integer t: block) {
1829            request.writeInt(t);
1830        }
1831        return native_setMetadataFilter(request);
1832    }
1833
1834    /**
1835     * Set the MediaPlayer to start when this MediaPlayer finishes playback
1836     * (i.e. reaches the end of the stream).
1837     * The media framework will attempt to transition from this player to
1838     * the next as seamlessly as possible. The next player can be set at
1839     * any time before completion, but shall be after setDataSource has been
1840     * called successfully. The next player must be prepared by the
1841     * app, and the application should not call start() on it.
1842     * The next MediaPlayer must be different from 'this'. An exception
1843     * will be thrown if next == this.
1844     * The application may call setNextMediaPlayer(null) to indicate no
1845     * next player should be started at the end of playback.
1846     * If the current player is looping, it will keep looping and the next
1847     * player will not be started.
1848     *
1849     * @param next the player to start after this one completes playback.
1850     *
1851     */
1852    public native void setNextMediaPlayer(MediaPlayer next);
1853
1854    /**
1855     * Releases resources associated with this MediaPlayer object.
1856     * It is considered good practice to call this method when you're
1857     * done using the MediaPlayer. In particular, whenever an Activity
1858     * of an application is paused (its onPause() method is called),
1859     * or stopped (its onStop() method is called), this method should be
1860     * invoked to release the MediaPlayer object, unless the application
1861     * has a special need to keep the object around. In addition to
1862     * unnecessary resources (such as memory and instances of codecs)
1863     * being held, failure to call this method immediately if a
1864     * MediaPlayer object is no longer needed may also lead to
1865     * continuous battery consumption for mobile devices, and playback
1866     * failure for other applications if no multiple instances of the
1867     * same codec are supported on a device. Even if multiple instances
1868     * of the same codec are supported, some performance degradation
1869     * may be expected when unnecessary multiple instances are used
1870     * at the same time.
1871     */
1872    public void release() {
1873        baseRelease();
1874        stayAwake(false);
1875        updateSurfaceScreenOn();
1876        mOnPreparedListener = null;
1877        mOnBufferingUpdateListener = null;
1878        mOnCompletionListener = null;
1879        mOnSeekCompleteListener = null;
1880        mOnErrorListener = null;
1881        mOnInfoListener = null;
1882        mOnVideoSizeChangedListener = null;
1883        mOnTimedTextListener = null;
1884        if (mTimeProvider != null) {
1885            mTimeProvider.close();
1886            mTimeProvider = null;
1887        }
1888        mOnSubtitleDataListener = null;
1889
1890        // Modular DRM clean up
1891        mOnDrmInfoHandlerDelegate = null;
1892        mOnDrmPreparedHandlerDelegate = null;
1893        resetDrmState();
1894
1895        _release();
1896    }
1897
1898    private native void _release();
1899
1900    /**
1901     * Resets the MediaPlayer to its uninitialized state. After calling
1902     * this method, you will have to initialize it again by setting the
1903     * data source and calling prepare().
1904     */
1905    public void reset() {
1906        mSelectedSubtitleTrackIndex = -1;
1907        synchronized(mOpenSubtitleSources) {
1908            for (final InputStream is: mOpenSubtitleSources) {
1909                try {
1910                    is.close();
1911                } catch (IOException e) {
1912                }
1913            }
1914            mOpenSubtitleSources.clear();
1915        }
1916        if (mSubtitleController != null) {
1917            mSubtitleController.reset();
1918        }
1919        if (mTimeProvider != null) {
1920            mTimeProvider.close();
1921            mTimeProvider = null;
1922        }
1923
1924        stayAwake(false);
1925        _reset();
1926        // make sure none of the listeners get called anymore
1927        if (mEventHandler != null) {
1928            mEventHandler.removeCallbacksAndMessages(null);
1929        }
1930
1931        synchronized (mIndexTrackPairs) {
1932            mIndexTrackPairs.clear();
1933            mInbandTrackIndices.clear();
1934        };
1935
1936        resetDrmState();
1937    }
1938
1939    private native void _reset();
1940
1941    /**
1942     * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
1943     * for a list of stream types. Must call this method before prepare() or
1944     * prepareAsync() in order for the target stream type to become effective
1945     * thereafter.
1946     *
1947     * @param streamtype the audio stream type
1948     * @deprecated use {@link #setAudioAttributes(AudioAttributes)}
1949     * @see android.media.AudioManager
1950     */
1951    public void setAudioStreamType(int streamtype) {
1952        deprecateStreamTypeForPlayback(streamtype, "MediaPlayer", "setAudioStreamType()");
1953        baseUpdateAudioAttributes(
1954                new AudioAttributes.Builder().setInternalLegacyStreamType(streamtype).build());
1955        _setAudioStreamType(streamtype);
1956        mStreamType = streamtype;
1957    }
1958
1959    private native void _setAudioStreamType(int streamtype);
1960
1961    // Keep KEY_PARAMETER_* in sync with include/media/mediaplayer.h
1962    private final static int KEY_PARAMETER_AUDIO_ATTRIBUTES = 1400;
1963    /**
1964     * Sets the parameter indicated by key.
1965     * @param key key indicates the parameter to be set.
1966     * @param value value of the parameter to be set.
1967     * @return true if the parameter is set successfully, false otherwise
1968     * {@hide}
1969     */
1970    private native boolean setParameter(int key, Parcel value);
1971
1972    /**
1973     * Sets the audio attributes for this MediaPlayer.
1974     * See {@link AudioAttributes} for how to build and configure an instance of this class.
1975     * You must call this method before {@link #prepare()} or {@link #prepareAsync()} in order
1976     * for the audio attributes to become effective thereafter.
1977     * @param attributes a non-null set of audio attributes
1978     */
1979    public void setAudioAttributes(AudioAttributes attributes) throws IllegalArgumentException {
1980        if (attributes == null) {
1981            final String msg = "Cannot set AudioAttributes to null";
1982            throw new IllegalArgumentException(msg);
1983        }
1984        baseUpdateAudioAttributes(attributes);
1985        mUsage = attributes.getUsage();
1986        mBypassInterruptionPolicy = (attributes.getAllFlags()
1987                & AudioAttributes.FLAG_BYPASS_INTERRUPTION_POLICY) != 0;
1988        Parcel pattributes = Parcel.obtain();
1989        attributes.writeToParcel(pattributes, AudioAttributes.FLATTEN_TAGS);
1990        setParameter(KEY_PARAMETER_AUDIO_ATTRIBUTES, pattributes);
1991        pattributes.recycle();
1992    }
1993
1994    /**
1995     * Sets the player to be looping or non-looping.
1996     *
1997     * @param looping whether to loop or not
1998     */
1999    public native void setLooping(boolean looping);
2000
2001    /**
2002     * Checks whether the MediaPlayer is looping or non-looping.
2003     *
2004     * @return true if the MediaPlayer is currently looping, false otherwise
2005     */
2006    public native boolean isLooping();
2007
2008    /**
2009     * Sets the volume on this player.
2010     * This API is recommended for balancing the output of audio streams
2011     * within an application. Unless you are writing an application to
2012     * control user settings, this API should be used in preference to
2013     * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
2014     * a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
2015     * UI controls should be scaled logarithmically.
2016     *
2017     * @param leftVolume left volume scalar
2018     * @param rightVolume right volume scalar
2019     */
2020    /*
2021     * FIXME: Merge this into javadoc comment above when setVolume(float) is not @hide.
2022     * The single parameter form below is preferred if the channel volumes don't need
2023     * to be set independently.
2024     */
2025    public void setVolume(float leftVolume, float rightVolume) {
2026        baseSetVolume(leftVolume, rightVolume);
2027    }
2028
2029    @Override
2030    void playerSetVolume(boolean muting, float leftVolume, float rightVolume) {
2031        _setVolume(muting ? 0.0f : leftVolume, muting ? 0.0f : rightVolume);
2032    }
2033
2034    private native void _setVolume(float leftVolume, float rightVolume);
2035
2036    /**
2037     * Similar, excepts sets volume of all channels to same value.
2038     * @hide
2039     */
2040    public void setVolume(float volume) {
2041        setVolume(volume, volume);
2042    }
2043
2044    /**
2045     * Sets the audio session ID.
2046     *
2047     * @param sessionId the audio session ID.
2048     * The audio session ID is a system wide unique identifier for the audio stream played by
2049     * this MediaPlayer instance.
2050     * The primary use of the audio session ID  is to associate audio effects to a particular
2051     * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
2052     * this effect will be applied only to the audio content of media players within the same
2053     * audio session and not to the output mix.
2054     * When created, a MediaPlayer instance automatically generates its own audio session ID.
2055     * However, it is possible to force this player to be part of an already existing audio session
2056     * by calling this method.
2057     * This method must be called before one of the overloaded <code> setDataSource </code> methods.
2058     * @throws IllegalStateException if it is called in an invalid state
2059     */
2060    public native void setAudioSessionId(int sessionId)  throws IllegalArgumentException, IllegalStateException;
2061
2062    /**
2063     * Returns the audio session ID.
2064     *
2065     * @return the audio session ID. {@see #setAudioSessionId(int)}
2066     * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
2067     */
2068    public native int getAudioSessionId();
2069
2070    /**
2071     * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
2072     * effect which can be applied on any sound source that directs a certain amount of its
2073     * energy to this effect. This amount is defined by setAuxEffectSendLevel().
2074     * See {@link #setAuxEffectSendLevel(float)}.
2075     * <p>After creating an auxiliary effect (e.g.
2076     * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
2077     * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
2078     * to attach the player to the effect.
2079     * <p>To detach the effect from the player, call this method with a null effect id.
2080     * <p>This method must be called after one of the overloaded <code> setDataSource </code>
2081     * methods.
2082     * @param effectId system wide unique id of the effect to attach
2083     */
2084    public native void attachAuxEffect(int effectId);
2085
2086
2087    /**
2088     * Sets the send level of the player to the attached auxiliary effect.
2089     * See {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
2090     * <p>By default the send level is 0, so even if an effect is attached to the player
2091     * this method must be called for the effect to be applied.
2092     * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
2093     * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
2094     * so an appropriate conversion from linear UI input x to level is:
2095     * x == 0 -> level = 0
2096     * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
2097     * @param level send level scalar
2098     */
2099    public void setAuxEffectSendLevel(float level) {
2100        baseSetAuxEffectSendLevel(level);
2101    }
2102
2103    @Override
2104    int playerSetAuxEffectSendLevel(boolean muting, float level) {
2105        _setAuxEffectSendLevel(muting ? 0.0f : level);
2106        return AudioSystem.SUCCESS;
2107    }
2108
2109    private native void _setAuxEffectSendLevel(float level);
2110
2111    /*
2112     * @param request Parcel destinated to the media player. The
2113     *                Interface token must be set to the IMediaPlayer
2114     *                one to be routed correctly through the system.
2115     * @param reply[out] Parcel that will contain the reply.
2116     * @return The status code.
2117     */
2118    private native final int native_invoke(Parcel request, Parcel reply);
2119
2120
2121    /*
2122     * @param update_only If true fetch only the set of metadata that have
2123     *                    changed since the last invocation of getMetadata.
2124     *                    The set is built using the unfiltered
2125     *                    notifications the native player sent to the
2126     *                    MediaPlayerService during that period of
2127     *                    time. If false, all the metadatas are considered.
2128     * @param apply_filter  If true, once the metadata set has been built based on
2129     *                     the value update_only, the current filter is applied.
2130     * @param reply[out] On return contains the serialized
2131     *                   metadata. Valid only if the call was successful.
2132     * @return The status code.
2133     */
2134    private native final boolean native_getMetadata(boolean update_only,
2135                                                    boolean apply_filter,
2136                                                    Parcel reply);
2137
2138    /*
2139     * @param request Parcel with the 2 serialized lists of allowed
2140     *                metadata types followed by the one to be
2141     *                dropped. Each list starts with an integer
2142     *                indicating the number of metadata type elements.
2143     * @return The status code.
2144     */
2145    private native final int native_setMetadataFilter(Parcel request);
2146
2147    private static native final void native_init();
2148    private native final void native_setup(Object mediaplayer_this);
2149    private native final void native_finalize();
2150
2151    /**
2152     * Class for MediaPlayer to return each audio/video/subtitle track's metadata.
2153     *
2154     * @see android.media.MediaPlayer#getTrackInfo
2155     */
2156    static public class TrackInfo implements Parcelable {
2157        /**
2158         * Gets the track type.
2159         * @return TrackType which indicates if the track is video, audio, timed text.
2160         */
2161        public int getTrackType() {
2162            return mTrackType;
2163        }
2164
2165        /**
2166         * Gets the language code of the track.
2167         * @return a language code in either way of ISO-639-1 or ISO-639-2.
2168         * When the language is unknown or could not be determined,
2169         * ISO-639-2 language code, "und", is returned.
2170         */
2171        public String getLanguage() {
2172            String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
2173            return language == null ? "und" : language;
2174        }
2175
2176        /**
2177         * Gets the {@link MediaFormat} of the track.  If the format is
2178         * unknown or could not be determined, null is returned.
2179         */
2180        public MediaFormat getFormat() {
2181            if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT
2182                    || mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
2183                return mFormat;
2184            }
2185            return null;
2186        }
2187
2188        public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
2189        public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
2190        public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
2191        public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
2192        public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
2193        public static final int MEDIA_TRACK_TYPE_METADATA = 5;
2194
2195        final int mTrackType;
2196        final MediaFormat mFormat;
2197
2198        TrackInfo(Parcel in) {
2199            mTrackType = in.readInt();
2200            // TODO: parcel in the full MediaFormat; currently we are using createSubtitleFormat
2201            // even for audio/video tracks, meaning we only set the mime and language.
2202            String mime = in.readString();
2203            String language = in.readString();
2204            mFormat = MediaFormat.createSubtitleFormat(mime, language);
2205
2206            if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
2207                mFormat.setInteger(MediaFormat.KEY_IS_AUTOSELECT, in.readInt());
2208                mFormat.setInteger(MediaFormat.KEY_IS_DEFAULT, in.readInt());
2209                mFormat.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.readInt());
2210            }
2211        }
2212
2213        /** @hide */
2214        TrackInfo(int type, MediaFormat format) {
2215            mTrackType = type;
2216            mFormat = format;
2217        }
2218
2219        /**
2220         * {@inheritDoc}
2221         */
2222        @Override
2223        public int describeContents() {
2224            return 0;
2225        }
2226
2227        /**
2228         * {@inheritDoc}
2229         */
2230        @Override
2231        public void writeToParcel(Parcel dest, int flags) {
2232            dest.writeInt(mTrackType);
2233            dest.writeString(getLanguage());
2234
2235            if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
2236                dest.writeString(mFormat.getString(MediaFormat.KEY_MIME));
2237                dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_AUTOSELECT));
2238                dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_DEFAULT));
2239                dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE));
2240            }
2241        }
2242
2243        @Override
2244        public String toString() {
2245            StringBuilder out = new StringBuilder(128);
2246            out.append(getClass().getName());
2247            out.append('{');
2248            switch (mTrackType) {
2249            case MEDIA_TRACK_TYPE_VIDEO:
2250                out.append("VIDEO");
2251                break;
2252            case MEDIA_TRACK_TYPE_AUDIO:
2253                out.append("AUDIO");
2254                break;
2255            case MEDIA_TRACK_TYPE_TIMEDTEXT:
2256                out.append("TIMEDTEXT");
2257                break;
2258            case MEDIA_TRACK_TYPE_SUBTITLE:
2259                out.append("SUBTITLE");
2260                break;
2261            default:
2262                out.append("UNKNOWN");
2263                break;
2264            }
2265            out.append(", " + mFormat.toString());
2266            out.append("}");
2267            return out.toString();
2268        }
2269
2270        /**
2271         * Used to read a TrackInfo from a Parcel.
2272         */
2273        static final Parcelable.Creator<TrackInfo> CREATOR
2274                = new Parcelable.Creator<TrackInfo>() {
2275                    @Override
2276                    public TrackInfo createFromParcel(Parcel in) {
2277                        return new TrackInfo(in);
2278                    }
2279
2280                    @Override
2281                    public TrackInfo[] newArray(int size) {
2282                        return new TrackInfo[size];
2283                    }
2284                };
2285
2286    };
2287
2288    // We would like domain specific classes with more informative names than the `first` and `second`
2289    // in generic Pair, but we would also like to avoid creating new/trivial classes. As a compromise
2290    // we document the meanings of `first` and `second` here:
2291    //
2292    // Pair.first - inband track index; non-null iff representing an inband track.
2293    // Pair.second - a SubtitleTrack registered with mSubtitleController; non-null iff representing
2294    //               an inband subtitle track or any out-of-band track (subtitle or timedtext).
2295    private Vector<Pair<Integer, SubtitleTrack>> mIndexTrackPairs = new Vector<>();
2296    private BitSet mInbandTrackIndices = new BitSet();
2297
2298    /**
2299     * Returns an array of track information.
2300     *
2301     * @return Array of track info. The total number of tracks is the array length.
2302     * Must be called again if an external timed text source has been added after any of the
2303     * addTimedTextSource methods are called.
2304     * @throws IllegalStateException if it is called in an invalid state.
2305     */
2306    public TrackInfo[] getTrackInfo() throws IllegalStateException {
2307        TrackInfo trackInfo[] = getInbandTrackInfo();
2308        // add out-of-band tracks
2309        synchronized (mIndexTrackPairs) {
2310            TrackInfo allTrackInfo[] = new TrackInfo[mIndexTrackPairs.size()];
2311            for (int i = 0; i < allTrackInfo.length; i++) {
2312                Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
2313                if (p.first != null) {
2314                    // inband track
2315                    allTrackInfo[i] = trackInfo[p.first];
2316                } else {
2317                    SubtitleTrack track = p.second;
2318                    allTrackInfo[i] = new TrackInfo(track.getTrackType(), track.getFormat());
2319                }
2320            }
2321            return allTrackInfo;
2322        }
2323    }
2324
2325    private TrackInfo[] getInbandTrackInfo() throws IllegalStateException {
2326        Parcel request = Parcel.obtain();
2327        Parcel reply = Parcel.obtain();
2328        try {
2329            request.writeInterfaceToken(IMEDIA_PLAYER);
2330            request.writeInt(INVOKE_ID_GET_TRACK_INFO);
2331            invoke(request, reply);
2332            TrackInfo trackInfo[] = reply.createTypedArray(TrackInfo.CREATOR);
2333            return trackInfo;
2334        } finally {
2335            request.recycle();
2336            reply.recycle();
2337        }
2338    }
2339
2340    /* Do not change these values without updating their counterparts
2341     * in include/media/stagefright/MediaDefs.h and media/libstagefright/MediaDefs.cpp!
2342     */
2343    /**
2344     * MIME type for SubRip (SRT) container. Used in addTimedTextSource APIs.
2345     */
2346    public static final String MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
2347
2348    /**
2349     * MIME type for WebVTT subtitle data.
2350     * @hide
2351     */
2352    public static final String MEDIA_MIMETYPE_TEXT_VTT = "text/vtt";
2353
2354    /**
2355     * MIME type for CEA-608 closed caption data.
2356     * @hide
2357     */
2358    public static final String MEDIA_MIMETYPE_TEXT_CEA_608 = "text/cea-608";
2359
2360    /**
2361     * MIME type for CEA-708 closed caption data.
2362     * @hide
2363     */
2364    public static final String MEDIA_MIMETYPE_TEXT_CEA_708 = "text/cea-708";
2365
2366    /*
2367     * A helper function to check if the mime type is supported by media framework.
2368     */
2369    private static boolean availableMimeTypeForExternalSource(String mimeType) {
2370        if (MEDIA_MIMETYPE_TEXT_SUBRIP.equals(mimeType)) {
2371            return true;
2372        }
2373        return false;
2374    }
2375
2376    private SubtitleController mSubtitleController;
2377
2378    /** @hide */
2379    public void setSubtitleAnchor(
2380            SubtitleController controller,
2381            SubtitleController.Anchor anchor) {
2382        // TODO: create SubtitleController in MediaPlayer
2383        mSubtitleController = controller;
2384        mSubtitleController.setAnchor(anchor);
2385    }
2386
2387    /**
2388     * The private version of setSubtitleAnchor is used internally to set mSubtitleController if
2389     * necessary when clients don't provide their own SubtitleControllers using the public version
2390     * {@link #setSubtitleAnchor(SubtitleController, Anchor)} (e.g. {@link VideoView} provides one).
2391     */
2392    private synchronized void setSubtitleAnchor() {
2393        if ((mSubtitleController == null) && (ActivityThread.currentApplication() != null)) {
2394            final HandlerThread thread = new HandlerThread("SetSubtitleAnchorThread");
2395            thread.start();
2396            Handler handler = new Handler(thread.getLooper());
2397            handler.post(new Runnable() {
2398                @Override
2399                public void run() {
2400                    Context context = ActivityThread.currentApplication();
2401                    mSubtitleController = new SubtitleController(context, mTimeProvider, MediaPlayer.this);
2402                    mSubtitleController.setAnchor(new Anchor() {
2403                        @Override
2404                        public void setSubtitleWidget(RenderingWidget subtitleWidget) {
2405                        }
2406
2407                        @Override
2408                        public Looper getSubtitleLooper() {
2409                            return Looper.getMainLooper();
2410                        }
2411                    });
2412                    thread.getLooper().quitSafely();
2413                }
2414            });
2415            try {
2416                thread.join();
2417            } catch (InterruptedException e) {
2418                Thread.currentThread().interrupt();
2419                Log.w(TAG, "failed to join SetSubtitleAnchorThread");
2420            }
2421        }
2422    }
2423
2424    private int mSelectedSubtitleTrackIndex = -1;
2425    private Vector<InputStream> mOpenSubtitleSources;
2426
2427    private OnSubtitleDataListener mSubtitleDataListener = new OnSubtitleDataListener() {
2428        @Override
2429        public void onSubtitleData(MediaPlayer mp, SubtitleData data) {
2430            int index = data.getTrackIndex();
2431            synchronized (mIndexTrackPairs) {
2432                for (Pair<Integer, SubtitleTrack> p : mIndexTrackPairs) {
2433                    if (p.first != null && p.first == index && p.second != null) {
2434                        // inband subtitle track that owns data
2435                        SubtitleTrack track = p.second;
2436                        track.onData(data);
2437                    }
2438                }
2439            }
2440        }
2441    };
2442
2443    /** @hide */
2444    @Override
2445    public void onSubtitleTrackSelected(SubtitleTrack track) {
2446        if (mSelectedSubtitleTrackIndex >= 0) {
2447            try {
2448                selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, false);
2449            } catch (IllegalStateException e) {
2450            }
2451            mSelectedSubtitleTrackIndex = -1;
2452        }
2453        setOnSubtitleDataListener(null);
2454        if (track == null) {
2455            return;
2456        }
2457
2458        synchronized (mIndexTrackPairs) {
2459            for (Pair<Integer, SubtitleTrack> p : mIndexTrackPairs) {
2460                if (p.first != null && p.second == track) {
2461                    // inband subtitle track that is selected
2462                    mSelectedSubtitleTrackIndex = p.first;
2463                    break;
2464                }
2465            }
2466        }
2467
2468        if (mSelectedSubtitleTrackIndex >= 0) {
2469            try {
2470                selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, true);
2471            } catch (IllegalStateException e) {
2472            }
2473            setOnSubtitleDataListener(mSubtitleDataListener);
2474        }
2475        // no need to select out-of-band tracks
2476    }
2477
2478    /** @hide */
2479    public void addSubtitleSource(InputStream is, MediaFormat format)
2480            throws IllegalStateException
2481    {
2482        final InputStream fIs = is;
2483        final MediaFormat fFormat = format;
2484
2485        if (is != null) {
2486            // Ensure all input streams are closed.  It is also a handy
2487            // way to implement timeouts in the future.
2488            synchronized(mOpenSubtitleSources) {
2489                mOpenSubtitleSources.add(is);
2490            }
2491        } else {
2492            Log.w(TAG, "addSubtitleSource called with null InputStream");
2493        }
2494
2495        getMediaTimeProvider();
2496
2497        // process each subtitle in its own thread
2498        final HandlerThread thread = new HandlerThread("SubtitleReadThread",
2499              Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
2500        thread.start();
2501        Handler handler = new Handler(thread.getLooper());
2502        handler.post(new Runnable() {
2503            private int addTrack() {
2504                if (fIs == null || mSubtitleController == null) {
2505                    return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
2506                }
2507
2508                SubtitleTrack track = mSubtitleController.addTrack(fFormat);
2509                if (track == null) {
2510                    return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
2511                }
2512
2513                // TODO: do the conversion in the subtitle track
2514                Scanner scanner = new Scanner(fIs, "UTF-8");
2515                String contents = scanner.useDelimiter("\\A").next();
2516                synchronized(mOpenSubtitleSources) {
2517                    mOpenSubtitleSources.remove(fIs);
2518                }
2519                scanner.close();
2520                synchronized (mIndexTrackPairs) {
2521                    mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(null, track));
2522                }
2523                Handler h = mTimeProvider.mEventHandler;
2524                int what = TimeProvider.NOTIFY;
2525                int arg1 = TimeProvider.NOTIFY_TRACK_DATA;
2526                Pair<SubtitleTrack, byte[]> trackData = Pair.create(track, contents.getBytes());
2527                Message m = h.obtainMessage(what, arg1, 0, trackData);
2528                h.sendMessage(m);
2529                return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
2530            }
2531
2532            public void run() {
2533                int res = addTrack();
2534                if (mEventHandler != null) {
2535                    Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
2536                    mEventHandler.sendMessage(m);
2537                }
2538                thread.getLooper().quitSafely();
2539            }
2540        });
2541    }
2542
2543    private void scanInternalSubtitleTracks() {
2544        setSubtitleAnchor();
2545
2546        populateInbandTracks();
2547
2548        if (mSubtitleController != null) {
2549            mSubtitleController.selectDefaultTrack();
2550        }
2551    }
2552
2553    private void populateInbandTracks() {
2554        TrackInfo[] tracks = getInbandTrackInfo();
2555        synchronized (mIndexTrackPairs) {
2556            for (int i = 0; i < tracks.length; i++) {
2557                if (mInbandTrackIndices.get(i)) {
2558                    continue;
2559                } else {
2560                    mInbandTrackIndices.set(i);
2561                }
2562
2563                // newly appeared inband track
2564                if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
2565                    SubtitleTrack track = mSubtitleController.addTrack(
2566                            tracks[i].getFormat());
2567                    mIndexTrackPairs.add(Pair.create(i, track));
2568                } else {
2569                    mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(i, null));
2570                }
2571            }
2572        }
2573    }
2574
2575    /* TODO: Limit the total number of external timed text source to a reasonable number.
2576     */
2577    /**
2578     * Adds an external timed text source file.
2579     *
2580     * Currently supported format is SubRip with the file extension .srt, case insensitive.
2581     * Note that a single external timed text source may contain multiple tracks in it.
2582     * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
2583     * additional tracks become available after this method call.
2584     *
2585     * @param path The file path of external timed text source file.
2586     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2587     * @throws IOException if the file cannot be accessed or is corrupted.
2588     * @throws IllegalArgumentException if the mimeType is not supported.
2589     * @throws IllegalStateException if called in an invalid state.
2590     */
2591    public void addTimedTextSource(String path, String mimeType)
2592            throws IOException, IllegalArgumentException, IllegalStateException {
2593        if (!availableMimeTypeForExternalSource(mimeType)) {
2594            final String msg = "Illegal mimeType for timed text source: " + mimeType;
2595            throw new IllegalArgumentException(msg);
2596        }
2597
2598        File file = new File(path);
2599        if (file.exists()) {
2600            FileInputStream is = new FileInputStream(file);
2601            FileDescriptor fd = is.getFD();
2602            addTimedTextSource(fd, mimeType);
2603            is.close();
2604        } else {
2605            // We do not support the case where the path is not a file.
2606            throw new IOException(path);
2607        }
2608    }
2609
2610    /**
2611     * Adds an external timed text source file (Uri).
2612     *
2613     * Currently supported format is SubRip with the file extension .srt, case insensitive.
2614     * Note that a single external timed text source may contain multiple tracks in it.
2615     * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
2616     * additional tracks become available after this method call.
2617     *
2618     * @param context the Context to use when resolving the Uri
2619     * @param uri the Content URI of the data you want to play
2620     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2621     * @throws IOException if the file cannot be accessed or is corrupted.
2622     * @throws IllegalArgumentException if the mimeType is not supported.
2623     * @throws IllegalStateException if called in an invalid state.
2624     */
2625    public void addTimedTextSource(Context context, Uri uri, String mimeType)
2626            throws IOException, IllegalArgumentException, IllegalStateException {
2627        String scheme = uri.getScheme();
2628        if(scheme == null || scheme.equals("file")) {
2629            addTimedTextSource(uri.getPath(), mimeType);
2630            return;
2631        }
2632
2633        AssetFileDescriptor fd = null;
2634        try {
2635            ContentResolver resolver = context.getContentResolver();
2636            fd = resolver.openAssetFileDescriptor(uri, "r");
2637            if (fd == null) {
2638                return;
2639            }
2640            addTimedTextSource(fd.getFileDescriptor(), mimeType);
2641            return;
2642        } catch (SecurityException ex) {
2643        } catch (IOException ex) {
2644        } finally {
2645            if (fd != null) {
2646                fd.close();
2647            }
2648        }
2649    }
2650
2651    /**
2652     * Adds an external timed text source file (FileDescriptor).
2653     *
2654     * It is the caller's responsibility to close the file descriptor.
2655     * It is safe to do so as soon as this call returns.
2656     *
2657     * Currently supported format is SubRip. Note that a single external timed text source may
2658     * contain multiple tracks in it. One can find the total number of available tracks
2659     * using {@link #getTrackInfo()} to see what additional tracks become available
2660     * after this method call.
2661     *
2662     * @param fd the FileDescriptor for the file you want to play
2663     * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2664     * @throws IllegalArgumentException if the mimeType is not supported.
2665     * @throws IllegalStateException if called in an invalid state.
2666     */
2667    public void addTimedTextSource(FileDescriptor fd, String mimeType)
2668            throws IllegalArgumentException, IllegalStateException {
2669        // intentionally less than LONG_MAX
2670        addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
2671    }
2672
2673    /**
2674     * Adds an external timed text file (FileDescriptor).
2675     *
2676     * It is the caller's responsibility to close the file descriptor.
2677     * It is safe to do so as soon as this call returns.
2678     *
2679     * Currently supported format is SubRip. Note that a single external timed text source may
2680     * contain multiple tracks in it. One can find the total number of available tracks
2681     * using {@link #getTrackInfo()} to see what additional tracks become available
2682     * after this method call.
2683     *
2684     * @param fd the FileDescriptor for the file you want to play
2685     * @param offset the offset into the file where the data to be played starts, in bytes
2686     * @param length the length in bytes of the data to be played
2687     * @param mime The mime type of the file. Must be one of the mime types listed above.
2688     * @throws IllegalArgumentException if the mimeType is not supported.
2689     * @throws IllegalStateException if called in an invalid state.
2690     */
2691    public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mime)
2692            throws IllegalArgumentException, IllegalStateException {
2693        if (!availableMimeTypeForExternalSource(mime)) {
2694            throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mime);
2695        }
2696
2697        final FileDescriptor dupedFd;
2698        try {
2699            dupedFd = Libcore.os.dup(fd);
2700        } catch (ErrnoException ex) {
2701            Log.e(TAG, ex.getMessage(), ex);
2702            throw new RuntimeException(ex);
2703        }
2704
2705        final MediaFormat fFormat = new MediaFormat();
2706        fFormat.setString(MediaFormat.KEY_MIME, mime);
2707        fFormat.setInteger(MediaFormat.KEY_IS_TIMED_TEXT, 1);
2708
2709        // A MediaPlayer created by a VideoView should already have its mSubtitleController set.
2710        if (mSubtitleController == null) {
2711            setSubtitleAnchor();
2712        }
2713
2714        if (!mSubtitleController.hasRendererFor(fFormat)) {
2715            // test and add not atomic
2716            Context context = ActivityThread.currentApplication();
2717            mSubtitleController.registerRenderer(new SRTRenderer(context, mEventHandler));
2718        }
2719        final SubtitleTrack track = mSubtitleController.addTrack(fFormat);
2720        synchronized (mIndexTrackPairs) {
2721            mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(null, track));
2722        }
2723
2724        getMediaTimeProvider();
2725
2726        final long offset2 = offset;
2727        final long length2 = length;
2728        final HandlerThread thread = new HandlerThread(
2729                "TimedTextReadThread",
2730                Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
2731        thread.start();
2732        Handler handler = new Handler(thread.getLooper());
2733        handler.post(new Runnable() {
2734            private int addTrack() {
2735                final ByteArrayOutputStream bos = new ByteArrayOutputStream();
2736                try {
2737                    Libcore.os.lseek(dupedFd, offset2, OsConstants.SEEK_SET);
2738                    byte[] buffer = new byte[4096];
2739                    for (long total = 0; total < length2;) {
2740                        int bytesToRead = (int) Math.min(buffer.length, length2 - total);
2741                        int bytes = IoBridge.read(dupedFd, buffer, 0, bytesToRead);
2742                        if (bytes < 0) {
2743                            break;
2744                        } else {
2745                            bos.write(buffer, 0, bytes);
2746                            total += bytes;
2747                        }
2748                    }
2749                    Handler h = mTimeProvider.mEventHandler;
2750                    int what = TimeProvider.NOTIFY;
2751                    int arg1 = TimeProvider.NOTIFY_TRACK_DATA;
2752                    Pair<SubtitleTrack, byte[]> trackData = Pair.create(track, bos.toByteArray());
2753                    Message m = h.obtainMessage(what, arg1, 0, trackData);
2754                    h.sendMessage(m);
2755                    return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
2756                } catch (Exception e) {
2757                    Log.e(TAG, e.getMessage(), e);
2758                    return MEDIA_INFO_TIMED_TEXT_ERROR;
2759                } finally {
2760                    try {
2761                        Libcore.os.close(dupedFd);
2762                    } catch (ErrnoException e) {
2763                        Log.e(TAG, e.getMessage(), e);
2764                    }
2765                }
2766            }
2767
2768            public void run() {
2769                int res = addTrack();
2770                if (mEventHandler != null) {
2771                    Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
2772                    mEventHandler.sendMessage(m);
2773                }
2774                thread.getLooper().quitSafely();
2775            }
2776        });
2777    }
2778
2779    /**
2780     * Returns the index of the audio, video, or subtitle track currently selected for playback,
2781     * The return value is an index into the array returned by {@link #getTrackInfo()}, and can
2782     * be used in calls to {@link #selectTrack(int)} or {@link #deselectTrack(int)}.
2783     *
2784     * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
2785     * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
2786     * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
2787     * @return index of the audio, video, or subtitle track currently selected for playback;
2788     * a negative integer is returned when there is no selected track for {@code trackType} or
2789     * when {@code trackType} is not one of audio, video, or subtitle.
2790     * @throws IllegalStateException if called after {@link #release()}
2791     *
2792     * @see #getTrackInfo()
2793     * @see #selectTrack(int)
2794     * @see #deselectTrack(int)
2795     */
2796    public int getSelectedTrack(int trackType) throws IllegalStateException {
2797        if (mSubtitleController != null
2798                && (trackType == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE
2799                || trackType == TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT)) {
2800            SubtitleTrack subtitleTrack = mSubtitleController.getSelectedTrack();
2801            if (subtitleTrack != null) {
2802                synchronized (mIndexTrackPairs) {
2803                    for (int i = 0; i < mIndexTrackPairs.size(); i++) {
2804                        Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
2805                        if (p.second == subtitleTrack && subtitleTrack.getTrackType() == trackType) {
2806                            return i;
2807                        }
2808                    }
2809                }
2810            }
2811        }
2812
2813        Parcel request = Parcel.obtain();
2814        Parcel reply = Parcel.obtain();
2815        try {
2816            request.writeInterfaceToken(IMEDIA_PLAYER);
2817            request.writeInt(INVOKE_ID_GET_SELECTED_TRACK);
2818            request.writeInt(trackType);
2819            invoke(request, reply);
2820            int inbandTrackIndex = reply.readInt();
2821            synchronized (mIndexTrackPairs) {
2822                for (int i = 0; i < mIndexTrackPairs.size(); i++) {
2823                    Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
2824                    if (p.first != null && p.first == inbandTrackIndex) {
2825                        return i;
2826                    }
2827                }
2828            }
2829            return -1;
2830        } finally {
2831            request.recycle();
2832            reply.recycle();
2833        }
2834    }
2835
2836    /**
2837     * Selects a track.
2838     * <p>
2839     * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
2840     * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
2841     * If a MediaPlayer is not in Started state, it just marks the track to be played.
2842     * </p>
2843     * <p>
2844     * In any valid state, if it is called multiple times on the same type of track (ie. Video,
2845     * Audio, Timed Text), the most recent one will be chosen.
2846     * </p>
2847     * <p>
2848     * The first audio and video tracks are selected by default if available, even though
2849     * this method is not called. However, no timed text track will be selected until
2850     * this function is called.
2851     * </p>
2852     * <p>
2853     * Currently, only timed text tracks or audio tracks can be selected via this method.
2854     * In addition, the support for selecting an audio track at runtime is pretty limited
2855     * in that an audio track can only be selected in the <em>Prepared</em> state.
2856     * </p>
2857     * @param index the index of the track to be selected. The valid range of the index
2858     * is 0..total number of track - 1. The total number of tracks as well as the type of
2859     * each individual track can be found by calling {@link #getTrackInfo()} method.
2860     * @throws IllegalStateException if called in an invalid state.
2861     *
2862     * @see android.media.MediaPlayer#getTrackInfo
2863     */
2864    public void selectTrack(int index) throws IllegalStateException {
2865        selectOrDeselectTrack(index, true /* select */);
2866    }
2867
2868    /**
2869     * Deselect a track.
2870     * <p>
2871     * Currently, the track must be a timed text track and no audio or video tracks can be
2872     * deselected. If the timed text track identified by index has not been
2873     * selected before, it throws an exception.
2874     * </p>
2875     * @param index the index of the track to be deselected. The valid range of the index
2876     * is 0..total number of tracks - 1. The total number of tracks as well as the type of
2877     * each individual track can be found by calling {@link #getTrackInfo()} method.
2878     * @throws IllegalStateException if called in an invalid state.
2879     *
2880     * @see android.media.MediaPlayer#getTrackInfo
2881     */
2882    public void deselectTrack(int index) throws IllegalStateException {
2883        selectOrDeselectTrack(index, false /* select */);
2884    }
2885
2886    private void selectOrDeselectTrack(int index, boolean select)
2887            throws IllegalStateException {
2888        // handle subtitle track through subtitle controller
2889        populateInbandTracks();
2890
2891        Pair<Integer,SubtitleTrack> p = null;
2892        try {
2893            p = mIndexTrackPairs.get(index);
2894        } catch (ArrayIndexOutOfBoundsException e) {
2895            // ignore bad index
2896            return;
2897        }
2898
2899        SubtitleTrack track = p.second;
2900        if (track == null) {
2901            // inband (de)select
2902            selectOrDeselectInbandTrack(p.first, select);
2903            return;
2904        }
2905
2906        if (mSubtitleController == null) {
2907            return;
2908        }
2909
2910        if (!select) {
2911            // out-of-band deselect
2912            if (mSubtitleController.getSelectedTrack() == track) {
2913                mSubtitleController.selectTrack(null);
2914            } else {
2915                Log.w(TAG, "trying to deselect track that was not selected");
2916            }
2917            return;
2918        }
2919
2920        // out-of-band select
2921        if (track.getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT) {
2922            int ttIndex = getSelectedTrack(TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT);
2923            synchronized (mIndexTrackPairs) {
2924                if (ttIndex >= 0 && ttIndex < mIndexTrackPairs.size()) {
2925                    Pair<Integer,SubtitleTrack> p2 = mIndexTrackPairs.get(ttIndex);
2926                    if (p2.first != null && p2.second == null) {
2927                        // deselect inband counterpart
2928                        selectOrDeselectInbandTrack(p2.first, false);
2929                    }
2930                }
2931            }
2932        }
2933        mSubtitleController.selectTrack(track);
2934    }
2935
2936    private void selectOrDeselectInbandTrack(int index, boolean select)
2937            throws IllegalStateException {
2938        Parcel request = Parcel.obtain();
2939        Parcel reply = Parcel.obtain();
2940        try {
2941            request.writeInterfaceToken(IMEDIA_PLAYER);
2942            request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
2943            request.writeInt(index);
2944            invoke(request, reply);
2945        } finally {
2946            request.recycle();
2947            reply.recycle();
2948        }
2949    }
2950
2951
2952    /**
2953     * @param reply Parcel with audio/video duration info for battery
2954                    tracking usage
2955     * @return The status code.
2956     * {@hide}
2957     */
2958    public native static int native_pullBatteryData(Parcel reply);
2959
2960    /**
2961     * Sets the target UDP re-transmit endpoint for the low level player.
2962     * Generally, the address portion of the endpoint is an IP multicast
2963     * address, although a unicast address would be equally valid.  When a valid
2964     * retransmit endpoint has been set, the media player will not decode and
2965     * render the media presentation locally.  Instead, the player will attempt
2966     * to re-multiplex its media data using the Android@Home RTP profile and
2967     * re-transmit to the target endpoint.  Receiver devices (which may be
2968     * either the same as the transmitting device or different devices) may
2969     * instantiate, prepare, and start a receiver player using a setDataSource
2970     * URL of the form...
2971     *
2972     * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
2973     *
2974     * to receive, decode and render the re-transmitted content.
2975     *
2976     * setRetransmitEndpoint may only be called before setDataSource has been
2977     * called; while the player is in the Idle state.
2978     *
2979     * @param endpoint the address and UDP port of the re-transmission target or
2980     * null if no re-transmission is to be performed.
2981     * @throws IllegalStateException if it is called in an invalid state
2982     * @throws IllegalArgumentException if the retransmit endpoint is supplied,
2983     * but invalid.
2984     *
2985     * {@hide} pending API council
2986     */
2987    public void setRetransmitEndpoint(InetSocketAddress endpoint)
2988            throws IllegalStateException, IllegalArgumentException
2989    {
2990        String addrString = null;
2991        int port = 0;
2992
2993        if (null != endpoint) {
2994            addrString = endpoint.getAddress().getHostAddress();
2995            port = endpoint.getPort();
2996        }
2997
2998        int ret = native_setRetransmitEndpoint(addrString, port);
2999        if (ret != 0) {
3000            throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
3001        }
3002    }
3003
3004    private native final int native_setRetransmitEndpoint(String addrString, int port);
3005
3006    @Override
3007    protected void finalize() {
3008        baseRelease();
3009        native_finalize();
3010    }
3011
3012    /* Do not change these values without updating their counterparts
3013     * in include/media/mediaplayer.h!
3014     */
3015    private static final int MEDIA_NOP = 0; // interface test message
3016    private static final int MEDIA_PREPARED = 1;
3017    private static final int MEDIA_PLAYBACK_COMPLETE = 2;
3018    private static final int MEDIA_BUFFERING_UPDATE = 3;
3019    private static final int MEDIA_SEEK_COMPLETE = 4;
3020    private static final int MEDIA_SET_VIDEO_SIZE = 5;
3021    private static final int MEDIA_STARTED = 6;
3022    private static final int MEDIA_PAUSED = 7;
3023    private static final int MEDIA_STOPPED = 8;
3024    private static final int MEDIA_SKIPPED = 9;
3025    private static final int MEDIA_TIMED_TEXT = 99;
3026    private static final int MEDIA_ERROR = 100;
3027    private static final int MEDIA_INFO = 200;
3028    private static final int MEDIA_SUBTITLE_DATA = 201;
3029    private static final int MEDIA_META_DATA = 202;
3030    private static final int MEDIA_DRM_INFO = 210;
3031
3032    private TimeProvider mTimeProvider;
3033
3034    /** @hide */
3035    public MediaTimeProvider getMediaTimeProvider() {
3036        if (mTimeProvider == null) {
3037            mTimeProvider = new TimeProvider(this);
3038        }
3039        return mTimeProvider;
3040    }
3041
3042    private class EventHandler extends Handler
3043    {
3044        private MediaPlayer mMediaPlayer;
3045
3046        public EventHandler(MediaPlayer mp, Looper looper) {
3047            super(looper);
3048            mMediaPlayer = mp;
3049        }
3050
3051        @Override
3052        public void handleMessage(Message msg) {
3053            if (mMediaPlayer.mNativeContext == 0) {
3054                Log.w(TAG, "mediaplayer went away with unhandled events");
3055                return;
3056            }
3057            switch(msg.what) {
3058            case MEDIA_PREPARED:
3059                try {
3060                    scanInternalSubtitleTracks();
3061                } catch (RuntimeException e) {
3062                    // send error message instead of crashing;
3063                    // send error message instead of inlining a call to onError
3064                    // to avoid code duplication.
3065                    Message msg2 = obtainMessage(
3066                            MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_UNSUPPORTED, null);
3067                    sendMessage(msg2);
3068                }
3069
3070                // MEDIA_DRM_INFO is fired (if available) before MEDIA_PREPARED.
3071                // An empty mDrmInfo indicates prepared is done but the source is not DRM protected.
3072                // Setting this before the callback so onPreparedListener can call getDrmInfo to
3073                // get the right state
3074                mDrmInfoResolved = true;
3075
3076                OnPreparedListener onPreparedListener = mOnPreparedListener;
3077                if (onPreparedListener != null)
3078                    onPreparedListener.onPrepared(mMediaPlayer);
3079                return;
3080
3081            case MEDIA_DRM_INFO:
3082                Log.v(TAG, "MEDIA_DRM_INFO " + mOnDrmInfoHandlerDelegate);
3083
3084                if (msg.obj == null) {
3085                    Log.w(TAG, "MEDIA_DRM_INFO msg.obj=NULL");
3086                } else if (msg.obj instanceof Parcel) {
3087                    Parcel parcel = (Parcel)msg.obj;
3088                    DrmInfo drmInfo = new DrmInfo(parcel);
3089
3090                    OnDrmInfoHandlerDelegate onDrmInfoHandlerDelegate;
3091                    synchronized (mDrmLock) {
3092                        mDrmInfo = drmInfo.makeCopy();
3093                        // local copy while keeping the lock
3094                        onDrmInfoHandlerDelegate = mOnDrmInfoHandlerDelegate;
3095                    }
3096
3097                    // notifying the client outside the lock
3098                    if (onDrmInfoHandlerDelegate != null) {
3099                        onDrmInfoHandlerDelegate.notifyClient(drmInfo);
3100                    }
3101                } else {
3102                    Log.w(TAG, "MEDIA_DRM_INFO msg.obj NONE; UNEXPECTED" + msg.obj);
3103                }
3104                return;
3105
3106            case MEDIA_PLAYBACK_COMPLETE:
3107                {
3108                    mOnCompletionInternalListener.onCompletion(mMediaPlayer);
3109                    OnCompletionListener onCompletionListener = mOnCompletionListener;
3110                    if (onCompletionListener != null)
3111                        onCompletionListener.onCompletion(mMediaPlayer);
3112                }
3113                stayAwake(false);
3114                return;
3115
3116            case MEDIA_STOPPED:
3117                {
3118                    TimeProvider timeProvider = mTimeProvider;
3119                    if (timeProvider != null) {
3120                        timeProvider.onStopped();
3121                    }
3122                }
3123                break;
3124
3125            case MEDIA_STARTED:
3126            case MEDIA_PAUSED:
3127                {
3128                    TimeProvider timeProvider = mTimeProvider;
3129                    if (timeProvider != null) {
3130                        timeProvider.onPaused(msg.what == MEDIA_PAUSED);
3131                    }
3132                }
3133                break;
3134
3135            case MEDIA_BUFFERING_UPDATE:
3136                OnBufferingUpdateListener onBufferingUpdateListener = mOnBufferingUpdateListener;
3137                if (onBufferingUpdateListener != null)
3138                    onBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
3139                return;
3140
3141            case MEDIA_SEEK_COMPLETE:
3142                OnSeekCompleteListener onSeekCompleteListener = mOnSeekCompleteListener;
3143                if (onSeekCompleteListener != null) {
3144                    onSeekCompleteListener.onSeekComplete(mMediaPlayer);
3145                }
3146                // fall through
3147
3148            case MEDIA_SKIPPED:
3149                {
3150                    TimeProvider timeProvider = mTimeProvider;
3151                    if (timeProvider != null) {
3152                        timeProvider.onSeekComplete(mMediaPlayer);
3153                    }
3154                }
3155                return;
3156
3157            case MEDIA_SET_VIDEO_SIZE:
3158                OnVideoSizeChangedListener onVideoSizeChangedListener = mOnVideoSizeChangedListener;
3159                if (onVideoSizeChangedListener != null) {
3160                    onVideoSizeChangedListener.onVideoSizeChanged(
3161                        mMediaPlayer, msg.arg1, msg.arg2);
3162                }
3163                return;
3164
3165            case MEDIA_ERROR:
3166                Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
3167                boolean error_was_handled = false;
3168                OnErrorListener onErrorListener = mOnErrorListener;
3169                if (onErrorListener != null) {
3170                    error_was_handled = onErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
3171                }
3172                {
3173                    mOnCompletionInternalListener.onCompletion(mMediaPlayer);
3174                    OnCompletionListener onCompletionListener = mOnCompletionListener;
3175                    if (onCompletionListener != null && ! error_was_handled) {
3176                        onCompletionListener.onCompletion(mMediaPlayer);
3177                    }
3178                }
3179                stayAwake(false);
3180                return;
3181
3182            case MEDIA_INFO:
3183                switch (msg.arg1) {
3184                case MEDIA_INFO_VIDEO_TRACK_LAGGING:
3185                    Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
3186                    break;
3187                case MEDIA_INFO_METADATA_UPDATE:
3188                    try {
3189                        scanInternalSubtitleTracks();
3190                    } catch (RuntimeException e) {
3191                        Message msg2 = obtainMessage(
3192                                MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_UNSUPPORTED, null);
3193                        sendMessage(msg2);
3194                    }
3195                    // fall through
3196
3197                case MEDIA_INFO_EXTERNAL_METADATA_UPDATE:
3198                    msg.arg1 = MEDIA_INFO_METADATA_UPDATE;
3199                    // update default track selection
3200                    if (mSubtitleController != null) {
3201                        mSubtitleController.selectDefaultTrack();
3202                    }
3203                    break;
3204                case MEDIA_INFO_BUFFERING_START:
3205                case MEDIA_INFO_BUFFERING_END:
3206                    TimeProvider timeProvider = mTimeProvider;
3207                    if (timeProvider != null) {
3208                        timeProvider.onBuffering(msg.arg1 == MEDIA_INFO_BUFFERING_START);
3209                    }
3210                    break;
3211                }
3212
3213                OnInfoListener onInfoListener = mOnInfoListener;
3214                if (onInfoListener != null) {
3215                    onInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
3216                }
3217                // No real default action so far.
3218                return;
3219            case MEDIA_TIMED_TEXT:
3220                OnTimedTextListener onTimedTextListener = mOnTimedTextListener;
3221                if (onTimedTextListener == null)
3222                    return;
3223                if (msg.obj == null) {
3224                    onTimedTextListener.onTimedText(mMediaPlayer, null);
3225                } else {
3226                    if (msg.obj instanceof Parcel) {
3227                        Parcel parcel = (Parcel)msg.obj;
3228                        TimedText text = new TimedText(parcel);
3229                        parcel.recycle();
3230                        onTimedTextListener.onTimedText(mMediaPlayer, text);
3231                    }
3232                }
3233                return;
3234
3235            case MEDIA_SUBTITLE_DATA:
3236                OnSubtitleDataListener onSubtitleDataListener = mOnSubtitleDataListener;
3237                if (onSubtitleDataListener == null) {
3238                    return;
3239                }
3240                if (msg.obj instanceof Parcel) {
3241                    Parcel parcel = (Parcel) msg.obj;
3242                    SubtitleData data = new SubtitleData(parcel);
3243                    parcel.recycle();
3244                    onSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
3245                }
3246                return;
3247
3248            case MEDIA_META_DATA:
3249                OnTimedMetaDataAvailableListener onTimedMetaDataAvailableListener =
3250                    mOnTimedMetaDataAvailableListener;
3251                if (onTimedMetaDataAvailableListener == null) {
3252                    return;
3253                }
3254                if (msg.obj instanceof Parcel) {
3255                    Parcel parcel = (Parcel) msg.obj;
3256                    TimedMetaData data = TimedMetaData.createTimedMetaDataFromParcel(parcel);
3257                    parcel.recycle();
3258                    onTimedMetaDataAvailableListener.onTimedMetaDataAvailable(mMediaPlayer, data);
3259                }
3260                return;
3261
3262            case MEDIA_NOP: // interface test message - ignore
3263                break;
3264
3265            default:
3266                Log.e(TAG, "Unknown message type " + msg.what);
3267                return;
3268            }
3269        }
3270    }
3271
3272    /*
3273     * Called from native code when an interesting event happens.  This method
3274     * just uses the EventHandler system to post the event back to the main app thread.
3275     * We use a weak reference to the original MediaPlayer object so that the native
3276     * code is safe from the object disappearing from underneath it.  (This is
3277     * the cookie passed to native_setup().)
3278     */
3279    private static void postEventFromNative(Object mediaplayer_ref,
3280                                            int what, int arg1, int arg2, Object obj)
3281    {
3282        MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
3283        if (mp == null) {
3284            return;
3285        }
3286
3287        if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
3288            // this acquires the wakelock if needed, and sets the client side state
3289            mp.start();
3290        }
3291        if (mp.mEventHandler != null) {
3292            Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
3293            mp.mEventHandler.sendMessage(m);
3294        }
3295    }
3296
3297    /**
3298     * Interface definition for a callback to be invoked when the media
3299     * source is ready for playback.
3300     */
3301    public interface OnPreparedListener
3302    {
3303        /**
3304         * Called when the media file is ready for playback.
3305         *
3306         * @param mp the MediaPlayer that is ready for playback
3307         */
3308        void onPrepared(MediaPlayer mp);
3309    }
3310
3311    /**
3312     * Register a callback to be invoked when the media source is ready
3313     * for playback.
3314     *
3315     * @param listener the callback that will be run
3316     */
3317    public void setOnPreparedListener(OnPreparedListener listener)
3318    {
3319        mOnPreparedListener = listener;
3320    }
3321
3322    private OnPreparedListener mOnPreparedListener;
3323
3324    /**
3325     * Interface definition for a callback to be invoked when playback of
3326     * a media source has completed.
3327     */
3328    public interface OnCompletionListener
3329    {
3330        /**
3331         * Called when the end of a media source is reached during playback.
3332         *
3333         * @param mp the MediaPlayer that reached the end of the file
3334         */
3335        void onCompletion(MediaPlayer mp);
3336    }
3337
3338    /**
3339     * Register a callback to be invoked when the end of a media source
3340     * has been reached during playback.
3341     *
3342     * @param listener the callback that will be run
3343     */
3344    public void setOnCompletionListener(OnCompletionListener listener)
3345    {
3346        mOnCompletionListener = listener;
3347    }
3348
3349    private OnCompletionListener mOnCompletionListener;
3350
3351    /**
3352     * @hide
3353     * Internal completion listener to update PlayerBase of the play state. Always "registered".
3354     */
3355    private final OnCompletionListener mOnCompletionInternalListener = new OnCompletionListener() {
3356        @Override
3357        public void onCompletion(MediaPlayer mp) {
3358            baseStop();
3359        }
3360    };
3361
3362    /**
3363     * Interface definition of a callback to be invoked indicating buffering
3364     * status of a media resource being streamed over the network.
3365     */
3366    public interface OnBufferingUpdateListener
3367    {
3368        /**
3369         * Called to update status in buffering a media stream received through
3370         * progressive HTTP download. The received buffering percentage
3371         * indicates how much of the content has been buffered or played.
3372         * For example a buffering update of 80 percent when half the content
3373         * has already been played indicates that the next 30 percent of the
3374         * content to play has been buffered.
3375         *
3376         * @param mp      the MediaPlayer the update pertains to
3377         * @param percent the percentage (0-100) of the content
3378         *                that has been buffered or played thus far
3379         */
3380        void onBufferingUpdate(MediaPlayer mp, int percent);
3381    }
3382
3383    /**
3384     * Register a callback to be invoked when the status of a network
3385     * stream's buffer has changed.
3386     *
3387     * @param listener the callback that will be run.
3388     */
3389    public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
3390    {
3391        mOnBufferingUpdateListener = listener;
3392    }
3393
3394    private OnBufferingUpdateListener mOnBufferingUpdateListener;
3395
3396    /**
3397     * Interface definition of a callback to be invoked indicating
3398     * the completion of a seek operation.
3399     */
3400    public interface OnSeekCompleteListener
3401    {
3402        /**
3403         * Called to indicate the completion of a seek operation.
3404         *
3405         * @param mp the MediaPlayer that issued the seek operation
3406         */
3407        public void onSeekComplete(MediaPlayer mp);
3408    }
3409
3410    /**
3411     * Register a callback to be invoked when a seek operation has been
3412     * completed.
3413     *
3414     * @param listener the callback that will be run
3415     */
3416    public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
3417    {
3418        mOnSeekCompleteListener = listener;
3419    }
3420
3421    private OnSeekCompleteListener mOnSeekCompleteListener;
3422
3423    /**
3424     * Interface definition of a callback to be invoked when the
3425     * video size is first known or updated
3426     */
3427    public interface OnVideoSizeChangedListener
3428    {
3429        /**
3430         * Called to indicate the video size
3431         *
3432         * The video size (width and height) could be 0 if there was no video,
3433         * no display surface was set, or the value was not determined yet.
3434         *
3435         * @param mp        the MediaPlayer associated with this callback
3436         * @param width     the width of the video
3437         * @param height    the height of the video
3438         */
3439        public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
3440    }
3441
3442    /**
3443     * Register a callback to be invoked when the video size is
3444     * known or updated.
3445     *
3446     * @param listener the callback that will be run
3447     */
3448    public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
3449    {
3450        mOnVideoSizeChangedListener = listener;
3451    }
3452
3453    private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
3454
3455    /**
3456     * Interface definition of a callback to be invoked when a
3457     * timed text is available for display.
3458     */
3459    public interface OnTimedTextListener
3460    {
3461        /**
3462         * Called to indicate an avaliable timed text
3463         *
3464         * @param mp             the MediaPlayer associated with this callback
3465         * @param text           the timed text sample which contains the text
3466         *                       needed to be displayed and the display format.
3467         */
3468        public void onTimedText(MediaPlayer mp, TimedText text);
3469    }
3470
3471    /**
3472     * Register a callback to be invoked when a timed text is available
3473     * for display.
3474     *
3475     * @param listener the callback that will be run
3476     */
3477    public void setOnTimedTextListener(OnTimedTextListener listener)
3478    {
3479        mOnTimedTextListener = listener;
3480    }
3481
3482    private OnTimedTextListener mOnTimedTextListener;
3483
3484    /**
3485     * Interface definition of a callback to be invoked when a
3486     * track has data available.
3487     *
3488     * @hide
3489     */
3490    public interface OnSubtitleDataListener
3491    {
3492        public void onSubtitleData(MediaPlayer mp, SubtitleData data);
3493    }
3494
3495    /**
3496     * Register a callback to be invoked when a track has data available.
3497     *
3498     * @param listener the callback that will be run
3499     *
3500     * @hide
3501     */
3502    public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
3503    {
3504        mOnSubtitleDataListener = listener;
3505    }
3506
3507    private OnSubtitleDataListener mOnSubtitleDataListener;
3508
3509    /**
3510     * Interface definition of a callback to be invoked when a
3511     * track has timed metadata available.
3512     *
3513     * @see MediaPlayer#setOnTimedMetaDataAvailableListener(OnTimedMetaDataAvailableListener)
3514     */
3515    public interface OnTimedMetaDataAvailableListener
3516    {
3517        /**
3518         * Called to indicate avaliable timed metadata
3519         * <p>
3520         * This method will be called as timed metadata is extracted from the media,
3521         * in the same order as it occurs in the media. The timing of this event is
3522         * not controlled by the associated timestamp.
3523         *
3524         * @param mp             the MediaPlayer associated with this callback
3525         * @param data           the timed metadata sample associated with this event
3526         */
3527        public void onTimedMetaDataAvailable(MediaPlayer mp, TimedMetaData data);
3528    }
3529
3530    /**
3531     * Register a callback to be invoked when a selected track has timed metadata available.
3532     * <p>
3533     * Currently only HTTP live streaming data URI's embedded with timed ID3 tags generates
3534     * {@link TimedMetaData}.
3535     *
3536     * @see MediaPlayer#selectTrack(int)
3537     * @see MediaPlayer.OnTimedMetaDataAvailableListener
3538     * @see TimedMetaData
3539     *
3540     * @param listener the callback that will be run
3541     */
3542    public void setOnTimedMetaDataAvailableListener(OnTimedMetaDataAvailableListener listener)
3543    {
3544        mOnTimedMetaDataAvailableListener = listener;
3545    }
3546
3547    private OnTimedMetaDataAvailableListener mOnTimedMetaDataAvailableListener;
3548
3549    /* Do not change these values without updating their counterparts
3550     * in include/media/mediaplayer.h!
3551     */
3552    /** Unspecified media player error.
3553     * @see android.media.MediaPlayer.OnErrorListener
3554     */
3555    public static final int MEDIA_ERROR_UNKNOWN = 1;
3556
3557    /** Media server died. In this case, the application must release the
3558     * MediaPlayer object and instantiate a new one.
3559     * @see android.media.MediaPlayer.OnErrorListener
3560     */
3561    public static final int MEDIA_ERROR_SERVER_DIED = 100;
3562
3563    /** The video is streamed and its container is not valid for progressive
3564     * playback i.e the video's index (e.g moov atom) is not at the start of the
3565     * file.
3566     * @see android.media.MediaPlayer.OnErrorListener
3567     */
3568    public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
3569
3570    /** File or network related operation errors. */
3571    public static final int MEDIA_ERROR_IO = -1004;
3572    /** Bitstream is not conforming to the related coding standard or file spec. */
3573    public static final int MEDIA_ERROR_MALFORMED = -1007;
3574    /** Bitstream is conforming to the related coding standard or file spec, but
3575     * the media framework does not support the feature. */
3576    public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
3577    /** Some operation takes too long to complete, usually more than 3-5 seconds. */
3578    public static final int MEDIA_ERROR_TIMED_OUT = -110;
3579
3580    /** Unspecified low-level system error. This value originated from UNKNOWN_ERROR in
3581     * system/core/include/utils/Errors.h
3582     * @see android.media.MediaPlayer.OnErrorListener
3583     * @hide
3584     */
3585    public static final int MEDIA_ERROR_SYSTEM = -2147483648;
3586
3587    /**
3588     * Interface definition of a callback to be invoked when there
3589     * has been an error during an asynchronous operation (other errors
3590     * will throw exceptions at method call time).
3591     */
3592    public interface OnErrorListener
3593    {
3594        /**
3595         * Called to indicate an error.
3596         *
3597         * @param mp      the MediaPlayer the error pertains to
3598         * @param what    the type of error that has occurred:
3599         * <ul>
3600         * <li>{@link #MEDIA_ERROR_UNKNOWN}
3601         * <li>{@link #MEDIA_ERROR_SERVER_DIED}
3602         * </ul>
3603         * @param extra an extra code, specific to the error. Typically
3604         * implementation dependent.
3605         * <ul>
3606         * <li>{@link #MEDIA_ERROR_IO}
3607         * <li>{@link #MEDIA_ERROR_MALFORMED}
3608         * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
3609         * <li>{@link #MEDIA_ERROR_TIMED_OUT}
3610         * <li><code>MEDIA_ERROR_SYSTEM (-2147483648)</code> - low-level system error.
3611         * </ul>
3612         * @return True if the method handled the error, false if it didn't.
3613         * Returning false, or not having an OnErrorListener at all, will
3614         * cause the OnCompletionListener to be called.
3615         */
3616        boolean onError(MediaPlayer mp, int what, int extra);
3617    }
3618
3619    /**
3620     * Register a callback to be invoked when an error has happened
3621     * during an asynchronous operation.
3622     *
3623     * @param listener the callback that will be run
3624     */
3625    public void setOnErrorListener(OnErrorListener listener)
3626    {
3627        mOnErrorListener = listener;
3628    }
3629
3630    private OnErrorListener mOnErrorListener;
3631
3632
3633    /* Do not change these values without updating their counterparts
3634     * in include/media/mediaplayer.h!
3635     */
3636    /** Unspecified media player info.
3637     * @see android.media.MediaPlayer.OnInfoListener
3638     */
3639    public static final int MEDIA_INFO_UNKNOWN = 1;
3640
3641    /** The player was started because it was used as the next player for another
3642     * player, which just completed playback.
3643     * @see android.media.MediaPlayer.OnInfoListener
3644     * @hide
3645     */
3646    public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
3647
3648    /** The player just pushed the very first video frame for rendering.
3649     * @see android.media.MediaPlayer.OnInfoListener
3650     */
3651    public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
3652
3653    /** The video is too complex for the decoder: it can't decode frames fast
3654     *  enough. Possibly only the audio plays fine at this stage.
3655     * @see android.media.MediaPlayer.OnInfoListener
3656     */
3657    public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
3658
3659    /** MediaPlayer is temporarily pausing playback internally in order to
3660     * buffer more data.
3661     * @see android.media.MediaPlayer.OnInfoListener
3662     */
3663    public static final int MEDIA_INFO_BUFFERING_START = 701;
3664
3665    /** MediaPlayer is resuming playback after filling buffers.
3666     * @see android.media.MediaPlayer.OnInfoListener
3667     */
3668    public static final int MEDIA_INFO_BUFFERING_END = 702;
3669
3670    /** Estimated network bandwidth information (kbps) is available; currently this event fires
3671     * simultaneously as {@link #MEDIA_INFO_BUFFERING_START} and {@link #MEDIA_INFO_BUFFERING_END}
3672     * when playing network files.
3673     * @see android.media.MediaPlayer.OnInfoListener
3674     * @hide
3675     */
3676    public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703;
3677
3678    /** Bad interleaving means that a media has been improperly interleaved or
3679     * not interleaved at all, e.g has all the video samples first then all the
3680     * audio ones. Video is playing but a lot of disk seeks may be happening.
3681     * @see android.media.MediaPlayer.OnInfoListener
3682     */
3683    public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
3684
3685    /** The media cannot be seeked (e.g live stream)
3686     * @see android.media.MediaPlayer.OnInfoListener
3687     */
3688    public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
3689
3690    /** A new set of metadata is available.
3691     * @see android.media.MediaPlayer.OnInfoListener
3692     */
3693    public static final int MEDIA_INFO_METADATA_UPDATE = 802;
3694
3695    /** A new set of external-only metadata is available.  Used by
3696     *  JAVA framework to avoid triggering track scanning.
3697     * @hide
3698     */
3699    public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
3700
3701    /** Failed to handle timed text track properly.
3702     * @see android.media.MediaPlayer.OnInfoListener
3703     *
3704     * {@hide}
3705     */
3706    public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
3707
3708    /** Subtitle track was not supported by the media framework.
3709     * @see android.media.MediaPlayer.OnInfoListener
3710     */
3711    public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
3712
3713    /** Reading the subtitle track takes too long.
3714     * @see android.media.MediaPlayer.OnInfoListener
3715     */
3716    public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
3717
3718    /**
3719     * Interface definition of a callback to be invoked to communicate some
3720     * info and/or warning about the media or its playback.
3721     */
3722    public interface OnInfoListener
3723    {
3724        /**
3725         * Called to indicate an info or a warning.
3726         *
3727         * @param mp      the MediaPlayer the info pertains to.
3728         * @param what    the type of info or warning.
3729         * <ul>
3730         * <li>{@link #MEDIA_INFO_UNKNOWN}
3731         * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
3732         * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
3733         * <li>{@link #MEDIA_INFO_BUFFERING_START}
3734         * <li>{@link #MEDIA_INFO_BUFFERING_END}
3735         * <li><code>MEDIA_INFO_NETWORK_BANDWIDTH (703)</code> -
3736         *     bandwidth information is available (as <code>extra</code> kbps)
3737         * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
3738         * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
3739         * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
3740         * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE}
3741         * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT}
3742         * </ul>
3743         * @param extra an extra code, specific to the info. Typically
3744         * implementation dependent.
3745         * @return True if the method handled the info, false if it didn't.
3746         * Returning false, or not having an OnInfoListener at all, will
3747         * cause the info to be discarded.
3748         */
3749        boolean onInfo(MediaPlayer mp, int what, int extra);
3750    }
3751
3752    /**
3753     * Register a callback to be invoked when an info/warning is available.
3754     *
3755     * @param listener the callback that will be run
3756     */
3757    public void setOnInfoListener(OnInfoListener listener)
3758    {
3759        mOnInfoListener = listener;
3760    }
3761
3762    private OnInfoListener mOnInfoListener;
3763
3764    // Modular DRM begin
3765
3766    /**
3767     * Interface definition of a callback to be invoked when the app
3768     * can do DRM configuration (get/set properties) before the session
3769     * is opened. This facilitates configuration of the properties, like
3770     * 'securityLevel', which has to be set after DRM scheme creation but
3771     * before the DRM session is opened.
3772     *
3773     * The only allowed DRM calls in this listener are getDrmPropertyString
3774     * and setDrmPropertyString.
3775     *
3776     */
3777    public static abstract class OnDrmConfigCallback
3778    {
3779        /**
3780         * Called to give the app the opportunity to configure DRM before the session is created
3781         *
3782         * @param mp the {@code MediaPlayer} associated with this callback
3783         */
3784        public void onDrmConfig(MediaPlayer mp) {}
3785    }
3786
3787    /**
3788     * Interface definition of a callback to be invoked when the
3789     * DRM info becomes available
3790     */
3791    public interface OnDrmInfoListener
3792    {
3793        /**
3794         * Called to indicate DRM info is available
3795         *
3796         * @param mp the {@code MediaPlayer} associated with this callback
3797         * @param drmInfo DRM info of the source including PSSH, mimes, and subset
3798         *                of crypto schemes supported by this device
3799         */
3800        public void onDrmInfo(MediaPlayer mp, DrmInfo drmInfo);
3801    }
3802
3803    /**
3804     * Register a callback to be invoked when the DRM info is
3805     * known.
3806     *
3807     * @param listener the callback that will be run
3808     */
3809    public void setOnDrmInfoListener(OnDrmInfoListener listener)
3810    {
3811        setOnDrmInfoListener(listener, null);
3812    }
3813
3814    /**
3815     * Register a callback to be invoked when the DRM info is
3816     * known.
3817     *
3818     * @param listener the callback that will be run
3819     */
3820    public void setOnDrmInfoListener(OnDrmInfoListener listener, Handler handler)
3821    {
3822        synchronized (mDrmLock) {
3823            if (listener != null) {
3824                mOnDrmInfoHandlerDelegate = new OnDrmInfoHandlerDelegate(this, listener, handler);
3825            } else {
3826                mOnDrmInfoHandlerDelegate = null;
3827            }
3828        } // synchronized
3829    }
3830
3831    private OnDrmInfoHandlerDelegate mOnDrmInfoHandlerDelegate;
3832
3833    /**
3834     * Interface definition of a callback to notify the app when the
3835     * DRM is ready for key request/response
3836     */
3837    public interface OnDrmPreparedListener
3838    {
3839        /**
3840         * Called to notify the app that prepareDrm is finished and ready for key request/response
3841         *
3842         * @param mp the {@code MediaPlayer} associated with this callback
3843         * @param success the result of DRM preparation
3844         */
3845        public void onDrmPrepared(MediaPlayer mp, boolean success);
3846    }
3847
3848    /**
3849     * Register a callback to be invoked when the DRM object is prepared.
3850     *
3851     * @param listener the callback that will be run
3852     */
3853    public void setOnDrmPreparedListener(OnDrmPreparedListener listener)
3854    {
3855        setOnDrmPreparedListener(listener, null);
3856    }
3857
3858    /**
3859     * Register a callback to be invoked when the DRM object is prepared.
3860     *
3861     * @param listener the callback that will be run
3862     * @param handler the Handler that will receive the callback
3863     */
3864    public void setOnDrmPreparedListener(OnDrmPreparedListener listener, Handler handler)
3865    {
3866        synchronized (mDrmLock) {
3867            if (listener != null) {
3868                mOnDrmPreparedHandlerDelegate = new OnDrmPreparedHandlerDelegate(this,
3869                                                            listener, handler);
3870            } else {
3871                mOnDrmPreparedHandlerDelegate = null;
3872            }
3873        } // synchronized
3874    }
3875
3876    private OnDrmPreparedHandlerDelegate mOnDrmPreparedHandlerDelegate;
3877
3878
3879    private class OnDrmInfoHandlerDelegate {
3880        private MediaPlayer mMediaPlayer;
3881        private OnDrmInfoListener mOnDrmInfoListener;
3882        private Handler mHandler;
3883
3884        OnDrmInfoHandlerDelegate(MediaPlayer mp, OnDrmInfoListener listener, Handler handler) {
3885            mMediaPlayer = mp;
3886            mOnDrmInfoListener = listener;
3887
3888            // find the looper for our new event handler
3889            Looper looper = null;
3890            if (handler != null) {
3891                looper = handler.getLooper();
3892            }
3893
3894            // construct the event handler with this looper
3895            if (looper != null) {
3896                // implement the event handler delegate
3897                mHandler = new Handler(looper) {
3898                    public void handleMessage(Message msg) {
3899                        DrmInfo drmInfo = (DrmInfo)msg.obj;
3900                        mOnDrmInfoListener.onDrmInfo(mMediaPlayer, drmInfo);
3901                    }
3902                };
3903            }
3904        }
3905
3906        void notifyClient(DrmInfo drmInfo) {
3907            if ( mHandler != null ) {
3908                Message msg = new Message();  // no message type needed
3909                msg.obj = drmInfo;
3910                mHandler.sendMessage(msg);
3911            }
3912            else {  // no handler: direct call
3913                mOnDrmInfoListener.onDrmInfo(mMediaPlayer, drmInfo);
3914            }
3915        }
3916    }
3917
3918    private class OnDrmPreparedHandlerDelegate {
3919        private MediaPlayer mMediaPlayer;
3920        private OnDrmPreparedListener mOnDrmPreparedListener;
3921        private Handler mHandler;
3922
3923        OnDrmPreparedHandlerDelegate(MediaPlayer mp, OnDrmPreparedListener listener,
3924                Handler handler) {
3925            mMediaPlayer = mp;
3926            mOnDrmPreparedListener = listener;
3927
3928            // find the looper for our new event handler
3929            Looper looper = null;
3930            if (handler != null) {
3931                looper = handler.getLooper();
3932            }
3933
3934            // construct the event handler with this looper
3935            if (looper != null) {
3936                // implement the event handler delegate
3937                mHandler = new Handler(looper) {
3938                    public void handleMessage(Message msg) {
3939                        boolean success = (msg.arg1 == 0) ? false : true;
3940                        mOnDrmPreparedListener.onDrmPrepared(mMediaPlayer, success);
3941                    }
3942                };
3943            }
3944        }
3945
3946        void notifyClient(boolean success) {
3947            if ( mHandler != null ) {
3948                Message msg = new Message();  // no message type needed
3949                msg.arg1 = success ? 1 : 0;
3950                mHandler.sendMessage(msg);
3951            }
3952            else {  // no handler: direct call
3953                mOnDrmPreparedListener.onDrmPrepared(mMediaPlayer, success);
3954            }
3955        }
3956    }
3957
3958    /**
3959     * Retrieves the DRM Info associated with the current source
3960     *
3961     * @throws IllegalStateException if called before prepare()
3962     */
3963    public DrmInfo getDrmInfo()
3964    {
3965        DrmInfo drmInfo = null;
3966
3967        // there is not much point if the app calls getDrmInfo within an OnDrmInfoListenet;
3968        // regardless below returns drmInfo anyway instead of raising an exception
3969        synchronized (mDrmLock) {
3970            if (!mDrmInfoResolved && mDrmInfo == null) {
3971                final String msg = "The Player has not been prepared yet";
3972                Log.v(TAG, msg);
3973                throw new IllegalStateException(msg);
3974            }
3975
3976            if (mDrmInfo != null) {
3977                drmInfo = mDrmInfo.makeCopy();
3978            }
3979        }   // synchronized
3980
3981        return drmInfo;
3982    }
3983
3984    private native void _prepareDrm(@NonNull byte[] uuid, int mode)
3985            throws UnsupportedSchemeException, ResourceBusyException, NotProvisionedException;
3986
3987    /**
3988     * Prepares the DRM for the current source
3989     * <p>
3990     * If {@code OnDrmConfigCallback} is registered, it will be called half-way into
3991     * preparation to allow configuration of the DRM properties before opening the
3992     * DRM session. Note that the callback is called synchronously in the thread that called
3993     * {@code prepareDrm}. It should be used only for a series of {@code getDrmPropertyString}
3994     * and {@code setDrmPropertyString} calls and refrain from any lengthy operation.
3995     * <p>
3996     * If the device has not been provisioned before, this call also provisions the device
3997     * which involves accessing the provisioning server and can take a variable time to
3998     * complete depending on the network connectivity.
3999     * If OnDrmPreparedListener is registered, prepareDrm() runs in non-blocking
4000     * mode by launching the provisioning in the background and returning. The listener
4001     * will be called when provisioning and preperation has finished. If a
4002     * OnDrmPreparedListener is not registered, prepareDrm() waits till provisioning
4003     * and preperation has finished, i.e., runs in blocking mode.
4004     * <p>
4005     * If OnDrmPreparedListener is registered, it is called to indicated the DRM session
4006     * being ready regardless of blocking or non-blocking mode. The application should
4007     * not make any assumption about its call sequence (e.g., before or after prepareDrm
4008     * returns) or the thread context that will execute the listener.
4009     * <p>
4010     *
4011     * @param uuid The UUID of the crypto scheme.
4012     *
4013     * @throws IllegalStateException       if called before prepare(), or there exists a Drm already
4014     * @throws UnsupportedSchemeException  if the crypto scheme is not supported
4015     * @throws ResourceBusyException       if required DRM resources are in use
4016     * @throws ProvisioningErrorException  if provisioning is required but an attempt failed
4017     */
4018    public void prepareDrm(@NonNull UUID uuid, OnDrmConfigCallback configCallback)
4019            throws UnsupportedSchemeException,
4020                   ResourceBusyException, ProvisioningErrorException
4021    {
4022        boolean allDoneWithoutProvisioning = false;
4023        // get a snapshot as we'll use them outside the lock
4024        OnDrmPreparedHandlerDelegate onDrmPreparedHandlerDelegate = null;
4025
4026        synchronized (mDrmLock) {
4027
4028            // only allowing if tied to a protected source; might releax for releasing offline keys
4029            if (mDrmInfo == null) {
4030                final String msg = String.format("prepareDrm(%s): Wrong usage: " +
4031                                                 "The player must be prepared and DRM " +
4032                                                 "info be retrieved before this call.", uuid);
4033                Log.e(TAG, msg);
4034                throw new IllegalStateException(msg);
4035            }
4036
4037            if (mActiveDrmScheme) {
4038                final String msg = String.format("prepareDrm(%s): Wrong usage: There is already " +
4039                                                 "an active DRM scheme with %s.", uuid, mDrmUUID);
4040                Log.e(TAG, msg);
4041                throw new IllegalStateException(msg);
4042            }
4043
4044            if (mPrepareDrmInProgress) {
4045                final String msg = String.format("prepareDrm(%s): Wrong usage: There is already " +
4046                                                 "a pending prepareDrm call.", uuid);
4047                Log.e(TAG, msg);
4048                throw new IllegalStateException(msg);
4049            }
4050
4051            if (mDrmProvisioningInProgress) {
4052                final String msg = String.format("prepareDrm(%s): Unexpectd: Provisioning is " +
4053                                                 "already in progress.", uuid);
4054                Log.e(TAG, msg);
4055                throw new IllegalStateException(msg);
4056            }
4057
4058            mPrepareDrmInProgress = true;
4059            // local copy while the lock is held
4060            onDrmPreparedHandlerDelegate = mOnDrmPreparedHandlerDelegate;
4061
4062            if (configCallback != null) {
4063                try {
4064                    boolean allowOpenSession = false;   // just pre-openSession
4065                    _prepareDrm(getByteArrayFromUUID(uuid), allowOpenSession ? 1 : 0);
4066                } catch (IllegalStateException e) {
4067                    final String msg = String.format("prepareDrm(): Wrong usage: The player must " +
4068                                                     "be in prepared state to call prepareDrm().");
4069                    Log.e(TAG, msg);
4070                    throw new IllegalStateException(msg);
4071                } catch (NotProvisionedException e) {   // the pre-config step won't raise this
4072                    final String msg = String.format("prepareDrm: Unexpected " +
4073                                                     "NotProvisionedException here.");
4074                    Log.e(TAG, msg);
4075                    throw new ProvisioningErrorException(msg);
4076                } catch (Exception e) {
4077                    Log.w(TAG, String.format("prepareDrm: Exception %s", e));
4078                    throw e;
4079                } finally {
4080                    mPrepareDrmInProgress = false;
4081                }
4082            }
4083
4084            mDrmConfigAllowed = true;
4085        }   // synchronized
4086
4087
4088        // call the callback outside the lock
4089        if (configCallback != null)  {
4090            configCallback.onDrmConfig(this);
4091        }
4092
4093        synchronized (mDrmLock) {
4094            mDrmConfigAllowed = false;
4095
4096            try {
4097                boolean allowOpenSession = true;    // all in
4098                _prepareDrm(getByteArrayFromUUID(uuid), allowOpenSession ? 1 : 0);
4099
4100                mDrmUUID = uuid;
4101                mActiveDrmScheme = true;
4102
4103                mPrepareDrmInProgress = false;
4104
4105                allDoneWithoutProvisioning = true;
4106            } catch (IllegalStateException e) {
4107                final String msg = String.format("prepareDrm(%s): Wrong usage: The player must be" +
4108                                                 " in prepared state to call prepareDrm().", uuid);
4109                Log.e(TAG, msg);
4110                throw new IllegalStateException(msg);
4111            } catch (NotProvisionedException e) {
4112                Log.w(TAG, String.format("prepareDrm: NotProvisionedException"));
4113
4114                // handle provisioning internally
4115                boolean result = HandleProvisioninig(uuid);
4116
4117                // if blocking mode, we're already done;
4118                // if non-blocking mode, we attempted to launch background provisioning
4119                if (result == false) {
4120                    final String msg =
4121                                String.format("prepareDrm: Provisioning was required but failed.");
4122                    Log.e(TAG, msg);
4123                    throw new ProvisioningErrorException(msg);
4124                }
4125
4126                // nothing else to do;
4127                // if blocking or non-blocking, HandleProvisioninig does the re-attempt & cleanup
4128            } catch (Exception e) {
4129                Log.w(TAG, String.format("prepareDrm: Exception %s", e));
4130                throw e;
4131            } finally {
4132                mPrepareDrmInProgress = false;
4133            }
4134        }   // synchronized
4135
4136
4137        // if finished successfully without provisioning, call the callback outside the lock
4138        if (allDoneWithoutProvisioning) {
4139            if (onDrmPreparedHandlerDelegate != null)
4140                onDrmPreparedHandlerDelegate.notifyClient(true /*success*/);
4141        }
4142
4143    }
4144
4145
4146    private native void _releaseDrm();
4147
4148    /**
4149     * Releases the DRM session
4150     *
4151     * @throws NoDrmSchemeException if there is no active DRM session to release
4152     */
4153    public void releaseDrm()
4154            throws NoDrmSchemeException
4155    {
4156        synchronized (mDrmLock) {
4157            if (!mActiveDrmScheme) {
4158                Log.e(TAG, String.format("releaseDrm(%s): No active DRM scheme to release."));
4159                throw new NoDrmSchemeException("releaseDrm: No active DRM scheme to release.");
4160            } else {
4161                _releaseDrm();
4162
4163                mActiveDrmScheme = false;
4164            }
4165        }   // synchronized
4166    }
4167
4168
4169    @NonNull
4170    private native MediaDrm.KeyRequest _getKeyRequest(@NonNull byte[] scope,
4171            @Nullable String mimeType, @MediaDrm.KeyType int keyType,
4172            @Nullable Map<String, String> optionalParameters)
4173            throws NotProvisionedException;
4174
4175    /**
4176     * A key request/response exchange occurs between the app and a license server
4177     * to obtain or release keys used to decrypt encrypted content.
4178     * <p>
4179     * getKeyRequest() is used to obtain an opaque key request byte array that is
4180     * delivered to the license server.  The opaque key request byte array is returned
4181     * in KeyRequest.data.  The recommended URL to deliver the key request to is
4182     * returned in KeyRequest.defaultUrl.
4183     * <p>
4184     * After the app has received the key request response from the server,
4185     * it should deliver to the response to the DRM engine plugin using the method
4186     * {@link #provideKeyResponse}.
4187     *
4188     * @param scope may be a container-specific initialization data or a keySetId,
4189     * depending on the specified keyType.
4190     * When the keyType is KEY_TYPE_STREAMING or KEY_TYPE_OFFLINE, scope should be set to
4191     * the container-specific initialization data. Its meaning is interpreted based on the
4192     * mime type provided in the mimeType parameter.  It could contain, for example,
4193     * the content ID, key ID or other data obtained from the content metadata that is
4194     * required in generating the key request.
4195     * When the keyType is KEY_TYPE_RELEASE, scope should be set to the keySetId of
4196     * the keys being released.
4197     *
4198     * @param mimeType identifies the mime type of the content
4199     *
4200     * @param keyType specifes the type of the request. The request may be to acquire
4201     * keys for streaming or offline content, or to release previously acquired
4202     * keys, which are identified by a keySetId.
4203     *
4204     * @param optionalParameters are included in the key request message to
4205     * allow a client application to provide additional message parameters to the server.
4206     * This may be {@code null} if no additional parameters are to be sent.
4207     *
4208     * @throws NoDrmSchemeException if there is no active DRM session
4209     */
4210    @NonNull
4211    public MediaDrm.KeyRequest getKeyRequest(@NonNull byte[] scope, @Nullable String mimeType,
4212            @MediaDrm.KeyType int keyType, @Nullable Map<String, String> optionalParameters)
4213            throws NoDrmSchemeException
4214    {
4215        synchronized (mDrmLock) {
4216            if (!mActiveDrmScheme) {
4217                Log.e(TAG, String.format("getKeyRequest NoDrmSchemeException"));
4218                throw new NoDrmSchemeException("getKeyRequest: Has to set a DRM scheme first.");
4219            }
4220
4221            try {
4222                return _getKeyRequest(scope, mimeType, keyType, optionalParameters);
4223            } catch (NotProvisionedException e) {
4224                Log.w(TAG, String.format("getKeyRequest NotProvisionedException: " +
4225                                         "Unexpected. Shouldn't have reached here."));
4226                throw new IllegalStateException("getKeyRequest: Unexpected provisioning error.");
4227            } catch (Exception e) {
4228                Log.w(TAG, String.format("getKeyRequest Exception %s", e));
4229                throw e;
4230            }
4231
4232        }   // synchronized
4233    }
4234
4235
4236    @Nullable
4237    private native byte[] _provideKeyResponse(@Nullable byte[] keySetId, @NonNull byte[] response)
4238            throws DeniedByServerException;
4239
4240    /**
4241     * A key response is received from the license server by the app, then it is
4242     * provided to the DRM engine plugin using provideKeyResponse. When the
4243     * response is for an offline key request, a key-set identifier is returned that
4244     * can be used to later restore the keys to a new session with the method
4245     * {@ link # restoreKeys}.
4246     * When the response is for a streaming or release request, null is returned.
4247     *
4248     * @param keySetId When the response is for a release request, keySetId identifies
4249     * the saved key associated with the release request (i.e., the same keySetId
4250     * passed to the earlier {@ link # getKeyRequest} call. It MUST be null when the
4251     * response is for either streaming or offline key requests.
4252     *
4253     * @param response the byte array response from the server
4254     *
4255     * @throws NoDrmSchemeException if there is no active DRM session
4256     * @throws DeniedByServerException if the response indicates that the
4257     * server rejected the request
4258     */
4259    public byte[] provideKeyResponse(@Nullable byte[] keySetId, @NonNull byte[] response)
4260            throws NoDrmSchemeException, DeniedByServerException
4261    {
4262        synchronized (mDrmLock) {
4263
4264            if (!mActiveDrmScheme) {
4265                Log.e(TAG, String.format("getKeyRequest NoDrmSchemeException"));
4266                throw new NoDrmSchemeException("getKeyRequest: Has to set a DRM scheme first.");
4267            }
4268
4269            try {
4270                return _provideKeyResponse(keySetId, response);
4271            } catch (Exception e) {
4272                Log.w(TAG, String.format("provideKeyResponse Exception %s", e));
4273                throw e;
4274            }
4275        }   // synchronized
4276    }
4277
4278
4279    private native void _restoreKeys(@NonNull byte[] keySetId);
4280
4281    /**
4282     * Restore persisted offline keys into a new session.  keySetId identifies the
4283     * keys to load, obtained from a prior call to {@link #provideKeyResponse}.
4284     *
4285     * @param keySetId identifies the saved key set to restore
4286     */
4287    public void restoreKeys(@NonNull byte[] keySetId)
4288            throws NoDrmSchemeException
4289    {
4290        synchronized (mDrmLock) {
4291
4292            if (!mActiveDrmScheme) {
4293                Log.w(TAG, String.format("restoreKeys NoDrmSchemeException"));
4294                throw new NoDrmSchemeException("restoreKeys: Has to set a DRM scheme first.");
4295            }
4296
4297            try {
4298                _restoreKeys(keySetId);
4299            } catch (Exception e) {
4300                Log.w(TAG, String.format("restoreKeys Exception %s", e));
4301                throw e;
4302            }
4303
4304        }   // synchronized
4305    }
4306
4307
4308    @NonNull
4309    private native String _getDrmPropertyString(@NonNull String propertyName);
4310
4311    /**
4312     * Read a DRM engine plugin String property value, given the property name string.
4313     * <p>
4314     * @param propertyName the property name
4315     *
4316     * Standard fields names are:
4317     * {link #PROPERTY_VENDOR}, {link #PROPERTY_VERSION},
4318     * {link #PROPERTY_DESCRIPTION}, {link #PROPERTY_ALGORITHMS}
4319     */
4320    @NonNull
4321    public String getDrmPropertyString(@NonNull @MediaDrm.StringProperty String propertyName)
4322            throws NoDrmSchemeException
4323    {
4324        String value;
4325        synchronized (mDrmLock) {
4326
4327            if (!mActiveDrmScheme && !mDrmConfigAllowed) {
4328                Log.w(TAG, String.format("getDrmPropertyString NoDrmSchemeException"));
4329                throw new NoDrmSchemeException("getDrmPropertyString: Has to prepareDrm() first.");
4330            }
4331
4332            try {
4333                value = _getDrmPropertyString(propertyName);
4334            } catch (Exception e) {
4335                Log.w(TAG, String.format("getDrmPropertyString Exception %s", e));
4336                throw e;
4337            }
4338        }   // synchronized
4339
4340        return value;
4341    }
4342
4343    private native void _setDrmPropertyString(@NonNull String propertyName, @NonNull String value);
4344
4345    /**
4346     * Set a DRM engine plugin String property value.
4347     * <p>
4348     * @param propertyName the property name
4349     * @param value the property value
4350     *
4351     * Standard fields names are:
4352     * {link #PROPERTY_VENDOR}, {link #PROPERTY_VERSION},
4353     * {link #PROPERTY_DESCRIPTION}, {link #PROPERTY_ALGORITHMS}
4354     */
4355    public void setDrmPropertyString(@NonNull @MediaDrm.StringProperty String propertyName,
4356                                     @NonNull String value)
4357            throws NoDrmSchemeException
4358    {
4359        synchronized (mDrmLock) {
4360
4361            if ( !mActiveDrmScheme && !mDrmConfigAllowed ) {
4362                Log.w(TAG, String.format("setDrmPropertyString NoDrmSchemeException"));
4363                throw new NoDrmSchemeException("setDrmPropertyString: Has to prepareDrm() first.");
4364            }
4365
4366            try {
4367                _setDrmPropertyString(propertyName, value);
4368            } catch ( Exception e ) {
4369                Log.w(TAG, String.format("setDrmPropertyString Exception %s", e));
4370                throw e;
4371            }
4372        }   // synchronized
4373    }
4374
4375    public static final class DrmInfo {
4376        private Map<UUID, byte[]> mapPssh;
4377        private UUID[] supportedSchemes;
4378        // TODO: Won't need this in final release. Only keeping it for the existing test app.
4379        private String[] mimes;
4380
4381        public Map<UUID, byte[]> getPssh() {
4382            return mapPssh;
4383        }
4384        public UUID[] getSupportedSchemes() {
4385            return supportedSchemes;
4386        }
4387        // TODO: Won't need this in final release. Only keeping it for the existing test app.
4388        public String[] getMimes() {
4389            return mimes;
4390        }
4391
4392        private DrmInfo(Map<UUID, byte[]> Pssh, UUID[] SupportedSchemes, String[] Mimes) {
4393            mapPssh = Pssh;
4394            supportedSchemes = SupportedSchemes;
4395            mimes = Mimes;
4396        }
4397
4398        private DrmInfo(Parcel parcel) {
4399            Log.v(TAG, "DrmInfo(" + parcel + ") size " + parcel.dataSize());
4400
4401            int psshsize = parcel.readInt();
4402            byte[] pssh = new byte[psshsize];
4403            parcel.readByteArray(pssh);
4404
4405            Log.v(TAG, "DrmInfo() PSSH: " + arrToHex(pssh));
4406            mapPssh = parsePSSH(pssh, psshsize);
4407            Log.v(TAG, "DrmInfo() PSSH: " + mapPssh);
4408
4409            int supportedDRMsCount = parcel.readInt();
4410            supportedSchemes = new UUID[supportedDRMsCount];
4411            for (int i = 0; i < supportedDRMsCount; i++) {
4412                byte[] uuid = new byte[16];
4413                parcel.readByteArray(uuid);
4414
4415                supportedSchemes[i] = bytesToUUID(uuid);
4416
4417                Log.v(TAG, "DrmInfo() supportedScheme[" + i + "]: " +
4418                      supportedSchemes[i]);
4419            }
4420
4421            // TODO: Won't need this in final release. Only keeping it for the test app.
4422            mimes = parcel.readStringArray();
4423            int mimeCount = mimes.length;
4424            Log.v(TAG, "DrmInfo() mime: " + Arrays.toString(mimes));
4425
4426            Log.v(TAG, "DrmInfo() Parcel psshsize: " + psshsize +
4427                  " supportedDRMsCount: " + supportedDRMsCount +
4428                  " mimeCount: " + mimeCount);
4429        }
4430
4431        private DrmInfo makeCopy() {
4432            return new DrmInfo(this.mapPssh, this.supportedSchemes, this.mimes);
4433        }
4434
4435        private String arrToHex(byte[] bytes) {
4436            String out = "0x";
4437            for (int i = 0; i < bytes.length; i++) {
4438                out += String.format("%02x", bytes[i]);
4439            }
4440
4441            return out;
4442        }
4443
4444        private UUID bytesToUUID(byte[] uuid) {
4445            long msb = 0, lsb = 0;
4446            for (int i = 0; i < 8; i++) {
4447                msb |= ( ((long)uuid[i]   & 0xff) << (8 * (7 - i)) );
4448                lsb |= ( ((long)uuid[i+8] & 0xff) << (8 * (7 - i)) );
4449            }
4450
4451            return new UUID(msb, lsb);
4452        }
4453
4454        private Map<UUID, byte[]> parsePSSH(byte[] pssh, int psshsize) {
4455            Map<UUID, byte[]> result = new HashMap<UUID, byte[]>();
4456
4457            final int UUID_SIZE = 16;
4458            final int DATALEN_SIZE = 4;
4459
4460            int len = psshsize;
4461            int numentries = 0;
4462            int i = 0;
4463
4464            while (len > 0) {
4465                if (len < UUID_SIZE) {
4466                    Log.w(TAG, String.format("parsePSSH: len is too short to parse " +
4467                                             "UUID: (%d < 16) pssh: %d", len, psshsize));
4468                    return null;
4469                }
4470
4471                byte[] subset = Arrays.copyOfRange(pssh, i, i + UUID_SIZE);
4472                UUID uuid = bytesToUUID(subset);
4473                i += UUID_SIZE;
4474                len -= UUID_SIZE;
4475
4476                // get data length
4477                if (len < 4) {
4478                    Log.w(TAG, String.format("parsePSSH: len is too short to parse " +
4479                                             "datalen: (%d < 4) pssh: %d", len, psshsize));
4480                    return null;
4481                }
4482
4483                subset = Arrays.copyOfRange(pssh, i, i+DATALEN_SIZE);
4484                int datalen = (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) ?
4485                    ((subset[3] & 0xff) << 24) | ((subset[2] & 0xff) << 16) |
4486                    ((subset[1] & 0xff) <<  8) |  (subset[0] & 0xff)          :
4487                    ((subset[0] & 0xff) << 24) | ((subset[1] & 0xff) << 16) |
4488                    ((subset[2] & 0xff) <<  8) |  (subset[3] & 0xff) ;
4489                i += DATALEN_SIZE;
4490                len -= DATALEN_SIZE;
4491
4492                if (len < datalen) {
4493                    Log.w(TAG, String.format("parsePSSH: len is too short to parse " +
4494                                             "data: (%d < %d) pssh: %d", len, datalen, psshsize));
4495                    return null;
4496                }
4497
4498                byte[] data = Arrays.copyOfRange(pssh, i, i+datalen);
4499
4500                // skip the data
4501                i += datalen;
4502                len -= datalen;
4503
4504                Log.v(TAG, String.format("parsePSSH[%d]: <%s, %s> pssh: %d",
4505                                         numentries, uuid, arrToHex(data), psshsize));
4506                numentries++;
4507                result.put(uuid, data);
4508            }
4509
4510            return result;
4511        }
4512
4513    };  // DrmInfo
4514
4515    /**
4516     * Thrown when a DRM method is called before preparing a DRM scheme through prepareDrm().
4517     * Extends MediaDrm.MediaDrmException
4518     */
4519    public static final class NoDrmSchemeException extends MediaDrmException {
4520        public NoDrmSchemeException(String detailMessage) {
4521            super(detailMessage);
4522        }
4523    }
4524
4525    /**
4526     * Thrown when the device requires DRM provisioning but the provisioning attempt has
4527     * failed (for example: network timeout, provisioning server error).
4528     * Extends MediaDrm.MediaDrmException
4529     */
4530    public static final class ProvisioningErrorException extends MediaDrmException {
4531        public ProvisioningErrorException(String detailMessage) {
4532            super(detailMessage);
4533        }
4534    }
4535
4536        // Modular DRM helpers
4537
4538    private class ProvisioningThread extends Thread
4539    {
4540        public static final int TIMEOUT_MS = 60000;
4541
4542        private UUID uuid;
4543        private String urlStr;
4544        private byte[] response;
4545        private Object drmLock;
4546        private OnDrmPreparedHandlerDelegate onDrmPreparedHandlerDelegate;
4547        private MediaPlayer mediaPlayer;
4548        private boolean succeeded;
4549        private boolean finished;
4550        public  boolean succeeded() {
4551            return succeeded;
4552        }
4553
4554        public ProvisioningThread initialize(MediaDrm.ProvisionRequest request,
4555                                          UUID uuid, MediaPlayer mediaPlayer) {
4556            // lock is held by the caller
4557            drmLock = mediaPlayer.mDrmLock;
4558            onDrmPreparedHandlerDelegate = mediaPlayer.mOnDrmPreparedHandlerDelegate;
4559            this.mediaPlayer = mediaPlayer;
4560
4561            urlStr = request.getDefaultUrl() + "&signedRequest=" + new String(request.getData());
4562            this.uuid = uuid;
4563
4564            Log.v(TAG, String.format("HandleProvisioninig: Thread is initialised url: %s", urlStr));
4565            return this;
4566        }
4567
4568        public void run() {
4569
4570            boolean provisioningSucceeded = false;
4571            try {
4572                URL url = new URL(urlStr);
4573                final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
4574                try {
4575                    connection.setRequestMethod("POST");
4576                    connection.setDoOutput(false);
4577                    connection.setDoInput(true);
4578                    connection.setConnectTimeout(TIMEOUT_MS);
4579                    connection.setReadTimeout(TIMEOUT_MS);
4580
4581                    connection.connect();
4582                    response = Streams.readFully(connection.getInputStream());
4583
4584                    Log.v(TAG, String.format("HandleProvisioninig: Thread run response %d %s",
4585                                             response.length, response));
4586                } catch (Exception e) {
4587                    Log.w(TAG, String.format("HandleProvisioninig: Thread run connect %s url: %s",
4588                                             e, url));
4589                } finally {
4590                    connection.disconnect();
4591                }
4592            } catch (Exception e)   {
4593                Log.w(TAG, String.format("HandleProvisioninig: Thread run openConnection %s", e));
4594            }
4595
4596            if (response != null) {
4597                try {
4598                    MediaDrm drm = new MediaDrm(uuid);
4599                    drm.provideProvisionResponse(response);
4600                    drm.release();
4601                    Log.v(TAG, String.format("HandleProvisioninig: Thread run " +
4602                                             "newDrm+provideProvisionResponse SUCCEEDED!"));
4603
4604                    provisioningSucceeded = true;
4605                } catch (Exception e)   {
4606                    Log.w(TAG, String.format("HandleProvisioninig: Thread run " +
4607                                             "newDrm+provideProvisionResponse %s", e));
4608                }
4609            }
4610
4611            // non-blocking mode needs the lock
4612            if (onDrmPreparedHandlerDelegate != null) {
4613
4614                synchronized (drmLock) {
4615                    // continuing with prepareDrm
4616                    if (provisioningSucceeded) {
4617                        succeeded = mediaPlayer.resumePrepareDrm(uuid);
4618                    }
4619                    mediaPlayer.mDrmProvisioningInProgress = false;
4620                    mediaPlayer.mPrepareDrmInProgress = false;
4621                }
4622
4623                // calling the callback outside the lock
4624                onDrmPreparedHandlerDelegate.notifyClient(succeeded);
4625            } else {   // blocking mode already has the lock
4626
4627                // continuing with prepareDrm
4628                if (provisioningSucceeded) {
4629                    succeeded = mediaPlayer.resumePrepareDrm(uuid);
4630                }
4631                mediaPlayer.mDrmProvisioningInProgress = false;
4632                mediaPlayer.mPrepareDrmInProgress = false;
4633            }
4634
4635            finished = true;
4636        }   // run()
4637
4638    }   // ProvisioningThread
4639
4640    private boolean HandleProvisioninig(UUID uuid)
4641    {
4642        // the lock is already held by the caller
4643
4644        if (mDrmProvisioningInProgress) {
4645            Log.e(TAG, String.format("HandleProvisioninig: Unexpected mDrmProvisioningInProgress"));
4646            return false;
4647        }
4648
4649        MediaDrm.ProvisionRequest provReq = null;
4650        try {
4651            MediaDrm drm = new MediaDrm(uuid);
4652            provReq = drm.getProvisionRequest();
4653            drm.release();
4654        } catch (Exception e) {
4655            Log.e(TAG, String.format("HandleProvisioninig: getProvisionRequest failed with %s", e));
4656            return false;
4657        }
4658
4659        Log.v(TAG, String.format("HandleProvisioninig provReq: data %s  url %s",
4660                                 (provReq != null) ? provReq.getData() : "-",
4661                                 (provReq != null) ? provReq.getDefaultUrl() : "://")
4662              );
4663
4664        // networking in a background thread
4665        mDrmProvisioningInProgress = true;
4666
4667        mDrmProvisioningThread = new ProvisioningThread().initialize(provReq, uuid, this);
4668        mDrmProvisioningThread.start();
4669
4670        boolean result = false;
4671
4672        // non-blocking
4673        if (mOnDrmPreparedHandlerDelegate != null) {
4674            result = true;
4675        } else {
4676            // if blocking mode, wait till provisioning is done
4677            try {
4678                mDrmProvisioningThread.join();
4679            } catch (Exception e) {
4680                Log.w(TAG, String.format("HandleProvisioninig: Thread.join Exception %s", e));
4681            }
4682            result = mDrmProvisioningThread.succeeded();
4683            // no longer need the thread
4684            mDrmProvisioningThread = null;
4685        }
4686
4687        return result;
4688    }
4689
4690    private boolean resumePrepareDrm(UUID uuid)
4691    {
4692        // mDrmLock is guaranteed to be held
4693        boolean success = false;
4694        try {
4695            boolean allowOpenSession = true;  // resuming
4696            _prepareDrm(getByteArrayFromUUID(uuid),  allowOpenSession ? 1 : 0);
4697
4698            mDrmUUID = uuid;
4699            mActiveDrmScheme = true;
4700
4701            success = true;
4702        } catch (Exception e) {
4703            Log.w(TAG, String.format("HandleProvisioninig: " +
4704                                     "Thread run _prepareDrm resume failed with %s", e));
4705        }
4706
4707        return success;
4708    }
4709
4710    private void resetDrmState()
4711    {
4712        synchronized (mDrmLock) {
4713            mDrmInfoResolved = false;
4714            mDrmInfo = null;
4715
4716            if (mDrmProvisioningThread != null) {
4717                // timeout; relying on HttpUrlConnection
4718                try {
4719                    mDrmProvisioningThread.join();
4720                }
4721                catch (InterruptedException e) {
4722                    Log.w(TAG, String.format("resetDrmState: ProvThread.join Exception %s", e));
4723                }
4724                mDrmProvisioningThread = null;
4725            }
4726
4727            mPrepareDrmInProgress = false;
4728        }   // synchronized
4729    }
4730
4731    private static final byte[] getByteArrayFromUUID(@NonNull UUID uuid) {
4732        long msb = uuid.getMostSignificantBits();
4733        long lsb = uuid.getLeastSignificantBits();
4734
4735        byte[] uuidBytes = new byte[16];
4736        for (int i = 0; i < 8; ++i) {
4737            uuidBytes[i] = (byte)(msb >>> (8 * (7 - i)));
4738            uuidBytes[8 + i] = (byte)(lsb >>> (8 * (7 - i)));
4739        }
4740
4741        return uuidBytes;
4742    }
4743
4744    // Modular DRM end
4745
4746    /*
4747     * Test whether a given video scaling mode is supported.
4748     */
4749    private boolean isVideoScalingModeSupported(int mode) {
4750        return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
4751                mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
4752    }
4753
4754    /** @hide */
4755    static class TimeProvider implements MediaPlayer.OnSeekCompleteListener,
4756            MediaTimeProvider {
4757        private static final String TAG = "MTP";
4758        private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L;
4759        private static final long MAX_EARLY_CALLBACK_US = 1000;
4760        private static final long TIME_ADJUSTMENT_RATE = 2;  /* meaning 1/2 */
4761        private long mLastTimeUs = 0;
4762        private MediaPlayer mPlayer;
4763        private boolean mPaused = true;
4764        private boolean mStopped = true;
4765        private boolean mBuffering;
4766        private long mLastReportedTime;
4767        private long mTimeAdjustment;
4768        // since we are expecting only a handful listeners per stream, there is
4769        // no need for log(N) search performance
4770        private MediaTimeProvider.OnMediaTimeListener mListeners[];
4771        private long mTimes[];
4772        private long mLastNanoTime;
4773        private Handler mEventHandler;
4774        private boolean mRefresh = false;
4775        private boolean mPausing = false;
4776        private boolean mSeeking = false;
4777        private static final int NOTIFY = 1;
4778        private static final int NOTIFY_TIME = 0;
4779        private static final int REFRESH_AND_NOTIFY_TIME = 1;
4780        private static final int NOTIFY_STOP = 2;
4781        private static final int NOTIFY_SEEK = 3;
4782        private static final int NOTIFY_TRACK_DATA = 4;
4783        private HandlerThread mHandlerThread;
4784
4785        /** @hide */
4786        public boolean DEBUG = false;
4787
4788        public TimeProvider(MediaPlayer mp) {
4789            mPlayer = mp;
4790            try {
4791                getCurrentTimeUs(true, false);
4792            } catch (IllegalStateException e) {
4793                // we assume starting position
4794                mRefresh = true;
4795            }
4796
4797            Looper looper;
4798            if ((looper = Looper.myLooper()) == null &&
4799                (looper = Looper.getMainLooper()) == null) {
4800                // Create our own looper here in case MP was created without one
4801                mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread",
4802                      Process.THREAD_PRIORITY_FOREGROUND);
4803                mHandlerThread.start();
4804                looper = mHandlerThread.getLooper();
4805            }
4806            mEventHandler = new EventHandler(looper);
4807
4808            mListeners = new MediaTimeProvider.OnMediaTimeListener[0];
4809            mTimes = new long[0];
4810            mLastTimeUs = 0;
4811            mTimeAdjustment = 0;
4812        }
4813
4814        private void scheduleNotification(int type, long delayUs) {
4815            // ignore time notifications until seek is handled
4816            if (mSeeking &&
4817                    (type == NOTIFY_TIME || type == REFRESH_AND_NOTIFY_TIME)) {
4818                return;
4819            }
4820
4821            if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs);
4822            mEventHandler.removeMessages(NOTIFY);
4823            Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0);
4824            mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000));
4825        }
4826
4827        /** @hide */
4828        public void close() {
4829            mEventHandler.removeMessages(NOTIFY);
4830            if (mHandlerThread != null) {
4831                mHandlerThread.quitSafely();
4832                mHandlerThread = null;
4833            }
4834        }
4835
4836        /** @hide */
4837        protected void finalize() {
4838            if (mHandlerThread != null) {
4839                mHandlerThread.quitSafely();
4840            }
4841        }
4842
4843        /** @hide */
4844        public void onPaused(boolean paused) {
4845            synchronized(this) {
4846                if (DEBUG) Log.d(TAG, "onPaused: " + paused);
4847                if (mStopped) { // handle as seek if we were stopped
4848                    mStopped = false;
4849                    mSeeking = true;
4850                    scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
4851                } else {
4852                    mPausing = paused;  // special handling if player disappeared
4853                    mSeeking = false;
4854                    scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
4855                }
4856            }
4857        }
4858
4859        /** @hide */
4860        public void onBuffering(boolean buffering) {
4861            synchronized (this) {
4862                if (DEBUG) Log.d(TAG, "onBuffering: " + buffering);
4863                mBuffering = buffering;
4864                scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
4865            }
4866        }
4867
4868        /** @hide */
4869        public void onStopped() {
4870            synchronized(this) {
4871                if (DEBUG) Log.d(TAG, "onStopped");
4872                mPaused = true;
4873                mStopped = true;
4874                mSeeking = false;
4875                mBuffering = false;
4876                scheduleNotification(NOTIFY_STOP, 0 /* delay */);
4877            }
4878        }
4879
4880        /** @hide */
4881        @Override
4882        public void onSeekComplete(MediaPlayer mp) {
4883            synchronized(this) {
4884                mStopped = false;
4885                mSeeking = true;
4886                scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
4887            }
4888        }
4889
4890        /** @hide */
4891        public void onNewPlayer() {
4892            if (mRefresh) {
4893                synchronized(this) {
4894                    mStopped = false;
4895                    mSeeking = true;
4896                    mBuffering = false;
4897                    scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
4898                }
4899            }
4900        }
4901
4902        private synchronized void notifySeek() {
4903            mSeeking = false;
4904            try {
4905                long timeUs = getCurrentTimeUs(true, false);
4906                if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs);
4907
4908                for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
4909                    if (listener == null) {
4910                        break;
4911                    }
4912                    listener.onSeek(timeUs);
4913                }
4914            } catch (IllegalStateException e) {
4915                // we should not be there, but at least signal pause
4916                if (DEBUG) Log.d(TAG, "onSeekComplete but no player");
4917                mPausing = true;  // special handling if player disappeared
4918                notifyTimedEvent(false /* refreshTime */);
4919            }
4920        }
4921
4922        private synchronized void notifyTrackData(Pair<SubtitleTrack, byte[]> trackData) {
4923            SubtitleTrack track = trackData.first;
4924            byte[] data = trackData.second;
4925            track.onData(data, true /* eos */, ~0 /* runID: keep forever */);
4926        }
4927
4928        private synchronized void notifyStop() {
4929            for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
4930                if (listener == null) {
4931                    break;
4932                }
4933                listener.onStop();
4934            }
4935        }
4936
4937        private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) {
4938            int i = 0;
4939            for (; i < mListeners.length; i++) {
4940                if (mListeners[i] == listener || mListeners[i] == null) {
4941                    break;
4942                }
4943            }
4944
4945            // new listener
4946            if (i >= mListeners.length) {
4947                MediaTimeProvider.OnMediaTimeListener[] newListeners =
4948                    new MediaTimeProvider.OnMediaTimeListener[i + 1];
4949                long[] newTimes = new long[i + 1];
4950                System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length);
4951                System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length);
4952                mListeners = newListeners;
4953                mTimes = newTimes;
4954            }
4955
4956            if (mListeners[i] == null) {
4957                mListeners[i] = listener;
4958                mTimes[i] = MediaTimeProvider.NO_TIME;
4959            }
4960            return i;
4961        }
4962
4963        public void notifyAt(
4964                long timeUs, MediaTimeProvider.OnMediaTimeListener listener) {
4965            synchronized(this) {
4966                if (DEBUG) Log.d(TAG, "notifyAt " + timeUs);
4967                mTimes[registerListener(listener)] = timeUs;
4968                scheduleNotification(NOTIFY_TIME, 0 /* delay */);
4969            }
4970        }
4971
4972        public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) {
4973            synchronized(this) {
4974                if (DEBUG) Log.d(TAG, "scheduleUpdate");
4975                int i = registerListener(listener);
4976
4977                if (!mStopped) {
4978                    mTimes[i] = 0;
4979                    scheduleNotification(NOTIFY_TIME, 0 /* delay */);
4980                }
4981            }
4982        }
4983
4984        public void cancelNotifications(
4985                MediaTimeProvider.OnMediaTimeListener listener) {
4986            synchronized(this) {
4987                int i = 0;
4988                for (; i < mListeners.length; i++) {
4989                    if (mListeners[i] == listener) {
4990                        System.arraycopy(mListeners, i + 1,
4991                                mListeners, i, mListeners.length - i - 1);
4992                        System.arraycopy(mTimes, i + 1,
4993                                mTimes, i, mTimes.length - i - 1);
4994                        mListeners[mListeners.length - 1] = null;
4995                        mTimes[mTimes.length - 1] = NO_TIME;
4996                        break;
4997                    } else if (mListeners[i] == null) {
4998                        break;
4999                    }
5000                }
5001
5002                scheduleNotification(NOTIFY_TIME, 0 /* delay */);
5003            }
5004        }
5005
5006        private synchronized void notifyTimedEvent(boolean refreshTime) {
5007            // figure out next callback
5008            long nowUs;
5009            try {
5010                nowUs = getCurrentTimeUs(refreshTime, true);
5011            } catch (IllegalStateException e) {
5012                // assume we paused until new player arrives
5013                mRefresh = true;
5014                mPausing = true; // this ensures that call succeeds
5015                nowUs = getCurrentTimeUs(refreshTime, true);
5016            }
5017            long nextTimeUs = nowUs;
5018
5019            if (mSeeking) {
5020                // skip timed-event notifications until seek is complete
5021                return;
5022            }
5023
5024            if (DEBUG) {
5025                StringBuilder sb = new StringBuilder();
5026                sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ")
5027                        .append(nowUs).append(") from {");
5028                boolean first = true;
5029                for (long time: mTimes) {
5030                    if (time == NO_TIME) {
5031                        continue;
5032                    }
5033                    if (!first) sb.append(", ");
5034                    sb.append(time);
5035                    first = false;
5036                }
5037                sb.append("}");
5038                Log.d(TAG, sb.toString());
5039            }
5040
5041            Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners =
5042                new Vector<MediaTimeProvider.OnMediaTimeListener>();
5043            for (int ix = 0; ix < mTimes.length; ix++) {
5044                if (mListeners[ix] == null) {
5045                    break;
5046                }
5047                if (mTimes[ix] <= NO_TIME) {
5048                    // ignore, unless we were stopped
5049                } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) {
5050                    activatedListeners.add(mListeners[ix]);
5051                    if (DEBUG) Log.d(TAG, "removed");
5052                    mTimes[ix] = NO_TIME;
5053                } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) {
5054                    nextTimeUs = mTimes[ix];
5055                }
5056            }
5057
5058            if (nextTimeUs > nowUs && !mPaused) {
5059                // schedule callback at nextTimeUs
5060                if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs);
5061                scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs);
5062            } else {
5063                mEventHandler.removeMessages(NOTIFY);
5064                // no more callbacks
5065            }
5066
5067            for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) {
5068                listener.onTimedEvent(nowUs);
5069            }
5070        }
5071
5072        private long getEstimatedTime(long nanoTime, boolean monotonic) {
5073            if (mPaused) {
5074                mLastReportedTime = mLastTimeUs + mTimeAdjustment;
5075            } else {
5076                long timeSinceRead = (nanoTime - mLastNanoTime) / 1000;
5077                mLastReportedTime = mLastTimeUs + timeSinceRead;
5078                if (mTimeAdjustment > 0) {
5079                    long adjustment =
5080                        mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE;
5081                    if (adjustment <= 0) {
5082                        mTimeAdjustment = 0;
5083                    } else {
5084                        mLastReportedTime += adjustment;
5085                    }
5086                }
5087            }
5088            return mLastReportedTime;
5089        }
5090
5091        public long getCurrentTimeUs(boolean refreshTime, boolean monotonic)
5092                throws IllegalStateException {
5093            synchronized (this) {
5094                // we always refresh the time when the paused-state changes, because
5095                // we expect to have received the pause-change event delayed.
5096                if (mPaused && !refreshTime) {
5097                    return mLastReportedTime;
5098                }
5099
5100                long nanoTime = System.nanoTime();
5101                if (refreshTime ||
5102                        nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) {
5103                    try {
5104                        mLastTimeUs = mPlayer.getCurrentPosition() * 1000L;
5105                        mPaused = !mPlayer.isPlaying() || mBuffering;
5106                        if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs);
5107                    } catch (IllegalStateException e) {
5108                        if (mPausing) {
5109                            // if we were pausing, get last estimated timestamp
5110                            mPausing = false;
5111                            getEstimatedTime(nanoTime, monotonic);
5112                            mPaused = true;
5113                            if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime);
5114                            return mLastReportedTime;
5115                        }
5116                        // TODO get time when prepared
5117                        throw e;
5118                    }
5119                    mLastNanoTime = nanoTime;
5120                    if (monotonic && mLastTimeUs < mLastReportedTime) {
5121                        /* have to adjust time */
5122                        mTimeAdjustment = mLastReportedTime - mLastTimeUs;
5123                        if (mTimeAdjustment > 1000000) {
5124                            // schedule seeked event if time jumped significantly
5125                            // TODO: do this properly by introducing an exception
5126                            mStopped = false;
5127                            mSeeking = true;
5128                            scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
5129                        }
5130                    } else {
5131                        mTimeAdjustment = 0;
5132                    }
5133                }
5134
5135                return getEstimatedTime(nanoTime, monotonic);
5136            }
5137        }
5138
5139        private class EventHandler extends Handler {
5140            public EventHandler(Looper looper) {
5141                super(looper);
5142            }
5143
5144            @Override
5145            public void handleMessage(Message msg) {
5146                if (msg.what == NOTIFY) {
5147                    switch (msg.arg1) {
5148                    case NOTIFY_TIME:
5149                        notifyTimedEvent(false /* refreshTime */);
5150                        break;
5151                    case REFRESH_AND_NOTIFY_TIME:
5152                        notifyTimedEvent(true /* refreshTime */);
5153                        break;
5154                    case NOTIFY_STOP:
5155                        notifyStop();
5156                        break;
5157                    case NOTIFY_SEEK:
5158                        notifySeek();
5159                        break;
5160                    case NOTIFY_TRACK_DATA:
5161                        notifyTrackData((Pair<SubtitleTrack, byte[]>)msg.obj);
5162                        break;
5163                    }
5164                }
5165            }
5166        }
5167    }
5168}
5169