2 * Copyright (C) 2006 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package android.media;
19 import android.annotation.IntDef;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.app.ActivityThread;
23 import android.content.ContentProvider;
24 import android.content.ContentResolver;
25 import android.content.Context;
26 import android.content.res.AssetFileDescriptor;
27 import android.net.Uri;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.os.HandlerThread;
31 import android.os.IBinder;
32 import android.os.Looper;
33 import android.os.Message;
34 import android.os.Parcel;
35 import android.os.Parcelable;
36 import android.os.PersistableBundle;
37 import android.os.Process;
38 import android.os.PowerManager;
39 import android.os.SystemProperties;
40 import android.provider.Settings;
41 import android.system.ErrnoException;
42 import android.system.OsConstants;
43 import android.util.Log;
44 import android.util.Pair;
45 import android.view.Surface;
46 import android.view.SurfaceHolder;
47 import android.widget.VideoView;
48 import android.graphics.SurfaceTexture;
49 import android.media.AudioManager;
50 import android.media.MediaDrm;
51 import android.media.MediaFormat;
52 import android.media.MediaTimeProvider;
53 import android.media.PlaybackParams;
54 import android.media.SubtitleController;
55 import android.media.SubtitleController.Anchor;
56 import android.media.SubtitleData;
57 import android.media.SubtitleTrack.RenderingWidget;
58 import android.media.SyncParams;
60 import com.android.internal.util.Preconditions;
62 import libcore.io.IoBridge;
63 import libcore.io.Libcore;
64 import libcore.io.Streams;
66 import java.io.ByteArrayOutputStream;
68 import java.io.FileDescriptor;
69 import java.io.FileInputStream;
70 import java.io.IOException;
71 import java.io.InputStream;
72 import java.lang.Runnable;
73 import java.lang.annotation.Retention;
74 import java.lang.annotation.RetentionPolicy;
75 import java.lang.ref.WeakReference;
76 import java.net.CookieHandler;
77 import java.net.CookieManager;
78 import java.net.HttpCookie;
79 import java.net.HttpURLConnection;
80 import java.net.InetSocketAddress;
82 import java.nio.ByteOrder;
83 import java.util.Arrays;
84 import java.util.BitSet;
85 import java.util.HashMap;
86 import java.util.List;
88 import java.util.Scanner;
90 import java.util.UUID;
91 import java.util.Vector;
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}.
99 * <p>Topics covered here are:
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>
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>
113 * <a name="StateDiagram"></a>
114 * <h3>State Diagram</h3>
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>
125 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
126 * alt="MediaPlayer State diagram"
129 * <p>From this state diagram, one can see that a MediaPlayer object has the
130 * following states:</p>
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.
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>
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.
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)}.
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>
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>
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.
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>
217 * <li>A MediaPlayer object must first enter the <em>Prepared</em> state
218 * before playback can be started.
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>
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.
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>
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.
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>
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.
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>
290 * <li>The playback position can be adjusted with a call to
291 * {@link #seekTo(long, int)}.
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>
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
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>
313 * <li>When the playback reaches the end of stream, the playback completes.
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>
330 * <a name="Valid_and_Invalid_States"></a>
331 * <h3>Valid and invalid states</h3>
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>
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>
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>
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,
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>
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,
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>
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>
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>
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>
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>
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>
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>
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>
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.
502 * <tr><td>setScreenOnWhilePlaying</></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>
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>
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 <uses-permission>}
554 * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
555 * when used with network-based content.
557 * <a name="Callbacks"></a>
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
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).
577 public class MediaPlayer extends PlayerBase
578 implements SubtitleController.Listener
582 Constant to retrieve only the new metadata since the last
585 // FIXME: add link to getMetadata(boolean, boolean)
588 public static final boolean METADATA_UPDATE_ONLY = true;
591 Constant to retrieve all the metadata.
593 // FIXME: add link to getMetadata(boolean, boolean)
596 public static final boolean METADATA_ALL = false;
599 Constant to enable the metadata filter during retrieval.
601 // FIXME: add link to getMetadata(boolean, boolean)
604 public static final boolean APPLY_METADATA_FILTER = true;
607 Constant to disable the metadata filter during retrieval.
609 // FIXME: add link to getMetadata(boolean, boolean)
612 public static final boolean BYPASS_METADATA_FILTER = false;
615 System.loadLibrary("media_jni");
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";
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;
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;
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>
657 public MediaPlayer() {
658 super(new AudioAttributes.Builder().build(),
659 AudioPlaybackConfiguration.PLAYER_TYPE_JAM_MEDIAPLAYER);
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);
667 mEventHandler = null;
670 mTimeProvider = new TimeProvider(this);
671 mOpenSubtitleSources = new Vector<InputStream>();
673 /* Native setup requires a weak reference to our object.
674 * It's easier to create it here than in C++.
676 native_setup(new WeakReference<MediaPlayer>(this));
678 baseRegisterPlayer();
682 * Update the MediaPlayer SurfaceTexture.
683 * Call after setting a new display surface.
685 private native void _setVideoSurface(Surface surface);
687 /* Do not change these values (starting with INVOKE_ID) without updating
688 * their counterparts in include/media/mediaplayer.h!
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;
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
705 * @return A parcel suitable to hold a request for the native
709 public Parcel newRequest() {
710 Parcel parcel = Parcel.obtain();
711 parcel.writeInterfaceToken(IMEDIA_PLAYER);
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.
722 * @param request Parcel with the data for the extension. The
723 * caller must use {@link #newRequest()} to get one.
725 * @param reply Output parcel with the data returned by the
729 public void invoke(Parcel request, Parcel reply) {
730 int retcode = native_invoke(request, reply);
731 reply.setDataPosition(0);
733 throw new RuntimeException("failure code: " + retcode);
738 * Sets the {@link SurfaceHolder} to use for displaying the video
739 * portion of the media.
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
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.
751 public void setDisplay(SurfaceHolder sh) {
755 surface = sh.getSurface();
759 _setVideoSurface(surface);
760 updateSurfaceScreenOn();
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.
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.
778 * @param surface The {@link Surface} to be used for the video portion of
780 * @throws IllegalStateException if the internal player engine has not been
781 * initialized or has been released.
783 public void setSurface(Surface surface) {
784 if (mScreenOnWhilePlaying && surface != null) {
785 Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
787 mSurfaceHolder = null;
788 _setVideoSurface(surface);
789 updateSurfaceScreenOn();
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
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.
805 public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1;
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.
813 public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2;
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}.
820 * <p> The supported video scaling modes are:
822 * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}
823 * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING}
826 * @param mode target video scaling mode. Must be one of the supported
827 * video scaling modes; otherwise, IllegalArgumentException will be thrown.
829 * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT
830 * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
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);
837 Parcel request = Parcel.obtain();
838 Parcel reply = Parcel.obtain();
840 request.writeInterfaceToken(IMEDIA_PLAYER);
841 request.writeInt(INVOKE_ID_SET_VIDEO_SCALE_MODE);
842 request.writeInt(mode);
843 invoke(request, reply);
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>
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
865 public static MediaPlayer create(Context context, Uri uri) {
866 return create (context, uri, null);
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>
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
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);
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
901 public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder,
902 AudioAttributes audioAttributes, int audioSessionId) {
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);
916 } catch (IOException ex) {
917 Log.d(TAG, "create failed:", ex);
919 } catch (IllegalArgumentException ex) {
920 Log.d(TAG, "create failed:", ex);
922 } catch (SecurityException ex) {
923 Log.d(TAG, "create failed:", ex);
930 // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
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>
943 * @param context the Context to use
944 * @param resid the raw resource id (<var>R.raw.<something></var>) for
945 * the resource to use as the datasource
946 * @return a MediaPlayer object, or null if creation failed
948 public static MediaPlayer create(Context context, int resid) {
949 int s = AudioSystem.newAudioSessionId();
950 return create(context, resid, null, s > 0 ? s : 0);
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.<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
964 public static MediaPlayer create(Context context, int resid,
965 AudioAttributes audioAttributes, int audioSessionId) {
967 AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
968 if (afd == null) return null;
970 MediaPlayer mp = new MediaPlayer();
972 final AudioAttributes aa = audioAttributes != null ? audioAttributes :
973 new AudioAttributes.Builder().build();
974 mp.setAudioAttributes(aa);
975 mp.setAudioSessionId(audioSessionId);
977 mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
981 } catch (IOException ex) {
982 Log.d(TAG, "create failed:", ex);
984 } catch (IllegalArgumentException ex) {
985 Log.d(TAG, "create failed:", ex);
987 } catch (SecurityException ex) {
988 Log.d(TAG, "create failed:", ex);
995 * Sets the data source as a content Uri.
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
1001 public void setDataSource(@NonNull Context context, @NonNull Uri uri)
1002 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
1003 setDataSource(context, uri, null, null);
1007 * Sets the data source as a content Uri.
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.
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.
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
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
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.");
1040 throw new NullPointerException("uri param can not be null.");
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.");
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());
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)) {
1068 } else if (attemptDataSource(resolver, actualUri)) {
1071 setDataSource(uri.toString(), headers, cookies);
1074 // Try requested Uri locally first, or fallback to media server
1075 if (attemptDataSource(resolver, uri)) {
1078 setDataSource(uri.toString(), headers, cookies);
1084 * Sets the data source as a content Uri.
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.
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
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);
1102 private boolean attemptDataSource(ContentResolver resolver, Uri uri) {
1103 try (AssetFileDescriptor afd = resolver.openAssetFileDescriptor(uri, "r")) {
1106 } catch (NullPointerException | SecurityException | IOException ex) {
1107 Log.w(TAG, "Couldn't open " + uri + ": " + ex);
1113 * Sets the data source (file-path or http/rtsp URL) to use.
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)}.
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
1125 public void setDataSource(String path)
1126 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
1127 setDataSource(path, null, null);
1131 * Sets the data source (file-path or http/rtsp URL) to use.
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
1138 public void setDataSource(String path, Map<String, String> headers)
1139 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
1140 setDataSource(path, headers, null);
1143 private void setDataSource(String path, Map<String, String> headers, List<HttpCookie> cookies)
1144 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException
1146 String[] keys = null;
1147 String[] values = null;
1149 if (headers != null) {
1150 keys = new String[headers.size()];
1151 values = new String[headers.size()];
1154 for (Map.Entry<String, String> entry: headers.entrySet()) {
1155 keys[i] = entry.getKey();
1156 values[i] = entry.getValue();
1160 setDataSource(path, keys, values, cookies);
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),
1180 final File file = new File(path);
1181 if (file.exists()) {
1182 FileInputStream is = new FileInputStream(file);
1183 FileDescriptor fd = is.getFD();
1187 throw new IOException("setDataSource failed.");
1191 private native void nativeSetDataSource(
1192 IBinder httpServiceBinder, String path, String[] keys, String[] values)
1193 throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
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.
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
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
1211 if (afd.getDeclaredLength() < 0) {
1212 setDataSource(afd.getFileDescriptor());
1214 setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
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.
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
1227 public void setDataSource(FileDescriptor fd)
1228 throws IOException, IllegalArgumentException, IllegalStateException {
1229 // intentionally less than LONG_MAX
1230 setDataSource(fd, 0, 0x7ffffffffffffffL);
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.
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
1245 public void setDataSource(FileDescriptor fd, long offset, long length)
1246 throws IOException, IllegalArgumentException, IllegalStateException {
1247 _setDataSource(fd, offset, length);
1250 private native void _setDataSource(FileDescriptor fd, long offset, long length)
1251 throws IOException, IllegalArgumentException, IllegalStateException;
1254 * Sets the data source (MediaDataSource) to use.
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
1260 public void setDataSource(MediaDataSource dataSource)
1261 throws IllegalArgumentException, IllegalStateException {
1262 _setDataSource(dataSource);
1265 private native void _setDataSource(MediaDataSource dataSource)
1266 throws IllegalArgumentException, IllegalStateException;
1269 * Prepares the player for playback, synchronously.
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.
1275 * @throws IllegalStateException if it is called in an invalid state
1277 public void prepare() throws IOException, IllegalStateException {
1279 scanInternalSubtitleTracks();
1281 // DrmInfo, if any, has been resolved by now.
1282 synchronized (mDrmLock) {
1283 mDrmInfoResolved = true;
1287 private native void _prepare() throws IOException, IllegalStateException;
1290 * Prepares the player for playback, asynchronously.
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
1297 * @throws IllegalStateException if it is called in an invalid state
1299 public native void prepareAsync() throws IllegalStateException;
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
1307 * @throws IllegalStateException if it is called in an invalid state
1309 public void start() throws IllegalStateException {
1310 //FIXME use lambda to pass startImpl to superclass
1311 final int delay = getStartDelayMs();
1318 Thread.sleep(delay);
1319 } catch (InterruptedException e) {
1320 e.printStackTrace();
1322 baseSetStartDelayMs(0);
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()
1335 private void startImpl() {
1341 private native void _start() throws IllegalStateException;
1344 private int getAudioStreamType() {
1345 if (mStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
1346 mStreamType = _getAudioStreamType();
1351 private native int _getAudioStreamType() throws IllegalStateException;
1354 * Stops playback after playback has been started or paused.
1356 * @throws IllegalStateException if the internal player engine has not been
1359 public void stop() throws IllegalStateException {
1365 private native void _stop() throws IllegalStateException;
1368 * Pauses playback. Call start() to resume.
1370 * @throws IllegalStateException if the internal player engine has not been
1373 public void pause() throws IllegalStateException {
1379 private native void _pause() throws IllegalStateException;
1382 void playerStart() {
1387 void playerPause() {
1397 /* package */ int playerApplyVolumeShaper(
1398 @NonNull VolumeShaper.Configuration configuration,
1399 @NonNull VolumeShaper.Operation operation) {
1400 return native_applyVolumeShaper(configuration, operation);
1404 /* package */ @Nullable VolumeShaper.State playerGetVolumeShaperState(int id) {
1405 return native_getVolumeShaperState(id);
1409 public @NonNull VolumeShaper createVolumeShaper(
1410 @NonNull VolumeShaper.Configuration configuration) {
1411 return new VolumeShaper(configuration, this);
1414 private native int native_applyVolumeShaper(
1415 @NonNull VolumeShaper.Configuration configuration,
1416 @NonNull VolumeShaper.Operation operation);
1418 private native @Nullable VolumeShaper.State native_getVolumeShaperState(int id);
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.
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}
1431 * By default, no attempt is made to keep the device awake during playback.
1433 * @param context the Context to use
1434 * @param mode the power/wake mode to set
1435 * @see android.os.PowerManager
1437 public void setWakeMode(Context context, int mode) {
1438 boolean washeld = false;
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);
1446 if (mWakeLock != null) {
1447 if (mWakeLock.isHeld()) {
1449 mWakeLock.release();
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);
1458 mWakeLock.acquire();
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
1469 * @param screenOn Supply true to keep the screen on, false to allow it
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");
1477 mScreenOnWhilePlaying = screenOn;
1478 updateSurfaceScreenOn();
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();
1491 updateSurfaceScreenOn();
1494 private void updateSurfaceScreenOn() {
1495 if (mSurfaceHolder != null) {
1496 mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
1501 * Returns the width of the video.
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.
1509 public native int getVideoWidth();
1512 * Returns the height of the video.
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.
1520 public native int getVideoHeight();
1523 * Return Metrics data about the current player.
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}.
1529 * Additional vendor-specific fields may also be present in
1532 public PersistableBundle getMetrics() {
1533 PersistableBundle bundle = native_getMetrics();
1537 private native PersistableBundle native_getMetrics();
1540 * Checks whether the MediaPlayer is playing.
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.
1546 public native boolean isPlaying();
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.
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.
1559 public native BufferingParams getDefaultBufferingParams();
1562 * Gets the current buffering management params used by the source component.
1563 * Calling it only after {@code setDataSource} has been called.
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.
1571 public native BufferingParams getBufferingParams();
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}.
1581 * @param params the buffering management params.
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.
1588 public native void setBufferingParams(@NonNull BufferingParams params);
1591 * Change playback speed of audio by resampling the audio.
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
1597 * When rate is larger than 1.0, pitch becomes higher.
1598 * When rate is smaller than 1.0, pitch becomes lower.
1602 public static final int PLAYBACK_RATE_AUDIO_MODE_RESAMPLE = 2;
1605 * Change playback speed of audio without changing its pitch.
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.
1611 * This mode is only supported for a limited range of playback speed factors,
1612 * e.g. between 1/2x and 2x.
1616 public static final int PLAYBACK_RATE_AUDIO_MODE_STRETCH = 1;
1619 * Change playback speed of audio without changing its pitch, and
1620 * possibly mute audio if time stretching is not supported for the playback
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
1629 public static final int PLAYBACK_RATE_AUDIO_MODE_DEFAULT = 0;
1634 PLAYBACK_RATE_AUDIO_MODE_DEFAULT,
1635 PLAYBACK_RATE_AUDIO_MODE_STRETCH,
1636 PLAYBACK_RATE_AUDIO_MODE_RESAMPLE,
1638 @Retention(RetentionPolicy.SOURCE)
1639 public @interface PlaybackRateAudioMode {}
1642 * Sets playback rate and audio mode.
1644 * @param rate the ratio between desired playback rate and normal one.
1645 * @param audioMode audio playback mode. Must be one of the supported
1648 * @throws IllegalStateException if the internal player engine has not been
1650 * @throws IllegalArgumentException if audioMode is not supported.
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);
1662 case PLAYBACK_RATE_AUDIO_MODE_STRETCH:
1663 params.setSpeed(rate).setPitch(1.0f)
1664 .setAudioFallbackMode(params.AUDIO_FALLBACK_MODE_FAIL);
1666 case PLAYBACK_RATE_AUDIO_MODE_RESAMPLE:
1667 params.setSpeed(rate).setPitch(rate);
1670 final String msg = "Audio playback mode " + audioMode + " is not supported";
1671 throw new IllegalArgumentException(msg);
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().
1685 * @param params the playback params.
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.
1691 public native void setPlaybackParams(@NonNull PlaybackParams params);
1694 * Gets the playback params, containing the current playback rate.
1696 * @return the playback params.
1697 * @throws IllegalStateException if the internal player engine has not been
1701 public native PlaybackParams getPlaybackParams();
1704 * Sets A/V sync mode.
1706 * @param params the A/V sync params to apply
1708 * @throws IllegalStateException if the internal player engine has not been
1710 * @throws IllegalArgumentException if params are not supported.
1712 public native void setSyncParams(@NonNull SyncParams params);
1715 * Gets the A/V sync mode.
1717 * @return the A/V sync params
1719 * @throws IllegalStateException if the internal player engine has not been
1723 public native SyncParams getSyncParams();
1726 * Seek modes used in method seekTo(long, int) to move media position
1727 * to a specified location.
1729 * Do not change these mode values without updating their counterparts
1730 * in include/media/IMediaSource.h!
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.
1737 * @see #seekTo(long, int)
1739 public static final int SEEK_PREVIOUS_SYNC = 0x00;
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.
1745 * @see #seekTo(long, int)
1747 public static final int SEEK_NEXT_SYNC = 0x01;
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.
1753 * @see #seekTo(long, int)
1755 public static final int SEEK_CLOSEST_SYNC = 0x02;
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.
1761 * @see #seekTo(long, int)
1763 public static final int SEEK_CLOSEST = 0x03;
1773 @Retention(RetentionPolicy.SOURCE)
1774 public @interface SeekMode {}
1776 private native final void _seekTo(long msec, int mode);
1779 * Moves the media to specified time position by considering the given mode.
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.
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
1806 * @throws IllegalArgumentException if the mode is invalid.
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);
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;
1821 _seekTo(msec, mode);
1825 * Seeks to specified time position.
1826 * Same as {@link #seekTo(long, int)} with {@code mode = SEEK_PREVIOUS_SYNC}.
1828 * @param msec the offset in milliseconds from the start to seek to
1829 * @throws IllegalStateException if the internal player engine has not been
1832 public void seekTo(int msec) throws IllegalStateException {
1833 seekTo(msec, SEEK_PREVIOUS_SYNC /* mode */);
1837 * Get current playback position as a {@link MediaTimestamp}.
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.
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.
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.
1852 * @see MediaTimestamp
1855 public MediaTimestamp getTimestamp()
1858 // TODO: get the timestamp from native side
1859 return new MediaTimestamp(
1860 getCurrentPosition() * 1000L,
1862 isPlaying() ? getPlaybackParams().getSpeed() : 0.f);
1863 } catch (IllegalStateException e) {
1869 * Gets the current playback position.
1871 * @return the current position in milliseconds
1873 public native int getCurrentPosition();
1876 * Gets the duration of the file.
1878 * @return the duration in milliseconds, if no duration is available
1879 * (for example, if streaming live content), -1 is returned.
1881 public native int getDuration();
1884 * Gets the media metadata.
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
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}.
1895 * @return The metadata, possibly empty. null if an error occured.
1899 public Metadata getMetadata(final boolean update_only,
1900 final boolean apply_filter) {
1901 Parcel reply = Parcel.obtain();
1902 Metadata data = new Metadata();
1904 if (!native_getMetadata(update_only, apply_filter, reply)) {
1909 // Metadata takes over the parcel, don't recycle it unless
1910 // there is an error.
1911 if (!data.parse(reply)) {
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
1923 * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
1924 * shorthands to allow/block all or no metadata.
1926 * By default, there is no filter set.
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.
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
1943 Parcel request = newRequest();
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());
1951 if (request.dataCapacity() < capacity) {
1952 request.setDataCapacity(capacity);
1955 request.writeInt(allow.size());
1956 for(Integer t: allow) {
1957 request.writeInt(t);
1959 request.writeInt(block.size());
1960 for(Integer t: block) {
1961 request.writeInt(t);
1963 return native_setMetadataFilter(request);
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.
1981 * @param next the player to start after this one completes playback.
1984 public native void setNextMediaPlayer(MediaPlayer next);
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
2004 public void release() {
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;
2020 mOnSubtitleDataListener = null;
2022 // Modular DRM clean up
2023 mOnDrmConfigHelper = null;
2024 mOnDrmInfoHandlerDelegate = null;
2025 mOnDrmPreparedHandlerDelegate = null;
2031 private native void _release();
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().
2038 public void reset() {
2039 mSelectedSubtitleTrackIndex = -1;
2040 synchronized(mOpenSubtitleSources) {
2041 for (final InputStream is: mOpenSubtitleSources) {
2044 } catch (IOException e) {
2047 mOpenSubtitleSources.clear();
2049 if (mSubtitleController != null) {
2050 mSubtitleController.reset();
2052 if (mTimeProvider != null) {
2053 mTimeProvider.close();
2054 mTimeProvider = null;
2059 // make sure none of the listeners get called anymore
2060 if (mEventHandler != null) {
2061 mEventHandler.removeCallbacksAndMessages(null);
2064 synchronized (mIndexTrackPairs) {
2065 mIndexTrackPairs.clear();
2066 mInbandTrackIndices.clear();
2072 private native void _reset();
2075 * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
2076 * for a list of stream types. Must call this method before prepare() or
2077 * prepareAsync() in order for the target stream type to become effective
2080 * @param streamtype the audio stream type
2081 * @deprecated use {@link #setAudioAttributes(AudioAttributes)}
2082 * @see android.media.AudioManager
2084 public void setAudioStreamType(int streamtype) {
2085 deprecateStreamTypeForPlayback(streamtype, "MediaPlayer", "setAudioStreamType()");
2086 baseUpdateAudioAttributes(
2087 new AudioAttributes.Builder().setInternalLegacyStreamType(streamtype).build());
2088 _setAudioStreamType(streamtype);
2089 mStreamType = streamtype;
2092 private native void _setAudioStreamType(int streamtype);
2094 // Keep KEY_PARAMETER_* in sync with include/media/mediaplayer.h
2095 private final static int KEY_PARAMETER_AUDIO_ATTRIBUTES = 1400;
2097 * Sets the parameter indicated by key.
2098 * @param key key indicates the parameter to be set.
2099 * @param value value of the parameter to be set.
2100 * @return true if the parameter is set successfully, false otherwise
2103 private native boolean setParameter(int key, Parcel value);
2106 * Sets the audio attributes for this MediaPlayer.
2107 * See {@link AudioAttributes} for how to build and configure an instance of this class.
2108 * You must call this method before {@link #prepare()} or {@link #prepareAsync()} in order
2109 * for the audio attributes to become effective thereafter.
2110 * @param attributes a non-null set of audio attributes
2112 public void setAudioAttributes(AudioAttributes attributes) throws IllegalArgumentException {
2113 if (attributes == null) {
2114 final String msg = "Cannot set AudioAttributes to null";
2115 throw new IllegalArgumentException(msg);
2117 baseUpdateAudioAttributes(attributes);
2118 mUsage = attributes.getUsage();
2119 mBypassInterruptionPolicy = (attributes.getAllFlags()
2120 & AudioAttributes.FLAG_BYPASS_INTERRUPTION_POLICY) != 0;
2121 Parcel pattributes = Parcel.obtain();
2122 attributes.writeToParcel(pattributes, AudioAttributes.FLATTEN_TAGS);
2123 setParameter(KEY_PARAMETER_AUDIO_ATTRIBUTES, pattributes);
2124 pattributes.recycle();
2128 * Sets the player to be looping or non-looping.
2130 * @param looping whether to loop or not
2132 public native void setLooping(boolean looping);
2135 * Checks whether the MediaPlayer is looping or non-looping.
2137 * @return true if the MediaPlayer is currently looping, false otherwise
2139 public native boolean isLooping();
2142 * Sets the volume on this player.
2143 * This API is recommended for balancing the output of audio streams
2144 * within an application. Unless you are writing an application to
2145 * control user settings, this API should be used in preference to
2146 * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
2147 * a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
2148 * UI controls should be scaled logarithmically.
2150 * @param leftVolume left volume scalar
2151 * @param rightVolume right volume scalar
2154 * FIXME: Merge this into javadoc comment above when setVolume(float) is not @hide.
2155 * The single parameter form below is preferred if the channel volumes don't need
2156 * to be set independently.
2158 public void setVolume(float leftVolume, float rightVolume) {
2159 baseSetVolume(leftVolume, rightVolume);
2163 void playerSetVolume(boolean muting, float leftVolume, float rightVolume) {
2164 _setVolume(muting ? 0.0f : leftVolume, muting ? 0.0f : rightVolume);
2167 private native void _setVolume(float leftVolume, float rightVolume);
2170 * Similar, excepts sets volume of all channels to same value.
2173 public void setVolume(float volume) {
2174 setVolume(volume, volume);
2178 * Sets the audio session ID.
2180 * @param sessionId the audio session ID.
2181 * The audio session ID is a system wide unique identifier for the audio stream played by
2182 * this MediaPlayer instance.
2183 * The primary use of the audio session ID is to associate audio effects to a particular
2184 * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
2185 * this effect will be applied only to the audio content of media players within the same
2186 * audio session and not to the output mix.
2187 * When created, a MediaPlayer instance automatically generates its own audio session ID.
2188 * However, it is possible to force this player to be part of an already existing audio session
2189 * by calling this method.
2190 * This method must be called before one of the overloaded <code> setDataSource </code> methods.
2191 * @throws IllegalStateException if it is called in an invalid state
2193 public native void setAudioSessionId(int sessionId) throws IllegalArgumentException, IllegalStateException;
2196 * Returns the audio session ID.
2198 * @return the audio session ID. {@see #setAudioSessionId(int)}
2199 * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
2201 public native int getAudioSessionId();
2204 * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
2205 * effect which can be applied on any sound source that directs a certain amount of its
2206 * energy to this effect. This amount is defined by setAuxEffectSendLevel().
2207 * See {@link #setAuxEffectSendLevel(float)}.
2208 * <p>After creating an auxiliary effect (e.g.
2209 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
2210 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
2211 * to attach the player to the effect.
2212 * <p>To detach the effect from the player, call this method with a null effect id.
2213 * <p>This method must be called after one of the overloaded <code> setDataSource </code>
2215 * @param effectId system wide unique id of the effect to attach
2217 public native void attachAuxEffect(int effectId);
2221 * Sets the send level of the player to the attached auxiliary effect.
2222 * See {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
2223 * <p>By default the send level is 0, so even if an effect is attached to the player
2224 * this method must be called for the effect to be applied.
2225 * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
2226 * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
2227 * so an appropriate conversion from linear UI input x to level is:
2228 * x == 0 -> level = 0
2229 * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
2230 * @param level send level scalar
2232 public void setAuxEffectSendLevel(float level) {
2233 baseSetAuxEffectSendLevel(level);
2237 int playerSetAuxEffectSendLevel(boolean muting, float level) {
2238 _setAuxEffectSendLevel(muting ? 0.0f : level);
2239 return AudioSystem.SUCCESS;
2242 private native void _setAuxEffectSendLevel(float level);
2245 * @param request Parcel destinated to the media player. The
2246 * Interface token must be set to the IMediaPlayer
2247 * one to be routed correctly through the system.
2248 * @param reply[out] Parcel that will contain the reply.
2249 * @return The status code.
2251 private native final int native_invoke(Parcel request, Parcel reply);
2255 * @param update_only If true fetch only the set of metadata that have
2256 * changed since the last invocation of getMetadata.
2257 * The set is built using the unfiltered
2258 * notifications the native player sent to the
2259 * MediaPlayerService during that period of
2260 * time. If false, all the metadatas are considered.
2261 * @param apply_filter If true, once the metadata set has been built based on
2262 * the value update_only, the current filter is applied.
2263 * @param reply[out] On return contains the serialized
2264 * metadata. Valid only if the call was successful.
2265 * @return The status code.
2267 private native final boolean native_getMetadata(boolean update_only,
2268 boolean apply_filter,
2272 * @param request Parcel with the 2 serialized lists of allowed
2273 * metadata types followed by the one to be
2274 * dropped. Each list starts with an integer
2275 * indicating the number of metadata type elements.
2276 * @return The status code.
2278 private native final int native_setMetadataFilter(Parcel request);
2280 private static native final void native_init();
2281 private native final void native_setup(Object mediaplayer_this);
2282 private native final void native_finalize();
2285 * Class for MediaPlayer to return each audio/video/subtitle track's metadata.
2287 * @see android.media.MediaPlayer#getTrackInfo
2289 static public class TrackInfo implements Parcelable {
2291 * Gets the track type.
2292 * @return TrackType which indicates if the track is video, audio, timed text.
2294 public int getTrackType() {
2299 * Gets the language code of the track.
2300 * @return a language code in either way of ISO-639-1 or ISO-639-2.
2301 * When the language is unknown or could not be determined,
2302 * ISO-639-2 language code, "und", is returned.
2304 public String getLanguage() {
2305 String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
2306 return language == null ? "und" : language;
2310 * Gets the {@link MediaFormat} of the track. If the format is
2311 * unknown or could not be determined, null is returned.
2313 public MediaFormat getFormat() {
2314 if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT
2315 || mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
2321 public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
2322 public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
2323 public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
2324 public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
2325 public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
2326 public static final int MEDIA_TRACK_TYPE_METADATA = 5;
2328 final int mTrackType;
2329 final MediaFormat mFormat;
2331 TrackInfo(Parcel in) {
2332 mTrackType = in.readInt();
2333 // TODO: parcel in the full MediaFormat; currently we are using createSubtitleFormat
2334 // even for audio/video tracks, meaning we only set the mime and language.
2335 String mime = in.readString();
2336 String language = in.readString();
2337 mFormat = MediaFormat.createSubtitleFormat(mime, language);
2339 if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
2340 mFormat.setInteger(MediaFormat.KEY_IS_AUTOSELECT, in.readInt());
2341 mFormat.setInteger(MediaFormat.KEY_IS_DEFAULT, in.readInt());
2342 mFormat.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.readInt());
2347 TrackInfo(int type, MediaFormat format) {
2356 public int describeContents() {
2364 public void writeToParcel(Parcel dest, int flags) {
2365 dest.writeInt(mTrackType);
2366 dest.writeString(getLanguage());
2368 if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
2369 dest.writeString(mFormat.getString(MediaFormat.KEY_MIME));
2370 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_AUTOSELECT));
2371 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_DEFAULT));
2372 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE));
2377 public String toString() {
2378 StringBuilder out = new StringBuilder(128);
2379 out.append(getClass().getName());
2381 switch (mTrackType) {
2382 case MEDIA_TRACK_TYPE_VIDEO:
2383 out.append("VIDEO");
2385 case MEDIA_TRACK_TYPE_AUDIO:
2386 out.append("AUDIO");
2388 case MEDIA_TRACK_TYPE_TIMEDTEXT:
2389 out.append("TIMEDTEXT");
2391 case MEDIA_TRACK_TYPE_SUBTITLE:
2392 out.append("SUBTITLE");
2395 out.append("UNKNOWN");
2398 out.append(", " + mFormat.toString());
2400 return out.toString();
2404 * Used to read a TrackInfo from a Parcel.
2406 static final Parcelable.Creator<TrackInfo> CREATOR
2407 = new Parcelable.Creator<TrackInfo>() {
2409 public TrackInfo createFromParcel(Parcel in) {
2410 return new TrackInfo(in);
2414 public TrackInfo[] newArray(int size) {
2415 return new TrackInfo[size];
2421 // We would like domain specific classes with more informative names than the `first` and `second`
2422 // in generic Pair, but we would also like to avoid creating new/trivial classes. As a compromise
2423 // we document the meanings of `first` and `second` here:
2425 // Pair.first - inband track index; non-null iff representing an inband track.
2426 // Pair.second - a SubtitleTrack registered with mSubtitleController; non-null iff representing
2427 // an inband subtitle track or any out-of-band track (subtitle or timedtext).
2428 private Vector<Pair<Integer, SubtitleTrack>> mIndexTrackPairs = new Vector<>();
2429 private BitSet mInbandTrackIndices = new BitSet();
2432 * Returns an array of track information.
2434 * @return Array of track info. The total number of tracks is the array length.
2435 * Must be called again if an external timed text source has been added after any of the
2436 * addTimedTextSource methods are called.
2437 * @throws IllegalStateException if it is called in an invalid state.
2439 public TrackInfo[] getTrackInfo() throws IllegalStateException {
2440 TrackInfo trackInfo[] = getInbandTrackInfo();
2441 // add out-of-band tracks
2442 synchronized (mIndexTrackPairs) {
2443 TrackInfo allTrackInfo[] = new TrackInfo[mIndexTrackPairs.size()];
2444 for (int i = 0; i < allTrackInfo.length; i++) {
2445 Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
2446 if (p.first != null) {
2448 allTrackInfo[i] = trackInfo[p.first];
2450 SubtitleTrack track = p.second;
2451 allTrackInfo[i] = new TrackInfo(track.getTrackType(), track.getFormat());
2454 return allTrackInfo;
2458 private TrackInfo[] getInbandTrackInfo() throws IllegalStateException {
2459 Parcel request = Parcel.obtain();
2460 Parcel reply = Parcel.obtain();
2462 request.writeInterfaceToken(IMEDIA_PLAYER);
2463 request.writeInt(INVOKE_ID_GET_TRACK_INFO);
2464 invoke(request, reply);
2465 TrackInfo trackInfo[] = reply.createTypedArray(TrackInfo.CREATOR);
2473 /* Do not change these values without updating their counterparts
2474 * in include/media/stagefright/MediaDefs.h and media/libstagefright/MediaDefs.cpp!
2477 * MIME type for SubRip (SRT) container. Used in addTimedTextSource APIs.
2479 public static final String MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
2482 * MIME type for WebVTT subtitle data.
2485 public static final String MEDIA_MIMETYPE_TEXT_VTT = "text/vtt";
2488 * MIME type for CEA-608 closed caption data.
2491 public static final String MEDIA_MIMETYPE_TEXT_CEA_608 = "text/cea-608";
2494 * MIME type for CEA-708 closed caption data.
2497 public static final String MEDIA_MIMETYPE_TEXT_CEA_708 = "text/cea-708";
2500 * A helper function to check if the mime type is supported by media framework.
2502 private static boolean availableMimeTypeForExternalSource(String mimeType) {
2503 if (MEDIA_MIMETYPE_TEXT_SUBRIP.equals(mimeType)) {
2509 private SubtitleController mSubtitleController;
2512 public void setSubtitleAnchor(
2513 SubtitleController controller,
2514 SubtitleController.Anchor anchor) {
2515 // TODO: create SubtitleController in MediaPlayer
2516 mSubtitleController = controller;
2517 mSubtitleController.setAnchor(anchor);
2521 * The private version of setSubtitleAnchor is used internally to set mSubtitleController if
2522 * necessary when clients don't provide their own SubtitleControllers using the public version
2523 * {@link #setSubtitleAnchor(SubtitleController, Anchor)} (e.g. {@link VideoView} provides one).
2525 private synchronized void setSubtitleAnchor() {
2526 if ((mSubtitleController == null) && (ActivityThread.currentApplication() != null)) {
2527 final HandlerThread thread = new HandlerThread("SetSubtitleAnchorThread");
2529 Handler handler = new Handler(thread.getLooper());
2530 handler.post(new Runnable() {
2533 Context context = ActivityThread.currentApplication();
2534 mSubtitleController = new SubtitleController(context, mTimeProvider, MediaPlayer.this);
2535 mSubtitleController.setAnchor(new Anchor() {
2537 public void setSubtitleWidget(RenderingWidget subtitleWidget) {
2541 public Looper getSubtitleLooper() {
2542 return Looper.getMainLooper();
2545 thread.getLooper().quitSafely();
2550 } catch (InterruptedException e) {
2551 Thread.currentThread().interrupt();
2552 Log.w(TAG, "failed to join SetSubtitleAnchorThread");
2557 private int mSelectedSubtitleTrackIndex = -1;
2558 private Vector<InputStream> mOpenSubtitleSources;
2560 private OnSubtitleDataListener mSubtitleDataListener = new OnSubtitleDataListener() {
2562 public void onSubtitleData(MediaPlayer mp, SubtitleData data) {
2563 int index = data.getTrackIndex();
2564 synchronized (mIndexTrackPairs) {
2565 for (Pair<Integer, SubtitleTrack> p : mIndexTrackPairs) {
2566 if (p.first != null && p.first == index && p.second != null) {
2567 // inband subtitle track that owns data
2568 SubtitleTrack track = p.second;
2578 public void onSubtitleTrackSelected(SubtitleTrack track) {
2579 if (mSelectedSubtitleTrackIndex >= 0) {
2581 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, false);
2582 } catch (IllegalStateException e) {
2584 mSelectedSubtitleTrackIndex = -1;
2586 setOnSubtitleDataListener(null);
2587 if (track == null) {
2591 synchronized (mIndexTrackPairs) {
2592 for (Pair<Integer, SubtitleTrack> p : mIndexTrackPairs) {
2593 if (p.first != null && p.second == track) {
2594 // inband subtitle track that is selected
2595 mSelectedSubtitleTrackIndex = p.first;
2601 if (mSelectedSubtitleTrackIndex >= 0) {
2603 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, true);
2604 } catch (IllegalStateException e) {
2606 setOnSubtitleDataListener(mSubtitleDataListener);
2608 // no need to select out-of-band tracks
2612 public void addSubtitleSource(InputStream is, MediaFormat format)
2613 throws IllegalStateException
2615 final InputStream fIs = is;
2616 final MediaFormat fFormat = format;
2619 // Ensure all input streams are closed. It is also a handy
2620 // way to implement timeouts in the future.
2621 synchronized(mOpenSubtitleSources) {
2622 mOpenSubtitleSources.add(is);
2625 Log.w(TAG, "addSubtitleSource called with null InputStream");
2628 getMediaTimeProvider();
2630 // process each subtitle in its own thread
2631 final HandlerThread thread = new HandlerThread("SubtitleReadThread",
2632 Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
2634 Handler handler = new Handler(thread.getLooper());
2635 handler.post(new Runnable() {
2636 private int addTrack() {
2637 if (fIs == null || mSubtitleController == null) {
2638 return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
2641 SubtitleTrack track = mSubtitleController.addTrack(fFormat);
2642 if (track == null) {
2643 return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
2646 // TODO: do the conversion in the subtitle track
2647 Scanner scanner = new Scanner(fIs, "UTF-8");
2648 String contents = scanner.useDelimiter("\\A").next();
2649 synchronized(mOpenSubtitleSources) {
2650 mOpenSubtitleSources.remove(fIs);
2653 synchronized (mIndexTrackPairs) {
2654 mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(null, track));
2656 Handler h = mTimeProvider.mEventHandler;
2657 int what = TimeProvider.NOTIFY;
2658 int arg1 = TimeProvider.NOTIFY_TRACK_DATA;
2659 Pair<SubtitleTrack, byte[]> trackData = Pair.create(track, contents.getBytes());
2660 Message m = h.obtainMessage(what, arg1, 0, trackData);
2662 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
2666 int res = addTrack();
2667 if (mEventHandler != null) {
2668 Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
2669 mEventHandler.sendMessage(m);
2671 thread.getLooper().quitSafely();
2676 private void scanInternalSubtitleTracks() {
2677 setSubtitleAnchor();
2679 populateInbandTracks();
2681 if (mSubtitleController != null) {
2682 mSubtitleController.selectDefaultTrack();
2686 private void populateInbandTracks() {
2687 TrackInfo[] tracks = getInbandTrackInfo();
2688 synchronized (mIndexTrackPairs) {
2689 for (int i = 0; i < tracks.length; i++) {
2690 if (mInbandTrackIndices.get(i)) {
2693 mInbandTrackIndices.set(i);
2696 // newly appeared inband track
2697 if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
2698 SubtitleTrack track = mSubtitleController.addTrack(
2699 tracks[i].getFormat());
2700 mIndexTrackPairs.add(Pair.create(i, track));
2702 mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(i, null));
2708 /* TODO: Limit the total number of external timed text source to a reasonable number.
2711 * Adds an external timed text source file.
2713 * Currently supported format is SubRip with the file extension .srt, case insensitive.
2714 * Note that a single external timed text source may contain multiple tracks in it.
2715 * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
2716 * additional tracks become available after this method call.
2718 * @param path The file path of external timed text source file.
2719 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2720 * @throws IOException if the file cannot be accessed or is corrupted.
2721 * @throws IllegalArgumentException if the mimeType is not supported.
2722 * @throws IllegalStateException if called in an invalid state.
2724 public void addTimedTextSource(String path, String mimeType)
2725 throws IOException, IllegalArgumentException, IllegalStateException {
2726 if (!availableMimeTypeForExternalSource(mimeType)) {
2727 final String msg = "Illegal mimeType for timed text source: " + mimeType;
2728 throw new IllegalArgumentException(msg);
2731 File file = new File(path);
2732 if (file.exists()) {
2733 FileInputStream is = new FileInputStream(file);
2734 FileDescriptor fd = is.getFD();
2735 addTimedTextSource(fd, mimeType);
2738 // We do not support the case where the path is not a file.
2739 throw new IOException(path);
2744 * Adds an external timed text source file (Uri).
2746 * Currently supported format is SubRip with the file extension .srt, case insensitive.
2747 * Note that a single external timed text source may contain multiple tracks in it.
2748 * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
2749 * additional tracks become available after this method call.
2751 * @param context the Context to use when resolving the Uri
2752 * @param uri the Content URI of the data you want to play
2753 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2754 * @throws IOException if the file cannot be accessed or is corrupted.
2755 * @throws IllegalArgumentException if the mimeType is not supported.
2756 * @throws IllegalStateException if called in an invalid state.
2758 public void addTimedTextSource(Context context, Uri uri, String mimeType)
2759 throws IOException, IllegalArgumentException, IllegalStateException {
2760 String scheme = uri.getScheme();
2761 if(scheme == null || scheme.equals("file")) {
2762 addTimedTextSource(uri.getPath(), mimeType);
2766 AssetFileDescriptor fd = null;
2768 ContentResolver resolver = context.getContentResolver();
2769 fd = resolver.openAssetFileDescriptor(uri, "r");
2773 addTimedTextSource(fd.getFileDescriptor(), mimeType);
2775 } catch (SecurityException ex) {
2776 } catch (IOException ex) {
2785 * Adds an external timed text source file (FileDescriptor).
2787 * It is the caller's responsibility to close the file descriptor.
2788 * It is safe to do so as soon as this call returns.
2790 * Currently supported format is SubRip. Note that a single external timed text source may
2791 * contain multiple tracks in it. One can find the total number of available tracks
2792 * using {@link #getTrackInfo()} to see what additional tracks become available
2793 * after this method call.
2795 * @param fd the FileDescriptor for the file you want to play
2796 * @param mimeType The mime type of the file. Must be one of the mime types listed above.
2797 * @throws IllegalArgumentException if the mimeType is not supported.
2798 * @throws IllegalStateException if called in an invalid state.
2800 public void addTimedTextSource(FileDescriptor fd, String mimeType)
2801 throws IllegalArgumentException, IllegalStateException {
2802 // intentionally less than LONG_MAX
2803 addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
2807 * Adds an external timed text file (FileDescriptor).
2809 * It is the caller's responsibility to close the file descriptor.
2810 * It is safe to do so as soon as this call returns.
2812 * Currently supported format is SubRip. Note that a single external timed text source may
2813 * contain multiple tracks in it. One can find the total number of available tracks
2814 * using {@link #getTrackInfo()} to see what additional tracks become available
2815 * after this method call.
2817 * @param fd the FileDescriptor for the file you want to play
2818 * @param offset the offset into the file where the data to be played starts, in bytes
2819 * @param length the length in bytes of the data to be played
2820 * @param mime The mime type of the file. Must be one of the mime types listed above.
2821 * @throws IllegalArgumentException if the mimeType is not supported.
2822 * @throws IllegalStateException if called in an invalid state.
2824 public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mime)
2825 throws IllegalArgumentException, IllegalStateException {
2826 if (!availableMimeTypeForExternalSource(mime)) {
2827 throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mime);
2830 final FileDescriptor dupedFd;
2832 dupedFd = Libcore.os.dup(fd);
2833 } catch (ErrnoException ex) {
2834 Log.e(TAG, ex.getMessage(), ex);
2835 throw new RuntimeException(ex);
2838 final MediaFormat fFormat = new MediaFormat();
2839 fFormat.setString(MediaFormat.KEY_MIME, mime);
2840 fFormat.setInteger(MediaFormat.KEY_IS_TIMED_TEXT, 1);
2842 // A MediaPlayer created by a VideoView should already have its mSubtitleController set.
2843 if (mSubtitleController == null) {
2844 setSubtitleAnchor();
2847 if (!mSubtitleController.hasRendererFor(fFormat)) {
2848 // test and add not atomic
2849 Context context = ActivityThread.currentApplication();
2850 mSubtitleController.registerRenderer(new SRTRenderer(context, mEventHandler));
2852 final SubtitleTrack track = mSubtitleController.addTrack(fFormat);
2853 synchronized (mIndexTrackPairs) {
2854 mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(null, track));
2857 getMediaTimeProvider();
2859 final long offset2 = offset;
2860 final long length2 = length;
2861 final HandlerThread thread = new HandlerThread(
2862 "TimedTextReadThread",
2863 Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
2865 Handler handler = new Handler(thread.getLooper());
2866 handler.post(new Runnable() {
2867 private int addTrack() {
2868 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
2870 Libcore.os.lseek(dupedFd, offset2, OsConstants.SEEK_SET);
2871 byte[] buffer = new byte[4096];
2872 for (long total = 0; total < length2;) {
2873 int bytesToRead = (int) Math.min(buffer.length, length2 - total);
2874 int bytes = IoBridge.read(dupedFd, buffer, 0, bytesToRead);
2878 bos.write(buffer, 0, bytes);
2882 Handler h = mTimeProvider.mEventHandler;
2883 int what = TimeProvider.NOTIFY;
2884 int arg1 = TimeProvider.NOTIFY_TRACK_DATA;
2885 Pair<SubtitleTrack, byte[]> trackData = Pair.create(track, bos.toByteArray());
2886 Message m = h.obtainMessage(what, arg1, 0, trackData);
2888 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
2889 } catch (Exception e) {
2890 Log.e(TAG, e.getMessage(), e);
2891 return MEDIA_INFO_TIMED_TEXT_ERROR;
2894 Libcore.os.close(dupedFd);
2895 } catch (ErrnoException e) {
2896 Log.e(TAG, e.getMessage(), e);
2902 int res = addTrack();
2903 if (mEventHandler != null) {
2904 Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
2905 mEventHandler.sendMessage(m);
2907 thread.getLooper().quitSafely();
2913 * Returns the index of the audio, video, or subtitle track currently selected for playback,
2914 * The return value is an index into the array returned by {@link #getTrackInfo()}, and can
2915 * be used in calls to {@link #selectTrack(int)} or {@link #deselectTrack(int)}.
2917 * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
2918 * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
2919 * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
2920 * @return index of the audio, video, or subtitle track currently selected for playback;
2921 * a negative integer is returned when there is no selected track for {@code trackType} or
2922 * when {@code trackType} is not one of audio, video, or subtitle.
2923 * @throws IllegalStateException if called after {@link #release()}
2925 * @see #getTrackInfo()
2926 * @see #selectTrack(int)
2927 * @see #deselectTrack(int)
2929 public int getSelectedTrack(int trackType) throws IllegalStateException {
2930 if (mSubtitleController != null
2931 && (trackType == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE
2932 || trackType == TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT)) {
2933 SubtitleTrack subtitleTrack = mSubtitleController.getSelectedTrack();
2934 if (subtitleTrack != null) {
2935 synchronized (mIndexTrackPairs) {
2936 for (int i = 0; i < mIndexTrackPairs.size(); i++) {
2937 Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
2938 if (p.second == subtitleTrack && subtitleTrack.getTrackType() == trackType) {
2946 Parcel request = Parcel.obtain();
2947 Parcel reply = Parcel.obtain();
2949 request.writeInterfaceToken(IMEDIA_PLAYER);
2950 request.writeInt(INVOKE_ID_GET_SELECTED_TRACK);
2951 request.writeInt(trackType);
2952 invoke(request, reply);
2953 int inbandTrackIndex = reply.readInt();
2954 synchronized (mIndexTrackPairs) {
2955 for (int i = 0; i < mIndexTrackPairs.size(); i++) {
2956 Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
2957 if (p.first != null && p.first == inbandTrackIndex) {
2972 * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
2973 * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
2974 * If a MediaPlayer is not in Started state, it just marks the track to be played.
2977 * In any valid state, if it is called multiple times on the same type of track (ie. Video,
2978 * Audio, Timed Text), the most recent one will be chosen.
2981 * The first audio and video tracks are selected by default if available, even though
2982 * this method is not called. However, no timed text track will be selected until
2983 * this function is called.
2986 * Currently, only timed text tracks or audio tracks can be selected via this method.
2987 * In addition, the support for selecting an audio track at runtime is pretty limited
2988 * in that an audio track can only be selected in the <em>Prepared</em> state.
2990 * @param index the index of the track to be selected. The valid range of the index
2991 * is 0..total number of track - 1. The total number of tracks as well as the type of
2992 * each individual track can be found by calling {@link #getTrackInfo()} method.
2993 * @throws IllegalStateException if called in an invalid state.
2995 * @see android.media.MediaPlayer#getTrackInfo
2997 public void selectTrack(int index) throws IllegalStateException {
2998 selectOrDeselectTrack(index, true /* select */);
3004 * Currently, the track must be a timed text track and no audio or video tracks can be
3005 * deselected. If the timed text track identified by index has not been
3006 * selected before, it throws an exception.
3008 * @param index the index of the track to be deselected. The valid range of the index
3009 * is 0..total number of tracks - 1. The total number of tracks as well as the type of
3010 * each individual track can be found by calling {@link #getTrackInfo()} method.
3011 * @throws IllegalStateException if called in an invalid state.
3013 * @see android.media.MediaPlayer#getTrackInfo
3015 public void deselectTrack(int index) throws IllegalStateException {
3016 selectOrDeselectTrack(index, false /* select */);
3019 private void selectOrDeselectTrack(int index, boolean select)
3020 throws IllegalStateException {
3021 // handle subtitle track through subtitle controller
3022 populateInbandTracks();
3024 Pair<Integer,SubtitleTrack> p = null;
3026 p = mIndexTrackPairs.get(index);
3027 } catch (ArrayIndexOutOfBoundsException e) {
3032 SubtitleTrack track = p.second;
3033 if (track == null) {
3034 // inband (de)select
3035 selectOrDeselectInbandTrack(p.first, select);
3039 if (mSubtitleController == null) {
3044 // out-of-band deselect
3045 if (mSubtitleController.getSelectedTrack() == track) {
3046 mSubtitleController.selectTrack(null);
3048 Log.w(TAG, "trying to deselect track that was not selected");
3053 // out-of-band select
3054 if (track.getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT) {
3055 int ttIndex = getSelectedTrack(TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT);
3056 synchronized (mIndexTrackPairs) {
3057 if (ttIndex >= 0 && ttIndex < mIndexTrackPairs.size()) {
3058 Pair<Integer,SubtitleTrack> p2 = mIndexTrackPairs.get(ttIndex);
3059 if (p2.first != null && p2.second == null) {
3060 // deselect inband counterpart
3061 selectOrDeselectInbandTrack(p2.first, false);
3066 mSubtitleController.selectTrack(track);
3069 private void selectOrDeselectInbandTrack(int index, boolean select)
3070 throws IllegalStateException {
3071 Parcel request = Parcel.obtain();
3072 Parcel reply = Parcel.obtain();
3074 request.writeInterfaceToken(IMEDIA_PLAYER);
3075 request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
3076 request.writeInt(index);
3077 invoke(request, reply);
3086 * @param reply Parcel with audio/video duration info for battery
3088 * @return The status code.
3091 public native static int native_pullBatteryData(Parcel reply);
3094 * Sets the target UDP re-transmit endpoint for the low level player.
3095 * Generally, the address portion of the endpoint is an IP multicast
3096 * address, although a unicast address would be equally valid. When a valid
3097 * retransmit endpoint has been set, the media player will not decode and
3098 * render the media presentation locally. Instead, the player will attempt
3099 * to re-multiplex its media data using the Android@Home RTP profile and
3100 * re-transmit to the target endpoint. Receiver devices (which may be
3101 * either the same as the transmitting device or different devices) may
3102 * instantiate, prepare, and start a receiver player using a setDataSource
3103 * URL of the form...
3105 * aahRX://<multicastIP>:<port>
3107 * to receive, decode and render the re-transmitted content.
3109 * setRetransmitEndpoint may only be called before setDataSource has been
3110 * called; while the player is in the Idle state.
3112 * @param endpoint the address and UDP port of the re-transmission target or
3113 * null if no re-transmission is to be performed.
3114 * @throws IllegalStateException if it is called in an invalid state
3115 * @throws IllegalArgumentException if the retransmit endpoint is supplied,
3118 * {@hide} pending API council
3120 public void setRetransmitEndpoint(InetSocketAddress endpoint)
3121 throws IllegalStateException, IllegalArgumentException
3123 String addrString = null;
3126 if (null != endpoint) {
3127 addrString = endpoint.getAddress().getHostAddress();
3128 port = endpoint.getPort();
3131 int ret = native_setRetransmitEndpoint(addrString, port);
3133 throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
3137 private native final int native_setRetransmitEndpoint(String addrString, int port);
3140 protected void finalize() {
3145 /* Do not change these values without updating their counterparts
3146 * in include/media/mediaplayer.h!
3148 private static final int MEDIA_NOP = 0; // interface test message
3149 private static final int MEDIA_PREPARED = 1;
3150 private static final int MEDIA_PLAYBACK_COMPLETE = 2;
3151 private static final int MEDIA_BUFFERING_UPDATE = 3;
3152 private static final int MEDIA_SEEK_COMPLETE = 4;
3153 private static final int MEDIA_SET_VIDEO_SIZE = 5;
3154 private static final int MEDIA_STARTED = 6;
3155 private static final int MEDIA_PAUSED = 7;
3156 private static final int MEDIA_STOPPED = 8;
3157 private static final int MEDIA_SKIPPED = 9;
3158 private static final int MEDIA_TIMED_TEXT = 99;
3159 private static final int MEDIA_ERROR = 100;
3160 private static final int MEDIA_INFO = 200;
3161 private static final int MEDIA_SUBTITLE_DATA = 201;
3162 private static final int MEDIA_META_DATA = 202;
3163 private static final int MEDIA_DRM_INFO = 210;
3165 private TimeProvider mTimeProvider;
3168 public MediaTimeProvider getMediaTimeProvider() {
3169 if (mTimeProvider == null) {
3170 mTimeProvider = new TimeProvider(this);
3172 return mTimeProvider;
3175 private class EventHandler extends Handler
3177 private MediaPlayer mMediaPlayer;
3179 public EventHandler(MediaPlayer mp, Looper looper) {
3185 public void handleMessage(Message msg) {
3186 if (mMediaPlayer.mNativeContext == 0) {
3187 Log.w(TAG, "mediaplayer went away with unhandled events");
3191 case MEDIA_PREPARED:
3193 scanInternalSubtitleTracks();
3194 } catch (RuntimeException e) {
3195 // send error message instead of crashing;
3196 // send error message instead of inlining a call to onError
3197 // to avoid code duplication.
3198 Message msg2 = obtainMessage(
3199 MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_UNSUPPORTED, null);
3203 OnPreparedListener onPreparedListener = mOnPreparedListener;
3204 if (onPreparedListener != null)
3205 onPreparedListener.onPrepared(mMediaPlayer);
3208 case MEDIA_DRM_INFO:
3209 Log.v(TAG, "MEDIA_DRM_INFO " + mOnDrmInfoHandlerDelegate);
3211 if (msg.obj == null) {
3212 Log.w(TAG, "MEDIA_DRM_INFO msg.obj=NULL");
3213 } else if (msg.obj instanceof Parcel) {
3214 // The parcel was parsed already in postEventFromNative
3215 DrmInfo drmInfo = null;
3217 OnDrmInfoHandlerDelegate onDrmInfoHandlerDelegate;
3218 synchronized (mDrmLock) {
3219 if (mOnDrmInfoHandlerDelegate != null && mDrmInfo != null) {
3220 drmInfo = mDrmInfo.makeCopy();
3222 // local copy while keeping the lock
3223 onDrmInfoHandlerDelegate = mOnDrmInfoHandlerDelegate;
3226 // notifying the client outside the lock
3227 if (onDrmInfoHandlerDelegate != null) {
3228 onDrmInfoHandlerDelegate.notifyClient(drmInfo);
3231 Log.w(TAG, "MEDIA_DRM_INFO msg.obj of unexpected type " + msg.obj);
3235 case MEDIA_PLAYBACK_COMPLETE:
3237 mOnCompletionInternalListener.onCompletion(mMediaPlayer);
3238 OnCompletionListener onCompletionListener = mOnCompletionListener;
3239 if (onCompletionListener != null)
3240 onCompletionListener.onCompletion(mMediaPlayer);
3247 TimeProvider timeProvider = mTimeProvider;
3248 if (timeProvider != null) {
3249 timeProvider.onStopped();
3257 TimeProvider timeProvider = mTimeProvider;
3258 if (timeProvider != null) {
3259 timeProvider.onPaused(msg.what == MEDIA_PAUSED);
3264 case MEDIA_BUFFERING_UPDATE:
3265 OnBufferingUpdateListener onBufferingUpdateListener = mOnBufferingUpdateListener;
3266 if (onBufferingUpdateListener != null)
3267 onBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
3270 case MEDIA_SEEK_COMPLETE:
3271 OnSeekCompleteListener onSeekCompleteListener = mOnSeekCompleteListener;
3272 if (onSeekCompleteListener != null) {
3273 onSeekCompleteListener.onSeekComplete(mMediaPlayer);
3279 TimeProvider timeProvider = mTimeProvider;
3280 if (timeProvider != null) {
3281 timeProvider.onSeekComplete(mMediaPlayer);
3286 case MEDIA_SET_VIDEO_SIZE:
3287 OnVideoSizeChangedListener onVideoSizeChangedListener = mOnVideoSizeChangedListener;
3288 if (onVideoSizeChangedListener != null) {
3289 onVideoSizeChangedListener.onVideoSizeChanged(
3290 mMediaPlayer, msg.arg1, msg.arg2);
3295 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
3296 boolean error_was_handled = false;
3297 OnErrorListener onErrorListener = mOnErrorListener;
3298 if (onErrorListener != null) {
3299 error_was_handled = onErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
3302 mOnCompletionInternalListener.onCompletion(mMediaPlayer);
3303 OnCompletionListener onCompletionListener = mOnCompletionListener;
3304 if (onCompletionListener != null && ! error_was_handled) {
3305 onCompletionListener.onCompletion(mMediaPlayer);
3313 case MEDIA_INFO_VIDEO_TRACK_LAGGING:
3314 Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
3316 case MEDIA_INFO_METADATA_UPDATE:
3318 scanInternalSubtitleTracks();
3319 } catch (RuntimeException e) {
3320 Message msg2 = obtainMessage(
3321 MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_UNSUPPORTED, null);
3326 case MEDIA_INFO_EXTERNAL_METADATA_UPDATE:
3327 msg.arg1 = MEDIA_INFO_METADATA_UPDATE;
3328 // update default track selection
3329 if (mSubtitleController != null) {
3330 mSubtitleController.selectDefaultTrack();
3333 case MEDIA_INFO_BUFFERING_START:
3334 case MEDIA_INFO_BUFFERING_END:
3335 TimeProvider timeProvider = mTimeProvider;
3336 if (timeProvider != null) {
3337 timeProvider.onBuffering(msg.arg1 == MEDIA_INFO_BUFFERING_START);
3342 OnInfoListener onInfoListener = mOnInfoListener;
3343 if (onInfoListener != null) {
3344 onInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
3346 // No real default action so far.
3348 case MEDIA_TIMED_TEXT:
3349 OnTimedTextListener onTimedTextListener = mOnTimedTextListener;
3350 if (onTimedTextListener == null)
3352 if (msg.obj == null) {
3353 onTimedTextListener.onTimedText(mMediaPlayer, null);
3355 if (msg.obj instanceof Parcel) {
3356 Parcel parcel = (Parcel)msg.obj;
3357 TimedText text = new TimedText(parcel);
3359 onTimedTextListener.onTimedText(mMediaPlayer, text);
3364 case MEDIA_SUBTITLE_DATA:
3365 OnSubtitleDataListener onSubtitleDataListener = mOnSubtitleDataListener;
3366 if (onSubtitleDataListener == null) {
3369 if (msg.obj instanceof Parcel) {
3370 Parcel parcel = (Parcel) msg.obj;
3371 SubtitleData data = new SubtitleData(parcel);
3373 onSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
3377 case MEDIA_META_DATA:
3378 OnTimedMetaDataAvailableListener onTimedMetaDataAvailableListener =
3379 mOnTimedMetaDataAvailableListener;
3380 if (onTimedMetaDataAvailableListener == null) {
3383 if (msg.obj instanceof Parcel) {
3384 Parcel parcel = (Parcel) msg.obj;
3385 TimedMetaData data = TimedMetaData.createTimedMetaDataFromParcel(parcel);
3387 onTimedMetaDataAvailableListener.onTimedMetaDataAvailable(mMediaPlayer, data);
3391 case MEDIA_NOP: // interface test message - ignore
3395 Log.e(TAG, "Unknown message type " + msg.what);
3402 * Called from native code when an interesting event happens. This method
3403 * just uses the EventHandler system to post the event back to the main app thread.
3404 * We use a weak reference to the original MediaPlayer object so that the native
3405 * code is safe from the object disappearing from underneath it. (This is
3406 * the cookie passed to native_setup().)
3408 private static void postEventFromNative(Object mediaplayer_ref,
3409 int what, int arg1, int arg2, Object obj)
3411 final MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
3418 if (arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
3419 new Thread(new Runnable() {
3422 // this acquires the wakelock if needed, and sets the client side state
3430 case MEDIA_DRM_INFO:
3431 // We need to derive mDrmInfo before prepare() returns so processing it here
3432 // before the notification is sent to EventHandler below. EventHandler runs in the
3433 // notification looper so its handleMessage might process the event after prepare()
3435 Log.v(TAG, "postEventFromNative MEDIA_DRM_INFO");
3436 if (obj instanceof Parcel) {
3437 Parcel parcel = (Parcel)obj;
3438 DrmInfo drmInfo = new DrmInfo(parcel);
3439 synchronized (mp.mDrmLock) {
3440 mp.mDrmInfo = drmInfo;
3443 Log.w(TAG, "MEDIA_DRM_INFO msg.obj of unexpected type " + obj);
3447 case MEDIA_PREPARED:
3448 // By this time, we've learned about DrmInfo's presence or absence. This is meant
3449 // mainly for prepareAsync() use case. For prepare(), this still can run to a race
3450 // condition b/c MediaPlayerNative releases the prepare() lock before calling notify
3451 // so we also set mDrmInfoResolved in prepare().
3452 synchronized (mp.mDrmLock) {
3453 mp.mDrmInfoResolved = true;
3459 if (mp.mEventHandler != null) {
3460 Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
3461 mp.mEventHandler.sendMessage(m);
3466 * Interface definition for a callback to be invoked when the media
3467 * source is ready for playback.
3469 public interface OnPreparedListener
3472 * Called when the media file is ready for playback.
3474 * @param mp the MediaPlayer that is ready for playback
3476 void onPrepared(MediaPlayer mp);
3480 * Register a callback to be invoked when the media source is ready
3483 * @param listener the callback that will be run
3485 public void setOnPreparedListener(OnPreparedListener listener)
3487 mOnPreparedListener = listener;
3490 private OnPreparedListener mOnPreparedListener;
3493 * Interface definition for a callback to be invoked when playback of
3494 * a media source has completed.
3496 public interface OnCompletionListener
3499 * Called when the end of a media source is reached during playback.
3501 * @param mp the MediaPlayer that reached the end of the file
3503 void onCompletion(MediaPlayer mp);
3507 * Register a callback to be invoked when the end of a media source
3508 * has been reached during playback.
3510 * @param listener the callback that will be run
3512 public void setOnCompletionListener(OnCompletionListener listener)
3514 mOnCompletionListener = listener;
3517 private OnCompletionListener mOnCompletionListener;
3521 * Internal completion listener to update PlayerBase of the play state. Always "registered".
3523 private final OnCompletionListener mOnCompletionInternalListener = new OnCompletionListener() {
3525 public void onCompletion(MediaPlayer mp) {
3531 * Interface definition of a callback to be invoked indicating buffering
3532 * status of a media resource being streamed over the network.
3534 public interface OnBufferingUpdateListener
3537 * Called to update status in buffering a media stream received through
3538 * progressive HTTP download. The received buffering percentage
3539 * indicates how much of the content has been buffered or played.
3540 * For example a buffering update of 80 percent when half the content
3541 * has already been played indicates that the next 30 percent of the
3542 * content to play has been buffered.
3544 * @param mp the MediaPlayer the update pertains to
3545 * @param percent the percentage (0-100) of the content
3546 * that has been buffered or played thus far
3548 void onBufferingUpdate(MediaPlayer mp, int percent);
3552 * Register a callback to be invoked when the status of a network
3553 * stream's buffer has changed.
3555 * @param listener the callback that will be run.
3557 public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
3559 mOnBufferingUpdateListener = listener;
3562 private OnBufferingUpdateListener mOnBufferingUpdateListener;
3565 * Interface definition of a callback to be invoked indicating
3566 * the completion of a seek operation.
3568 public interface OnSeekCompleteListener
3571 * Called to indicate the completion of a seek operation.
3573 * @param mp the MediaPlayer that issued the seek operation
3575 public void onSeekComplete(MediaPlayer mp);
3579 * Register a callback to be invoked when a seek operation has been
3582 * @param listener the callback that will be run
3584 public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
3586 mOnSeekCompleteListener = listener;
3589 private OnSeekCompleteListener mOnSeekCompleteListener;
3592 * Interface definition of a callback to be invoked when the
3593 * video size is first known or updated
3595 public interface OnVideoSizeChangedListener
3598 * Called to indicate the video size
3600 * The video size (width and height) could be 0 if there was no video,
3601 * no display surface was set, or the value was not determined yet.
3603 * @param mp the MediaPlayer associated with this callback
3604 * @param width the width of the video
3605 * @param height the height of the video
3607 public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
3611 * Register a callback to be invoked when the video size is
3614 * @param listener the callback that will be run
3616 public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
3618 mOnVideoSizeChangedListener = listener;
3621 private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
3624 * Interface definition of a callback to be invoked when a
3625 * timed text is available for display.
3627 public interface OnTimedTextListener
3630 * Called to indicate an avaliable timed text
3632 * @param mp the MediaPlayer associated with this callback
3633 * @param text the timed text sample which contains the text
3634 * needed to be displayed and the display format.
3636 public void onTimedText(MediaPlayer mp, TimedText text);
3640 * Register a callback to be invoked when a timed text is available
3643 * @param listener the callback that will be run
3645 public void setOnTimedTextListener(OnTimedTextListener listener)
3647 mOnTimedTextListener = listener;
3650 private OnTimedTextListener mOnTimedTextListener;
3653 * Interface definition of a callback to be invoked when a
3654 * track has data available.
3658 public interface OnSubtitleDataListener
3660 public void onSubtitleData(MediaPlayer mp, SubtitleData data);
3664 * Register a callback to be invoked when a track has data available.
3666 * @param listener the callback that will be run
3670 public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
3672 mOnSubtitleDataListener = listener;
3675 private OnSubtitleDataListener mOnSubtitleDataListener;
3678 * Interface definition of a callback to be invoked when a
3679 * track has timed metadata available.
3681 * @see MediaPlayer#setOnTimedMetaDataAvailableListener(OnTimedMetaDataAvailableListener)
3683 public interface OnTimedMetaDataAvailableListener
3686 * Called to indicate avaliable timed metadata
3688 * This method will be called as timed metadata is extracted from the media,
3689 * in the same order as it occurs in the media. The timing of this event is
3690 * not controlled by the associated timestamp.
3692 * @param mp the MediaPlayer associated with this callback
3693 * @param data the timed metadata sample associated with this event
3695 public void onTimedMetaDataAvailable(MediaPlayer mp, TimedMetaData data);
3699 * Register a callback to be invoked when a selected track has timed metadata available.
3701 * Currently only HTTP live streaming data URI's embedded with timed ID3 tags generates
3702 * {@link TimedMetaData}.
3704 * @see MediaPlayer#selectTrack(int)
3705 * @see MediaPlayer.OnTimedMetaDataAvailableListener
3706 * @see TimedMetaData
3708 * @param listener the callback that will be run
3710 public void setOnTimedMetaDataAvailableListener(OnTimedMetaDataAvailableListener listener)
3712 mOnTimedMetaDataAvailableListener = listener;
3715 private OnTimedMetaDataAvailableListener mOnTimedMetaDataAvailableListener;
3717 /* Do not change these values without updating their counterparts
3718 * in include/media/mediaplayer.h!
3720 /** Unspecified media player error.
3721 * @see android.media.MediaPlayer.OnErrorListener
3723 public static final int MEDIA_ERROR_UNKNOWN = 1;
3725 /** Media server died. In this case, the application must release the
3726 * MediaPlayer object and instantiate a new one.
3727 * @see android.media.MediaPlayer.OnErrorListener
3729 public static final int MEDIA_ERROR_SERVER_DIED = 100;
3731 /** The video is streamed and its container is not valid for progressive
3732 * playback i.e the video's index (e.g moov atom) is not at the start of the
3734 * @see android.media.MediaPlayer.OnErrorListener
3736 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
3738 /** File or network related operation errors. */
3739 public static final int MEDIA_ERROR_IO = -1004;
3740 /** Bitstream is not conforming to the related coding standard or file spec. */
3741 public static final int MEDIA_ERROR_MALFORMED = -1007;
3742 /** Bitstream is conforming to the related coding standard or file spec, but
3743 * the media framework does not support the feature. */
3744 public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
3745 /** Some operation takes too long to complete, usually more than 3-5 seconds. */
3746 public static final int MEDIA_ERROR_TIMED_OUT = -110;
3748 /** Unspecified low-level system error. This value originated from UNKNOWN_ERROR in
3749 * system/core/include/utils/Errors.h
3750 * @see android.media.MediaPlayer.OnErrorListener
3753 public static final int MEDIA_ERROR_SYSTEM = -2147483648;
3756 * Interface definition of a callback to be invoked when there
3757 * has been an error during an asynchronous operation (other errors
3758 * will throw exceptions at method call time).
3760 public interface OnErrorListener
3763 * Called to indicate an error.
3765 * @param mp the MediaPlayer the error pertains to
3766 * @param what the type of error that has occurred:
3768 * <li>{@link #MEDIA_ERROR_UNKNOWN}
3769 * <li>{@link #MEDIA_ERROR_SERVER_DIED}
3771 * @param extra an extra code, specific to the error. Typically
3772 * implementation dependent.
3774 * <li>{@link #MEDIA_ERROR_IO}
3775 * <li>{@link #MEDIA_ERROR_MALFORMED}
3776 * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
3777 * <li>{@link #MEDIA_ERROR_TIMED_OUT}
3778 * <li><code>MEDIA_ERROR_SYSTEM (-2147483648)</code> - low-level system error.
3780 * @return True if the method handled the error, false if it didn't.
3781 * Returning false, or not having an OnErrorListener at all, will
3782 * cause the OnCompletionListener to be called.
3784 boolean onError(MediaPlayer mp, int what, int extra);
3788 * Register a callback to be invoked when an error has happened
3789 * during an asynchronous operation.
3791 * @param listener the callback that will be run
3793 public void setOnErrorListener(OnErrorListener listener)
3795 mOnErrorListener = listener;
3798 private OnErrorListener mOnErrorListener;
3801 /* Do not change these values without updating their counterparts
3802 * in include/media/mediaplayer.h!
3804 /** Unspecified media player info.
3805 * @see android.media.MediaPlayer.OnInfoListener
3807 public static final int MEDIA_INFO_UNKNOWN = 1;
3809 /** The player was started because it was used as the next player for another
3810 * player, which just completed playback.
3811 * @see android.media.MediaPlayer.OnInfoListener
3814 public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
3816 /** The player just pushed the very first video frame for rendering.
3817 * @see android.media.MediaPlayer.OnInfoListener
3819 public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
3821 /** The video is too complex for the decoder: it can't decode frames fast
3822 * enough. Possibly only the audio plays fine at this stage.
3823 * @see android.media.MediaPlayer.OnInfoListener
3825 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
3827 /** MediaPlayer is temporarily pausing playback internally in order to
3829 * @see android.media.MediaPlayer.OnInfoListener
3831 public static final int MEDIA_INFO_BUFFERING_START = 701;
3833 /** MediaPlayer is resuming playback after filling buffers.
3834 * @see android.media.MediaPlayer.OnInfoListener
3836 public static final int MEDIA_INFO_BUFFERING_END = 702;
3838 /** Estimated network bandwidth information (kbps) is available; currently this event fires
3839 * simultaneously as {@link #MEDIA_INFO_BUFFERING_START} and {@link #MEDIA_INFO_BUFFERING_END}
3840 * when playing network files.
3841 * @see android.media.MediaPlayer.OnInfoListener
3844 public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703;
3846 /** Bad interleaving means that a media has been improperly interleaved or
3847 * not interleaved at all, e.g has all the video samples first then all the
3848 * audio ones. Video is playing but a lot of disk seeks may be happening.
3849 * @see android.media.MediaPlayer.OnInfoListener
3851 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
3853 /** The media cannot be seeked (e.g live stream)
3854 * @see android.media.MediaPlayer.OnInfoListener
3856 public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
3858 /** A new set of metadata is available.
3859 * @see android.media.MediaPlayer.OnInfoListener
3861 public static final int MEDIA_INFO_METADATA_UPDATE = 802;
3863 /** A new set of external-only metadata is available. Used by
3864 * JAVA framework to avoid triggering track scanning.
3867 public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
3869 /** Informs that audio is not playing. Note that playback of the video
3870 * is not interrupted.
3871 * @see android.media.MediaPlayer.OnInfoListener
3873 public static final int MEDIA_INFO_AUDIO_NOT_PLAYING = 804;
3875 /** Informs that video is not playing. Note that playback of the audio
3876 * is not interrupted.
3877 * @see android.media.MediaPlayer.OnInfoListener
3879 public static final int MEDIA_INFO_VIDEO_NOT_PLAYING = 805;
3881 /** Failed to handle timed text track properly.
3882 * @see android.media.MediaPlayer.OnInfoListener
3886 public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
3888 /** Subtitle track was not supported by the media framework.
3889 * @see android.media.MediaPlayer.OnInfoListener
3891 public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
3893 /** Reading the subtitle track takes too long.
3894 * @see android.media.MediaPlayer.OnInfoListener
3896 public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
3899 * Interface definition of a callback to be invoked to communicate some
3900 * info and/or warning about the media or its playback.
3902 public interface OnInfoListener
3905 * Called to indicate an info or a warning.
3907 * @param mp the MediaPlayer the info pertains to.
3908 * @param what the type of info or warning.
3910 * <li>{@link #MEDIA_INFO_UNKNOWN}
3911 * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
3912 * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
3913 * <li>{@link #MEDIA_INFO_BUFFERING_START}
3914 * <li>{@link #MEDIA_INFO_BUFFERING_END}
3915 * <li><code>MEDIA_INFO_NETWORK_BANDWIDTH (703)</code> -
3916 * bandwidth information is available (as <code>extra</code> kbps)
3917 * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
3918 * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
3919 * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
3920 * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE}
3921 * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT}
3923 * @param extra an extra code, specific to the info. Typically
3924 * implementation dependent.
3925 * @return True if the method handled the info, false if it didn't.
3926 * Returning false, or not having an OnInfoListener at all, will
3927 * cause the info to be discarded.
3929 boolean onInfo(MediaPlayer mp, int what, int extra);
3933 * Register a callback to be invoked when an info/warning is available.
3935 * @param listener the callback that will be run
3937 public void setOnInfoListener(OnInfoListener listener)
3939 mOnInfoListener = listener;
3942 private OnInfoListener mOnInfoListener;
3944 // Modular DRM begin
3947 * Interface definition of a callback to be invoked when the app
3948 * can do DRM configuration (get/set properties) before the session
3949 * is opened. This facilitates configuration of the properties, like
3950 * 'securityLevel', which has to be set after DRM scheme creation but
3951 * before the DRM session is opened.
3953 * The only allowed DRM calls in this listener are {@code getDrmPropertyString}
3954 * and {@code setDrmPropertyString}.
3957 public interface OnDrmConfigHelper
3960 * Called to give the app the opportunity to configure DRM before the session is created
3962 * @param mp the {@code MediaPlayer} associated with this callback
3964 public void onDrmConfig(MediaPlayer mp);
3968 * Register a callback to be invoked for configuration of the DRM object before
3969 * the session is created.
3970 * The callback will be invoked synchronously during the execution
3971 * of {@link #prepareDrm(UUID uuid)}.
3973 * @param listener the callback that will be run
3975 public void setOnDrmConfigHelper(OnDrmConfigHelper listener)
3977 synchronized (mDrmLock) {
3978 mOnDrmConfigHelper = listener;
3982 private OnDrmConfigHelper mOnDrmConfigHelper;
3985 * Interface definition of a callback to be invoked when the
3986 * DRM info becomes available
3988 public interface OnDrmInfoListener
3991 * Called to indicate DRM info is available
3993 * @param mp the {@code MediaPlayer} associated with this callback
3994 * @param drmInfo DRM info of the source including PSSH, and subset
3995 * of crypto schemes supported by this device
3997 public void onDrmInfo(MediaPlayer mp, DrmInfo drmInfo);
4001 * Register a callback to be invoked when the DRM info is
4004 * @param listener the callback that will be run
4006 public void setOnDrmInfoListener(OnDrmInfoListener listener)
4008 setOnDrmInfoListener(listener, null);
4012 * Register a callback to be invoked when the DRM info is
4015 * @param listener the callback that will be run
4017 public void setOnDrmInfoListener(OnDrmInfoListener listener, Handler handler)
4019 synchronized (mDrmLock) {
4020 if (listener != null) {
4021 mOnDrmInfoHandlerDelegate = new OnDrmInfoHandlerDelegate(this, listener, handler);
4023 mOnDrmInfoHandlerDelegate = null;
4028 private OnDrmInfoHandlerDelegate mOnDrmInfoHandlerDelegate;
4032 * The status codes for {@link OnDrmPreparedListener#onDrmPrepared} listener.
4035 * DRM preparation has succeeded.
4037 public static final int PREPARE_DRM_STATUS_SUCCESS = 0;
4040 * The device required DRM provisioning but couldn't reach the provisioning server.
4042 public static final int PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR = 1;
4045 * The device required DRM provisioning but the provisioning server denied the request.
4047 public static final int PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR = 2;
4050 * The DRM preparation has failed .
4052 public static final int PREPARE_DRM_STATUS_PREPARATION_ERROR = 3;
4057 PREPARE_DRM_STATUS_SUCCESS,
4058 PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR,
4059 PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR,
4060 PREPARE_DRM_STATUS_PREPARATION_ERROR,
4062 @Retention(RetentionPolicy.SOURCE)
4063 public @interface PrepareDrmStatusCode {}
4066 * Interface definition of a callback to notify the app when the
4067 * DRM is ready for key request/response
4069 public interface OnDrmPreparedListener
4072 * Called to notify the app that prepareDrm is finished and ready for key request/response
4074 * @param mp the {@code MediaPlayer} associated with this callback
4075 * @param status the result of DRM preparation which can be
4076 * {@link #PREPARE_DRM_STATUS_SUCCESS},
4077 * {@link #PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR},
4078 * {@link #PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR}, or
4079 * {@link #PREPARE_DRM_STATUS_PREPARATION_ERROR}.
4081 public void onDrmPrepared(MediaPlayer mp, @PrepareDrmStatusCode int status);
4085 * Register a callback to be invoked when the DRM object is prepared.
4087 * @param listener the callback that will be run
4089 public void setOnDrmPreparedListener(OnDrmPreparedListener listener)
4091 setOnDrmPreparedListener(listener, null);
4095 * Register a callback to be invoked when the DRM object is prepared.
4097 * @param listener the callback that will be run
4098 * @param handler the Handler that will receive the callback
4100 public void setOnDrmPreparedListener(OnDrmPreparedListener listener, Handler handler)
4102 synchronized (mDrmLock) {
4103 if (listener != null) {
4104 mOnDrmPreparedHandlerDelegate = new OnDrmPreparedHandlerDelegate(this,
4107 mOnDrmPreparedHandlerDelegate = null;
4112 private OnDrmPreparedHandlerDelegate mOnDrmPreparedHandlerDelegate;
4115 private class OnDrmInfoHandlerDelegate {
4116 private MediaPlayer mMediaPlayer;
4117 private OnDrmInfoListener mOnDrmInfoListener;
4118 private Handler mHandler;
4120 OnDrmInfoHandlerDelegate(MediaPlayer mp, OnDrmInfoListener listener, Handler handler) {
4122 mOnDrmInfoListener = listener;
4124 // find the looper for our new event handler
4125 if (handler != null) {
4129 // Will let OnDrmInfoListener be called in mEventHandler similar to other
4130 // legacy notifications. This is because MEDIA_DRM_INFO's notification has to be
4131 // sent before MEDIA_PREPARED's (i.e., in the same order they are issued by
4132 // mediaserver). As a result, the callback has to be called directly by
4133 // EventHandler.handleMessage similar to onPrepared.
4137 void notifyClient(DrmInfo drmInfo) {
4138 if (mHandler != null) {
4139 mHandler.post(new Runnable() {
4142 mOnDrmInfoListener.onDrmInfo(mMediaPlayer, drmInfo);
4146 else { // no handler: direct call by mEventHandler
4147 mOnDrmInfoListener.onDrmInfo(mMediaPlayer, drmInfo);
4152 private class OnDrmPreparedHandlerDelegate {
4153 private MediaPlayer mMediaPlayer;
4154 private OnDrmPreparedListener mOnDrmPreparedListener;
4155 private Handler mHandler;
4157 OnDrmPreparedHandlerDelegate(MediaPlayer mp, OnDrmPreparedListener listener,
4160 mOnDrmPreparedListener = listener;
4162 // find the looper for our new event handler
4163 if (handler != null) {
4165 } else if (mEventHandler != null) {
4166 // Otherwise, use mEventHandler
4167 mHandler = mEventHandler;
4169 Log.e(TAG, "OnDrmPreparedHandlerDelegate: Unexpected null mEventHandler");
4173 void notifyClient(int status) {
4174 if (mHandler != null) {
4175 mHandler.post(new Runnable() {
4178 mOnDrmPreparedListener.onDrmPrepared(mMediaPlayer, status);
4182 Log.e(TAG, "OnDrmPreparedHandlerDelegate:notifyClient: Unexpected null mHandler");
4188 * Retrieves the DRM Info associated with the current source
4190 * @throws IllegalStateException if called before prepare()
4192 public DrmInfo getDrmInfo()
4194 DrmInfo drmInfo = null;
4196 // there is not much point if the app calls getDrmInfo within an OnDrmInfoListenet;
4197 // regardless below returns drmInfo anyway instead of raising an exception
4198 synchronized (mDrmLock) {
4199 if (!mDrmInfoResolved && mDrmInfo == null) {
4200 final String msg = "The Player has not been prepared yet";
4202 throw new IllegalStateException(msg);
4205 if (mDrmInfo != null) {
4206 drmInfo = mDrmInfo.makeCopy();
4215 * Prepares the DRM for the current source
4217 * If {@code OnDrmConfigHelper} is registered, it will be called during
4218 * preparation to allow configuration of the DRM properties before opening the
4219 * DRM session. Note that the callback is called synchronously in the thread that called
4220 * {@code prepareDrm}. It should be used only for a series of {@code getDrmPropertyString}
4221 * and {@code setDrmPropertyString} calls and refrain from any lengthy operation.
4223 * If the device has not been provisioned before, this call also provisions the device
4224 * which involves accessing the provisioning server and can take a variable time to
4225 * complete depending on the network connectivity.
4226 * If {@code OnDrmPreparedListener} is registered, prepareDrm() runs in non-blocking
4227 * mode by launching the provisioning in the background and returning. The listener
4228 * will be called when provisioning and preparation has finished. If a
4229 * {@code OnDrmPreparedListener} is not registered, prepareDrm() waits till provisioning
4230 * and preparation has finished, i.e., runs in blocking mode.
4232 * If {@code OnDrmPreparedListener} is registered, it is called to indicate the DRM
4233 * session being ready. The application should not make any assumption about its call
4234 * sequence (e.g., before or after prepareDrm returns), or the thread context that will
4235 * execute the listener (unless the listener is registered with a handler thread).
4238 * @param uuid The UUID of the crypto scheme. If not known beforehand, it can be retrieved
4239 * from the source through {@code getDrmInfo} or registering a {@code onDrmInfoListener}.
4241 * @throws IllegalStateException if called before prepare(), or the DRM was
4243 * @throws UnsupportedSchemeException if the crypto scheme is not supported
4244 * @throws ResourceBusyException if required DRM resources are in use
4245 * @throws ProvisioningNetworkErrorException if provisioning is required but failed due to a
4247 * @throws ProvisioningServerErrorException if provisioning is required but failed due to
4248 * the request denied by the provisioning server
4250 public void prepareDrm(@NonNull UUID uuid)
4251 throws UnsupportedSchemeException, ResourceBusyException,
4252 ProvisioningNetworkErrorException, ProvisioningServerErrorException
4254 Log.v(TAG, "prepareDrm: uuid: " + uuid + " mOnDrmConfigHelper: " + mOnDrmConfigHelper);
4256 boolean allDoneWithoutProvisioning = false;
4257 // get a snapshot as we'll use them outside the lock
4258 OnDrmPreparedHandlerDelegate onDrmPreparedHandlerDelegate = null;
4260 synchronized (mDrmLock) {
4262 // only allowing if tied to a protected source; might relax for releasing offline keys
4263 if (mDrmInfo == null) {
4264 final String msg = "prepareDrm(): Wrong usage: The player must be prepared and " +
4265 "DRM info be retrieved before this call.";
4267 throw new IllegalStateException(msg);
4270 if (mActiveDrmScheme) {
4271 final String msg = "prepareDrm(): Wrong usage: There is already " +
4272 "an active DRM scheme with " + mDrmUUID;
4274 throw new IllegalStateException(msg);
4277 if (mPrepareDrmInProgress) {
4278 final String msg = "prepareDrm(): Wrong usage: There is already " +
4279 "a pending prepareDrm call.";
4281 throw new IllegalStateException(msg);
4284 if (mDrmProvisioningInProgress) {
4285 final String msg = "prepareDrm(): Unexpectd: Provisioning is already in progress.";
4287 throw new IllegalStateException(msg);
4290 // shouldn't need this; just for safeguard
4293 mPrepareDrmInProgress = true;
4294 // local copy while the lock is held
4295 onDrmPreparedHandlerDelegate = mOnDrmPreparedHandlerDelegate;
4298 // only creating the DRM object to allow pre-openSession configuration
4299 prepareDrm_createDrmStep(uuid);
4300 } catch (Exception e) {
4301 Log.w(TAG, "prepareDrm(): Exception ", e);
4302 mPrepareDrmInProgress = false;
4306 mDrmConfigAllowed = true;
4310 // call the callback outside the lock
4311 if (mOnDrmConfigHelper != null) {
4312 mOnDrmConfigHelper.onDrmConfig(this);
4315 synchronized (mDrmLock) {
4316 mDrmConfigAllowed = false;
4317 boolean earlyExit = false;
4320 prepareDrm_openSessionStep(uuid);
4323 mActiveDrmScheme = true;
4325 allDoneWithoutProvisioning = true;
4326 } catch (IllegalStateException e) {
4327 final String msg = "prepareDrm(): Wrong usage: The player must be " +
4328 "in the prepared state to call prepareDrm().";
4331 throw new IllegalStateException(msg);
4332 } catch (NotProvisionedException e) {
4333 Log.w(TAG, "prepareDrm: NotProvisionedException");
4335 // handle provisioning internally; it'll reset mPrepareDrmInProgress
4336 int result = HandleProvisioninig(uuid);
4338 // if blocking mode, we're already done;
4339 // if non-blocking mode, we attempted to launch background provisioning
4340 if (result != PREPARE_DRM_STATUS_SUCCESS) {
4345 case PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR:
4346 msg = "prepareDrm: Provisioning was required but failed " +
4347 "due to a network error.";
4349 throw new ProvisioningNetworkErrorException(msg);
4351 case PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR:
4352 msg = "prepareDrm: Provisioning was required but the request " +
4353 "was denied by the server.";
4355 throw new ProvisioningServerErrorException(msg);
4357 case PREPARE_DRM_STATUS_PREPARATION_ERROR:
4358 default: // default for safeguard
4359 msg = "prepareDrm: Post-provisioning preparation failed.";
4361 throw new IllegalStateException(msg);
4364 // nothing else to do;
4365 // if blocking or non-blocking, HandleProvisioninig does the re-attempt & cleanup
4366 } catch (Exception e) {
4367 Log.e(TAG, "prepareDrm: Exception " + e);
4371 if (!mDrmProvisioningInProgress) {// if early exit other than provisioning exception
4372 mPrepareDrmInProgress = false;
4374 if (earlyExit) { // cleaning up object if didn't succeed
4381 // if finished successfully without provisioning, call the callback outside the lock
4382 if (allDoneWithoutProvisioning) {
4383 if (onDrmPreparedHandlerDelegate != null)
4384 onDrmPreparedHandlerDelegate.notifyClient(PREPARE_DRM_STATUS_SUCCESS);
4390 private native void _releaseDrm();
4393 * Releases the DRM session
4395 * The player has to have an active DRM session and be in stopped, or prepared
4396 * state before this call is made.
4397 * A {@code reset()} call will release the DRM session implicitly.
4399 * @throws NoDrmSchemeException if there is no active DRM session to release
4401 public void releaseDrm()
4402 throws NoDrmSchemeException
4404 Log.v(TAG, "releaseDrm:");
4406 synchronized (mDrmLock) {
4407 if (!mActiveDrmScheme) {
4408 Log.e(TAG, "releaseDrm(): No active DRM scheme to release.");
4409 throw new NoDrmSchemeException("releaseDrm: No active DRM scheme to release.");
4413 // we don't have the player's state in this layer. The below call raises
4414 // exception if we're in a non-stopped/prepared state.
4416 // for cleaning native/mediaserver crypto object
4419 // for cleaning client-side MediaDrm object; only called if above has succeeded
4422 mActiveDrmScheme = false;
4423 } catch (IllegalStateException e) {
4424 Log.w(TAG, "releaseDrm: Exception ", e);
4425 throw new IllegalStateException("releaseDrm: The player is not in a valid state.");
4426 } catch (Exception e) {
4427 Log.e(TAG, "releaseDrm: Exception ", e);
4434 * A key request/response exchange occurs between the app and a license server
4435 * to obtain or release keys used to decrypt encrypted content.
4437 * getKeyRequest() is used to obtain an opaque key request byte array that is
4438 * delivered to the license server. The opaque key request byte array is returned
4439 * in KeyRequest.data. The recommended URL to deliver the key request to is
4440 * returned in KeyRequest.defaultUrl.
4442 * After the app has received the key request response from the server,
4443 * it should deliver to the response to the DRM engine plugin using the method
4444 * {@link #provideKeyResponse}.
4446 * @param keySetId is the key-set identifier of the offline keys being released when keyType is
4447 * {@link MediaDrm#KEY_TYPE_RELEASE}. It should be set to null for other key requests, when
4448 * keyType is {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}.
4450 * @param initData is the container-specific initialization data when the keyType is
4451 * {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}. Its meaning is
4452 * interpreted based on the mime type provided in the mimeType parameter. It could
4453 * contain, for example, the content ID, key ID or other data obtained from the content
4454 * metadata that is required in generating the key request.
4455 * When the keyType is {@link MediaDrm#KEY_TYPE_RELEASE}, it should be set to null.
4457 * @param mimeType identifies the mime type of the content
4459 * @param keyType specifies the type of the request. The request may be to acquire
4460 * keys for streaming, {@link MediaDrm#KEY_TYPE_STREAMING}, or for offline content
4461 * {@link MediaDrm#KEY_TYPE_OFFLINE}, or to release previously acquired
4462 * keys ({@link MediaDrm#KEY_TYPE_RELEASE}), which are identified by a keySetId.
4464 * @param optionalParameters are included in the key request message to
4465 * allow a client application to provide additional message parameters to the server.
4466 * This may be {@code null} if no additional parameters are to be sent.
4468 * @throws NoDrmSchemeException if there is no active DRM session
4471 public MediaDrm.KeyRequest getKeyRequest(@Nullable byte[] keySetId, @Nullable byte[] initData,
4472 @Nullable String mimeType, @MediaDrm.KeyType int keyType,
4473 @Nullable Map<String, String> optionalParameters)
4474 throws NoDrmSchemeException
4476 Log.v(TAG, "getKeyRequest: " +
4477 " keySetId: " + keySetId + " initData:" + initData + " mimeType: " + mimeType +
4478 " keyType: " + keyType + " optionalParameters: " + optionalParameters);
4480 synchronized (mDrmLock) {
4481 if (!mActiveDrmScheme) {
4482 Log.e(TAG, "getKeyRequest NoDrmSchemeException");
4483 throw new NoDrmSchemeException("getKeyRequest: Has to set a DRM scheme first.");
4487 byte[] scope = (keyType != MediaDrm.KEY_TYPE_RELEASE) ?
4488 mDrmSessionId : // sessionId for KEY_TYPE_STREAMING/OFFLINE
4489 keySetId; // keySetId for KEY_TYPE_RELEASE
4491 HashMap<String, String> hmapOptionalParameters =
4492 (optionalParameters != null) ?
4493 new HashMap<String, String>(optionalParameters) :
4496 MediaDrm.KeyRequest request = mDrmObj.getKeyRequest(scope, initData, mimeType,
4497 keyType, hmapOptionalParameters);
4498 Log.v(TAG, "getKeyRequest: --> request: " + request);
4502 } catch (NotProvisionedException e) {
4503 Log.w(TAG, "getKeyRequest NotProvisionedException: " +
4504 "Unexpected. Shouldn't have reached here.");
4505 throw new IllegalStateException("getKeyRequest: Unexpected provisioning error.");
4506 } catch (Exception e) {
4507 Log.w(TAG, "getKeyRequest Exception " + e);
4516 * A key response is received from the license server by the app, then it is
4517 * provided to the DRM engine plugin using provideKeyResponse. When the
4518 * response is for an offline key request, a key-set identifier is returned that
4519 * can be used to later restore the keys to a new session with the method
4520 * {@ link # restoreKeys}.
4521 * When the response is for a streaming or release request, null is returned.
4523 * @param keySetId When the response is for a release request, keySetId identifies
4524 * the saved key associated with the release request (i.e., the same keySetId
4525 * passed to the earlier {@ link # getKeyRequest} call. It MUST be null when the
4526 * response is for either streaming or offline key requests.
4528 * @param response the byte array response from the server
4530 * @throws NoDrmSchemeException if there is no active DRM session
4531 * @throws DeniedByServerException if the response indicates that the
4532 * server rejected the request
4534 public byte[] provideKeyResponse(@Nullable byte[] keySetId, @NonNull byte[] response)
4535 throws NoDrmSchemeException, DeniedByServerException
4537 Log.v(TAG, "provideKeyResponse: keySetId: " + keySetId + " response: " + response);
4539 synchronized (mDrmLock) {
4541 if (!mActiveDrmScheme) {
4542 Log.e(TAG, "getKeyRequest NoDrmSchemeException");
4543 throw new NoDrmSchemeException("getKeyRequest: Has to set a DRM scheme first.");
4547 byte[] scope = (keySetId == null) ?
4548 mDrmSessionId : // sessionId for KEY_TYPE_STREAMING/OFFLINE
4549 keySetId; // keySetId for KEY_TYPE_RELEASE
4551 byte[] keySetResult = mDrmObj.provideKeyResponse(scope, response);
4553 Log.v(TAG, "provideKeyResponse: keySetId: " + keySetId + " response: " + response +
4554 " --> " + keySetResult);
4557 return keySetResult;
4559 } catch (NotProvisionedException e) {
4560 Log.w(TAG, "provideKeyResponse NotProvisionedException: " +
4561 "Unexpected. Shouldn't have reached here.");
4562 throw new IllegalStateException("provideKeyResponse: " +
4563 "Unexpected provisioning error.");
4564 } catch (Exception e) {
4565 Log.w(TAG, "provideKeyResponse Exception " + e);
4573 * Restore persisted offline keys into a new session. keySetId identifies the
4574 * keys to load, obtained from a prior call to {@link #provideKeyResponse}.
4576 * @param keySetId identifies the saved key set to restore
4578 public void restoreKeys(@NonNull byte[] keySetId)
4579 throws NoDrmSchemeException
4581 Log.v(TAG, "restoreKeys: keySetId: " + keySetId);
4583 synchronized (mDrmLock) {
4585 if (!mActiveDrmScheme) {
4586 Log.w(TAG, "restoreKeys NoDrmSchemeException");
4587 throw new NoDrmSchemeException("restoreKeys: Has to set a DRM scheme first.");
4591 mDrmObj.restoreKeys(mDrmSessionId, keySetId);
4592 } catch (Exception e) {
4593 Log.w(TAG, "restoreKeys Exception " + e);
4602 * Read a DRM engine plugin String property value, given the property name string.
4604 * @param propertyName the property name
4606 * Standard fields names are:
4607 * {@link MediaDrm#PROPERTY_VENDOR}, {@link MediaDrm#PROPERTY_VERSION},
4608 * {@link MediaDrm#PROPERTY_DESCRIPTION}, {@link MediaDrm#PROPERTY_ALGORITHMS}
4611 public String getDrmPropertyString(@NonNull @MediaDrm.StringProperty String propertyName)
4612 throws NoDrmSchemeException
4614 Log.v(TAG, "getDrmPropertyString: propertyName: " + propertyName);
4617 synchronized (mDrmLock) {
4619 if (!mActiveDrmScheme && !mDrmConfigAllowed) {
4620 Log.w(TAG, "getDrmPropertyString NoDrmSchemeException");
4621 throw new NoDrmSchemeException("getDrmPropertyString: Has to prepareDrm() first.");
4625 value = mDrmObj.getPropertyString(propertyName);
4626 } catch (Exception e) {
4627 Log.w(TAG, "getDrmPropertyString Exception " + e);
4632 Log.v(TAG, "getDrmPropertyString: propertyName: " + propertyName + " --> value: " + value);
4639 * Set a DRM engine plugin String property value.
4641 * @param propertyName the property name
4642 * @param value the property value
4644 * Standard fields names are:
4645 * {@link MediaDrm#PROPERTY_VENDOR}, {@link MediaDrm#PROPERTY_VERSION},
4646 * {@link MediaDrm#PROPERTY_DESCRIPTION}, {@link MediaDrm#PROPERTY_ALGORITHMS}
4648 public void setDrmPropertyString(@NonNull @MediaDrm.StringProperty String propertyName,
4649 @NonNull String value)
4650 throws NoDrmSchemeException
4652 Log.v(TAG, "setDrmPropertyString: propertyName: " + propertyName + " value: " + value);
4654 synchronized (mDrmLock) {
4656 if ( !mActiveDrmScheme && !mDrmConfigAllowed ) {
4657 Log.w(TAG, "setDrmPropertyString NoDrmSchemeException");
4658 throw new NoDrmSchemeException("setDrmPropertyString: Has to prepareDrm() first.");
4662 mDrmObj.setPropertyString(propertyName, value);
4663 } catch ( Exception e ) {
4664 Log.w(TAG, "setDrmPropertyString Exception " + e);
4671 * Encapsulates the DRM properties of the source.
4673 public static final class DrmInfo {
4674 private Map<UUID, byte[]> mapPssh;
4675 private UUID[] supportedSchemes;
4678 * Returns the PSSH info of the data source for each supported DRM scheme.
4680 public Map<UUID, byte[]> getPssh() {
4685 * Returns the intersection of the data source and the device DRM schemes.
4686 * It effectively identifies the subset of the source's DRM schemes which
4687 * are supported by the device too.
4689 public UUID[] getSupportedSchemes() {
4690 return supportedSchemes;
4693 private DrmInfo(Map<UUID, byte[]> Pssh, UUID[] SupportedSchemes) {
4695 supportedSchemes = SupportedSchemes;
4698 private DrmInfo(Parcel parcel) {
4699 Log.v(TAG, "DrmInfo(" + parcel + ") size " + parcel.dataSize());
4701 int psshsize = parcel.readInt();
4702 byte[] pssh = new byte[psshsize];
4703 parcel.readByteArray(pssh);
4705 Log.v(TAG, "DrmInfo() PSSH: " + arrToHex(pssh));
4706 mapPssh = parsePSSH(pssh, psshsize);
4707 Log.v(TAG, "DrmInfo() PSSH: " + mapPssh);
4709 int supportedDRMsCount = parcel.readInt();
4710 supportedSchemes = new UUID[supportedDRMsCount];
4711 for (int i = 0; i < supportedDRMsCount; i++) {
4712 byte[] uuid = new byte[16];
4713 parcel.readByteArray(uuid);
4715 supportedSchemes[i] = bytesToUUID(uuid);
4717 Log.v(TAG, "DrmInfo() supportedScheme[" + i + "]: " +
4718 supportedSchemes[i]);
4721 Log.v(TAG, "DrmInfo() Parcel psshsize: " + psshsize +
4722 " supportedDRMsCount: " + supportedDRMsCount);
4725 private DrmInfo makeCopy() {
4726 return new DrmInfo(this.mapPssh, this.supportedSchemes);
4729 private String arrToHex(byte[] bytes) {
4731 for (int i = 0; i < bytes.length; i++) {
4732 out += String.format("%02x", bytes[i]);
4738 private UUID bytesToUUID(byte[] uuid) {
4739 long msb = 0, lsb = 0;
4740 for (int i = 0; i < 8; i++) {
4741 msb |= ( ((long)uuid[i] & 0xff) << (8 * (7 - i)) );
4742 lsb |= ( ((long)uuid[i+8] & 0xff) << (8 * (7 - i)) );
4745 return new UUID(msb, lsb);
4748 private Map<UUID, byte[]> parsePSSH(byte[] pssh, int psshsize) {
4749 Map<UUID, byte[]> result = new HashMap<UUID, byte[]>();
4751 final int UUID_SIZE = 16;
4752 final int DATALEN_SIZE = 4;
4759 if (len < UUID_SIZE) {
4760 Log.w(TAG, String.format("parsePSSH: len is too short to parse " +
4761 "UUID: (%d < 16) pssh: %d", len, psshsize));
4765 byte[] subset = Arrays.copyOfRange(pssh, i, i + UUID_SIZE);
4766 UUID uuid = bytesToUUID(subset);
4772 Log.w(TAG, String.format("parsePSSH: len is too short to parse " +
4773 "datalen: (%d < 4) pssh: %d", len, psshsize));
4777 subset = Arrays.copyOfRange(pssh, i, i+DATALEN_SIZE);
4778 int datalen = (ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN) ?
4779 ((subset[3] & 0xff) << 24) | ((subset[2] & 0xff) << 16) |
4780 ((subset[1] & 0xff) << 8) | (subset[0] & 0xff) :
4781 ((subset[0] & 0xff) << 24) | ((subset[1] & 0xff) << 16) |
4782 ((subset[2] & 0xff) << 8) | (subset[3] & 0xff) ;
4784 len -= DATALEN_SIZE;
4786 if (len < datalen) {
4787 Log.w(TAG, String.format("parsePSSH: len is too short to parse " +
4788 "data: (%d < %d) pssh: %d", len, datalen, psshsize));
4792 byte[] data = Arrays.copyOfRange(pssh, i, i+datalen);
4798 Log.v(TAG, String.format("parsePSSH[%d]: <%s, %s> pssh: %d",
4799 numentries, uuid, arrToHex(data), psshsize));
4801 result.put(uuid, data);
4810 * Thrown when a DRM method is called before preparing a DRM scheme through prepareDrm().
4811 * Extends MediaDrm.MediaDrmException
4813 public static final class NoDrmSchemeException extends MediaDrmException {
4814 public NoDrmSchemeException(String detailMessage) {
4815 super(detailMessage);
4820 * Thrown when the device requires DRM provisioning but the provisioning attempt has
4821 * failed due to a network error (Internet reachability, timeout, etc.).
4822 * Extends MediaDrm.MediaDrmException
4824 public static final class ProvisioningNetworkErrorException extends MediaDrmException {
4825 public ProvisioningNetworkErrorException(String detailMessage) {
4826 super(detailMessage);
4831 * Thrown when the device requires DRM provisioning but the provisioning attempt has
4832 * failed due to the provisioning server denying the request.
4833 * Extends MediaDrm.MediaDrmException
4835 public static final class ProvisioningServerErrorException extends MediaDrmException {
4836 public ProvisioningServerErrorException(String detailMessage) {
4837 super(detailMessage);
4842 private native void _prepareDrm(@NonNull byte[] uuid, @NonNull byte[] drmSessionId);
4844 // Modular DRM helpers
4846 private void prepareDrm_createDrmStep(@NonNull UUID uuid)
4847 throws UnsupportedSchemeException {
4848 Log.v(TAG, "prepareDrm_createDrmStep: UUID: " + uuid);
4851 mDrmObj = new MediaDrm(uuid);
4852 Log.v(TAG, "prepareDrm_createDrmStep: Created mDrmObj=" + mDrmObj);
4853 } catch (Exception e) { // UnsupportedSchemeException
4854 Log.e(TAG, "prepareDrm_createDrmStep: MediaDrm failed with " + e);
4859 private void prepareDrm_openSessionStep(@NonNull UUID uuid)
4860 throws NotProvisionedException, ResourceBusyException {
4861 Log.v(TAG, "prepareDrm_openSessionStep: uuid: " + uuid);
4863 // TODO: don't need an open session for a future specialKeyReleaseDrm mode but we should do
4864 // it anyway so it raises provisioning error if needed. We'd rather handle provisioning
4865 // at prepareDrm/openSession rather than getKeyRequest/provideKeyResponse
4867 mDrmSessionId = mDrmObj.openSession();
4868 Log.v(TAG, "prepareDrm_openSessionStep: mDrmSessionId=" + mDrmSessionId);
4870 // Sending it down to native/mediaserver to create the crypto object
4871 // This call could simply fail due to bad player state, e.g., after start().
4872 _prepareDrm(getByteArrayFromUUID(uuid), mDrmSessionId);
4873 Log.v(TAG, "prepareDrm_openSessionStep: _prepareDrm/Crypto succeeded");
4875 } catch (Exception e) { //ResourceBusyException, NotProvisionedException
4876 Log.e(TAG, "prepareDrm_openSessionStep: open/crypto failed with " + e);
4882 private class ProvisioningThread extends Thread
4884 public static final int TIMEOUT_MS = 60000;
4887 private String urlStr;
4888 private Object drmLock;
4889 private OnDrmPreparedHandlerDelegate onDrmPreparedHandlerDelegate;
4890 private MediaPlayer mediaPlayer;
4892 private boolean finished;
4893 public int status() {
4897 public ProvisioningThread initialize(MediaDrm.ProvisionRequest request,
4898 UUID uuid, MediaPlayer mediaPlayer) {
4899 // lock is held by the caller
4900 drmLock = mediaPlayer.mDrmLock;
4901 onDrmPreparedHandlerDelegate = mediaPlayer.mOnDrmPreparedHandlerDelegate;
4902 this.mediaPlayer = mediaPlayer;
4904 urlStr = request.getDefaultUrl() + "&signedRequest=" + new String(request.getData());
4907 status = PREPARE_DRM_STATUS_PREPARATION_ERROR;
4909 Log.v(TAG, "HandleProvisioninig: Thread is initialised url: " + urlStr);
4915 byte[] response = null;
4916 boolean provisioningSucceeded = false;
4918 URL url = new URL(urlStr);
4919 final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
4921 connection.setRequestMethod("POST");
4922 connection.setDoOutput(false);
4923 connection.setDoInput(true);
4924 connection.setConnectTimeout(TIMEOUT_MS);
4925 connection.setReadTimeout(TIMEOUT_MS);
4927 connection.connect();
4928 response = Streams.readFully(connection.getInputStream());
4930 Log.v(TAG, "HandleProvisioninig: Thread run: response " +
4931 response.length + " " + response);
4932 } catch (Exception e) {
4933 status = PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR;
4934 Log.w(TAG, "HandleProvisioninig: Thread run: connect " + e + " url: " + url);
4936 connection.disconnect();
4938 } catch (Exception e) {
4939 status = PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR;
4940 Log.w(TAG, "HandleProvisioninig: Thread run: openConnection " + e);
4943 if (response != null) {
4945 mDrmObj.provideProvisionResponse(response);
4946 Log.v(TAG, "HandleProvisioninig: Thread run: " +
4947 "provideProvisionResponse SUCCEEDED!");
4949 provisioningSucceeded = true;
4950 } catch (Exception e) {
4951 status = PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR;
4952 Log.w(TAG, "HandleProvisioninig: Thread run: " +
4953 "provideProvisionResponse " + e);
4957 boolean succeeded = false;
4959 // non-blocking mode needs the lock
4960 if (onDrmPreparedHandlerDelegate != null) {
4962 synchronized (drmLock) {
4963 // continuing with prepareDrm
4964 if (provisioningSucceeded) {
4965 succeeded = mediaPlayer.resumePrepareDrm(uuid);
4966 status = (succeeded) ?
4967 PREPARE_DRM_STATUS_SUCCESS :
4968 PREPARE_DRM_STATUS_PREPARATION_ERROR;
4970 mediaPlayer.mDrmProvisioningInProgress = false;
4971 mediaPlayer.mPrepareDrmInProgress = false;
4973 cleanDrmObj(); // cleaning up if it hasn't gone through while in the lock
4977 // calling the callback outside the lock
4978 onDrmPreparedHandlerDelegate.notifyClient(status);
4979 } else { // blocking mode already has the lock
4981 // continuing with prepareDrm
4982 if (provisioningSucceeded) {
4983 succeeded = mediaPlayer.resumePrepareDrm(uuid);
4984 status = (succeeded) ?
4985 PREPARE_DRM_STATUS_SUCCESS :
4986 PREPARE_DRM_STATUS_PREPARATION_ERROR;
4988 mediaPlayer.mDrmProvisioningInProgress = false;
4989 mediaPlayer.mPrepareDrmInProgress = false;
4991 cleanDrmObj(); // cleaning up if it hasn't gone through
4998 } // ProvisioningThread
5000 private int HandleProvisioninig(UUID uuid)
5002 // the lock is already held by the caller
5004 if (mDrmProvisioningInProgress) {
5005 Log.e(TAG, "HandleProvisioninig: Unexpected mDrmProvisioningInProgress");
5006 return PREPARE_DRM_STATUS_PREPARATION_ERROR;
5009 MediaDrm.ProvisionRequest provReq = mDrmObj.getProvisionRequest();
5010 if (provReq == null) {
5011 Log.e(TAG, "HandleProvisioninig: getProvisionRequest returned null.");
5012 return PREPARE_DRM_STATUS_PREPARATION_ERROR;
5015 Log.v(TAG, "HandleProvisioninig provReq " +
5016 " data: " + provReq.getData() + " url: " + provReq.getDefaultUrl());
5018 // networking in a background thread
5019 mDrmProvisioningInProgress = true;
5021 mDrmProvisioningThread = new ProvisioningThread().initialize(provReq, uuid, this);
5022 mDrmProvisioningThread.start();
5026 // non-blocking: this is not the final result
5027 if (mOnDrmPreparedHandlerDelegate != null) {
5028 result = PREPARE_DRM_STATUS_SUCCESS;
5030 // if blocking mode, wait till provisioning is done
5032 mDrmProvisioningThread.join();
5033 } catch (Exception e) {
5034 Log.w(TAG, "HandleProvisioninig: Thread.join Exception " + e);
5036 result = mDrmProvisioningThread.status();
5037 // no longer need the thread
5038 mDrmProvisioningThread = null;
5044 private boolean resumePrepareDrm(UUID uuid)
5046 Log.v(TAG, "resumePrepareDrm: uuid: " + uuid);
5048 // mDrmLock is guaranteed to be held
5049 boolean success = false;
5052 prepareDrm_openSessionStep(uuid);
5055 mActiveDrmScheme = true;
5058 } catch (Exception e) {
5059 Log.w(TAG, "HandleProvisioninig: Thread run _prepareDrm resume failed with " + e);
5060 // mDrmObj clean up is done by the caller
5066 private void resetDrmState()
5068 synchronized (mDrmLock) {
5069 Log.v(TAG, "resetDrmState: " +
5070 " mDrmInfo=" + mDrmInfo +
5071 " mDrmProvisioningThread=" + mDrmProvisioningThread +
5072 " mPrepareDrmInProgress=" + mPrepareDrmInProgress +
5073 " mActiveDrmScheme=" + mActiveDrmScheme);
5075 mDrmInfoResolved = false;
5078 if (mDrmProvisioningThread != null) {
5079 // timeout; relying on HttpUrlConnection
5081 mDrmProvisioningThread.join();
5083 catch (InterruptedException e) {
5084 Log.w(TAG, "resetDrmState: ProvThread.join Exception " + e);
5086 mDrmProvisioningThread = null;
5089 mPrepareDrmInProgress = false;
5090 mActiveDrmScheme = false;
5096 private void cleanDrmObj()
5098 // the caller holds mDrmLock
5099 Log.v(TAG, "cleanDrmObj: mDrmObj=" + mDrmObj + " mDrmSessionId=" + mDrmSessionId);
5101 if (mDrmSessionId != null) {
5102 mDrmObj.closeSession(mDrmSessionId);
5103 mDrmSessionId = null;
5105 if (mDrmObj != null) {
5111 private static final byte[] getByteArrayFromUUID(@NonNull UUID uuid) {
5112 long msb = uuid.getMostSignificantBits();
5113 long lsb = uuid.getLeastSignificantBits();
5115 byte[] uuidBytes = new byte[16];
5116 for (int i = 0; i < 8; ++i) {
5117 uuidBytes[i] = (byte)(msb >>> (8 * (7 - i)));
5118 uuidBytes[8 + i] = (byte)(lsb >>> (8 * (7 - i)));
5127 * Test whether a given video scaling mode is supported.
5129 private boolean isVideoScalingModeSupported(int mode) {
5130 return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
5131 mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
5135 static class TimeProvider implements MediaPlayer.OnSeekCompleteListener,
5137 private static final String TAG = "MTP";
5138 private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L;
5139 private static final long MAX_EARLY_CALLBACK_US = 1000;
5140 private static final long TIME_ADJUSTMENT_RATE = 2; /* meaning 1/2 */
5141 private long mLastTimeUs = 0;
5142 private MediaPlayer mPlayer;
5143 private boolean mPaused = true;
5144 private boolean mStopped = true;
5145 private boolean mBuffering;
5146 private long mLastReportedTime;
5147 private long mTimeAdjustment;
5148 // since we are expecting only a handful listeners per stream, there is
5149 // no need for log(N) search performance
5150 private MediaTimeProvider.OnMediaTimeListener mListeners[];
5151 private long mTimes[];
5152 private long mLastNanoTime;
5153 private Handler mEventHandler;
5154 private boolean mRefresh = false;
5155 private boolean mPausing = false;
5156 private boolean mSeeking = false;
5157 private static final int NOTIFY = 1;
5158 private static final int NOTIFY_TIME = 0;
5159 private static final int REFRESH_AND_NOTIFY_TIME = 1;
5160 private static final int NOTIFY_STOP = 2;
5161 private static final int NOTIFY_SEEK = 3;
5162 private static final int NOTIFY_TRACK_DATA = 4;
5163 private HandlerThread mHandlerThread;
5166 public boolean DEBUG = false;
5168 public TimeProvider(MediaPlayer mp) {
5171 getCurrentTimeUs(true, false);
5172 } catch (IllegalStateException e) {
5173 // we assume starting position
5178 if ((looper = Looper.myLooper()) == null &&
5179 (looper = Looper.getMainLooper()) == null) {
5180 // Create our own looper here in case MP was created without one
5181 mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread",
5182 Process.THREAD_PRIORITY_FOREGROUND);
5183 mHandlerThread.start();
5184 looper = mHandlerThread.getLooper();
5186 mEventHandler = new EventHandler(looper);
5188 mListeners = new MediaTimeProvider.OnMediaTimeListener[0];
5189 mTimes = new long[0];
5191 mTimeAdjustment = 0;
5194 private void scheduleNotification(int type, long delayUs) {
5195 // ignore time notifications until seek is handled
5197 (type == NOTIFY_TIME || type == REFRESH_AND_NOTIFY_TIME)) {
5201 if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs);
5202 mEventHandler.removeMessages(NOTIFY);
5203 Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0);
5204 mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000));
5208 public void close() {
5209 mEventHandler.removeMessages(NOTIFY);
5210 if (mHandlerThread != null) {
5211 mHandlerThread.quitSafely();
5212 mHandlerThread = null;
5217 protected void finalize() {
5218 if (mHandlerThread != null) {
5219 mHandlerThread.quitSafely();
5224 public void onPaused(boolean paused) {
5225 synchronized(this) {
5226 if (DEBUG) Log.d(TAG, "onPaused: " + paused);
5227 if (mStopped) { // handle as seek if we were stopped
5230 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
5232 mPausing = paused; // special handling if player disappeared
5234 scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
5240 public void onBuffering(boolean buffering) {
5241 synchronized (this) {
5242 if (DEBUG) Log.d(TAG, "onBuffering: " + buffering);
5243 mBuffering = buffering;
5244 scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
5249 public void onStopped() {
5250 synchronized(this) {
5251 if (DEBUG) Log.d(TAG, "onStopped");
5256 scheduleNotification(NOTIFY_STOP, 0 /* delay */);
5262 public void onSeekComplete(MediaPlayer mp) {
5263 synchronized(this) {
5266 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
5271 public void onNewPlayer() {
5273 synchronized(this) {
5277 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
5282 private synchronized void notifySeek() {
5285 long timeUs = getCurrentTimeUs(true, false);
5286 if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs);
5288 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
5289 if (listener == null) {
5292 listener.onSeek(timeUs);
5294 } catch (IllegalStateException e) {
5295 // we should not be there, but at least signal pause
5296 if (DEBUG) Log.d(TAG, "onSeekComplete but no player");
5297 mPausing = true; // special handling if player disappeared
5298 notifyTimedEvent(false /* refreshTime */);
5302 private synchronized void notifyTrackData(Pair<SubtitleTrack, byte[]> trackData) {
5303 SubtitleTrack track = trackData.first;
5304 byte[] data = trackData.second;
5305 track.onData(data, true /* eos */, ~0 /* runID: keep forever */);
5308 private synchronized void notifyStop() {
5309 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
5310 if (listener == null) {
5317 private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) {
5319 for (; i < mListeners.length; i++) {
5320 if (mListeners[i] == listener || mListeners[i] == null) {
5326 if (i >= mListeners.length) {
5327 MediaTimeProvider.OnMediaTimeListener[] newListeners =
5328 new MediaTimeProvider.OnMediaTimeListener[i + 1];
5329 long[] newTimes = new long[i + 1];
5330 System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length);
5331 System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length);
5332 mListeners = newListeners;
5336 if (mListeners[i] == null) {
5337 mListeners[i] = listener;
5338 mTimes[i] = MediaTimeProvider.NO_TIME;
5343 public void notifyAt(
5344 long timeUs, MediaTimeProvider.OnMediaTimeListener listener) {
5345 synchronized(this) {
5346 if (DEBUG) Log.d(TAG, "notifyAt " + timeUs);
5347 mTimes[registerListener(listener)] = timeUs;
5348 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
5352 public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) {
5353 synchronized(this) {
5354 if (DEBUG) Log.d(TAG, "scheduleUpdate");
5355 int i = registerListener(listener);
5359 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
5364 public void cancelNotifications(
5365 MediaTimeProvider.OnMediaTimeListener listener) {
5366 synchronized(this) {
5368 for (; i < mListeners.length; i++) {
5369 if (mListeners[i] == listener) {
5370 System.arraycopy(mListeners, i + 1,
5371 mListeners, i, mListeners.length - i - 1);
5372 System.arraycopy(mTimes, i + 1,
5373 mTimes, i, mTimes.length - i - 1);
5374 mListeners[mListeners.length - 1] = null;
5375 mTimes[mTimes.length - 1] = NO_TIME;
5377 } else if (mListeners[i] == null) {
5382 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
5386 private synchronized void notifyTimedEvent(boolean refreshTime) {
5387 // figure out next callback
5390 nowUs = getCurrentTimeUs(refreshTime, true);
5391 } catch (IllegalStateException e) {
5392 // assume we paused until new player arrives
5394 mPausing = true; // this ensures that call succeeds
5395 nowUs = getCurrentTimeUs(refreshTime, true);
5397 long nextTimeUs = nowUs;
5400 // skip timed-event notifications until seek is complete
5405 StringBuilder sb = new StringBuilder();
5406 sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ")
5407 .append(nowUs).append(") from {");
5408 boolean first = true;
5409 for (long time: mTimes) {
5410 if (time == NO_TIME) {
5413 if (!first) sb.append(", ");
5418 Log.d(TAG, sb.toString());
5421 Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners =
5422 new Vector<MediaTimeProvider.OnMediaTimeListener>();
5423 for (int ix = 0; ix < mTimes.length; ix++) {
5424 if (mListeners[ix] == null) {
5427 if (mTimes[ix] <= NO_TIME) {
5428 // ignore, unless we were stopped
5429 } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) {
5430 activatedListeners.add(mListeners[ix]);
5431 if (DEBUG) Log.d(TAG, "removed");
5432 mTimes[ix] = NO_TIME;
5433 } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) {
5434 nextTimeUs = mTimes[ix];
5438 if (nextTimeUs > nowUs && !mPaused) {
5439 // schedule callback at nextTimeUs
5440 if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs);
5441 scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs);
5443 mEventHandler.removeMessages(NOTIFY);
5444 // no more callbacks
5447 for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) {
5448 listener.onTimedEvent(nowUs);
5452 private long getEstimatedTime(long nanoTime, boolean monotonic) {
5454 mLastReportedTime = mLastTimeUs + mTimeAdjustment;
5456 long timeSinceRead = (nanoTime - mLastNanoTime) / 1000;
5457 mLastReportedTime = mLastTimeUs + timeSinceRead;
5458 if (mTimeAdjustment > 0) {
5460 mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE;
5461 if (adjustment <= 0) {
5462 mTimeAdjustment = 0;
5464 mLastReportedTime += adjustment;
5468 return mLastReportedTime;
5471 public long getCurrentTimeUs(boolean refreshTime, boolean monotonic)
5472 throws IllegalStateException {
5473 synchronized (this) {
5474 // we always refresh the time when the paused-state changes, because
5475 // we expect to have received the pause-change event delayed.
5476 if (mPaused && !refreshTime) {
5477 return mLastReportedTime;
5480 long nanoTime = System.nanoTime();
5482 nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) {
5484 mLastTimeUs = mPlayer.getCurrentPosition() * 1000L;
5485 mPaused = !mPlayer.isPlaying() || mBuffering;
5486 if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs);
5487 } catch (IllegalStateException e) {
5489 // if we were pausing, get last estimated timestamp
5491 getEstimatedTime(nanoTime, monotonic);
5493 if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime);
5494 return mLastReportedTime;
5496 // TODO get time when prepared
5499 mLastNanoTime = nanoTime;
5500 if (monotonic && mLastTimeUs < mLastReportedTime) {
5501 /* have to adjust time */
5502 mTimeAdjustment = mLastReportedTime - mLastTimeUs;
5503 if (mTimeAdjustment > 1000000) {
5504 // schedule seeked event if time jumped significantly
5505 // TODO: do this properly by introducing an exception
5508 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
5511 mTimeAdjustment = 0;
5515 return getEstimatedTime(nanoTime, monotonic);
5519 private class EventHandler extends Handler {
5520 public EventHandler(Looper looper) {
5525 public void handleMessage(Message msg) {
5526 if (msg.what == NOTIFY) {
5529 notifyTimedEvent(false /* refreshTime */);
5531 case REFRESH_AND_NOTIFY_TIME:
5532 notifyTimedEvent(true /* refreshTime */);
5540 case NOTIFY_TRACK_DATA:
5541 notifyTrackData((Pair<SubtitleTrack, byte[]>)msg.obj);
5549 public final static class MetricsConstants
5551 private MetricsConstants() {}
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.
5558 public static final String MIME_TYPE_VIDEO = "android.media.mediaplayer.video.mime";
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.
5565 public static final String CODEC_VIDEO = "android.media.mediaplayer.video.codec";
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.
5572 public static final String WIDTH = "android.media.mediaplayer.width";
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.
5579 public static final String HEIGHT = "android.media.mediaplayer.height";
5582 * Key to extract the count of video frames played
5583 * from the {@link MediaPlayer#getMetrics} return value.
5584 * The value is an integer.
5586 public static final String FRAMES = "android.media.mediaplayer.frames";
5589 * Key to extract the count of video frames dropped
5590 * from the {@link MediaPlayer#getMetrics} return value.
5591 * The value is an integer.
5593 public static final String FRAMES_DROPPED = "android.media.mediaplayer.dropped";
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.
5600 public static final String MIME_TYPE_AUDIO = "android.media.mediaplayer.audio.mime";
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.
5607 public static final String CODEC_AUDIO = "android.media.mediaplayer.audio.codec";
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.
5615 public static final String DURATION = "android.media.mediaplayer.durationMs";
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.
5623 public static final String PLAYING = "android.media.mediaplayer.playingMs";
5626 * Key to extract the count of errors encountered while
5628 * from the {@link MediaPlayer#getMetrics} return value.
5629 * The value is an integer.
5631 public static final String ERRORS = "android.media.mediaplayer.err";
5634 * Key to extract an (optional) error code detected while
5636 * from the {@link MediaPlayer#getMetrics} return value.
5637 * The value is an integer.
5639 public static final String ERROR_CODE = "android.media.mediaplayer.errcode";