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