blob: 1864d72da1c34d4e3bde01c0aa269c0b54559edc [file] [log] [blame]
Justin Klaassenb8042fc2018-04-15 00:41:15 -04001/*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package androidx.media;
18
19import static androidx.annotation.RestrictTo.Scope.LIBRARY_GROUP;
20
21import android.annotation.TargetApi;
22import android.graphics.SurfaceTexture;
23import android.media.AudioAttributes;
24import android.media.DeniedByServerException;
25import android.media.MediaDrm;
26import android.media.MediaDrmException;
27import android.media.MediaFormat;
28import android.media.MediaTimestamp;
29import android.media.PlaybackParams;
30import android.media.ResourceBusyException;
31import android.media.SyncParams;
32import android.media.TimedMetaData;
33import android.media.UnsupportedSchemeException;
34import android.os.Build;
35import android.os.PersistableBundle;
36import android.view.Surface;
37
38import androidx.annotation.IntDef;
39import androidx.annotation.NonNull;
40import androidx.annotation.Nullable;
41import androidx.annotation.RestrictTo;
42
43import java.lang.annotation.Retention;
44import java.lang.annotation.RetentionPolicy;
45import java.util.List;
46import java.util.Map;
47import java.util.UUID;
48import java.util.concurrent.Executor;
49
50
51/**
52 * @hide
53 * MediaPlayer2 class can be used to control playback
54 * of audio/video files and streams. An example on how to use the methods in
55 * this class can be found in {@link android.widget.VideoView}.
56 *
57 * <p>Topics covered here are:
58 * <ol>
59 * <li><a href="#StateDiagram">State Diagram</a>
60 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
61 * <li><a href="#Permissions">Permissions</a>
62 * <li><a href="#Callbacks">Register informational and error callbacks</a>
63 * </ol>
64 *
65 * <div class="special reference">
66 * <h3>Developer Guides</h3>
67 * <p>For more information about how to use MediaPlayer2, read the
68 * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p>
69 * </div>
70 *
71 * <a name="StateDiagram"></a>
72 * <h3>State Diagram</h3>
73 *
74 * <p>Playback control of audio/video files and streams is managed as a state
75 * machine. The following diagram shows the life cycle and the states of a
76 * MediaPlayer2 object driven by the supported playback control operations.
77 * The ovals represent the states a MediaPlayer2 object may reside
78 * in. The arcs represent the playback control operations that drive the object
79 * state transition. There are two types of arcs. The arcs with a single arrow
80 * head represent synchronous method calls, while those with
81 * a double arrow head represent asynchronous method calls.</p>
82 *
83 * <p><img src="../../../images/mediaplayer_state_diagram.gif"
84 * alt="MediaPlayer State diagram"
85 * border="0" /></p>
86 *
87 * <p>From this state diagram, one can see that a MediaPlayer2 object has the
88 * following states:</p>
89 * <ul>
90 * <li>When a MediaPlayer2 object is just created using <code>create</code> or
91 * after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
92 * {@link #close()} is called, it is in the <em>End</em> state. Between these
93 * two states is the life cycle of the MediaPlayer2 object.
94 * <ul>
95 * <li> It is a programming error to invoke methods such
96 * as {@link #getCurrentPosition()},
97 * {@link #getDuration()}, {@link #getVideoHeight()},
98 * {@link #getVideoWidth()}, {@link #setAudioAttributes(AudioAttributes)},
99 * {@link #setPlayerVolume(float)}, {@link #pause()}, {@link #play()},
100 * {@link #seekTo(long, int)} or
101 * {@link #prepare()} in the <em>Idle</em> state.
102 * <li>It is also recommended that once
103 * a MediaPlayer2 object is no longer being used, call {@link #close()} immediately
104 * so that resources used by the internal player engine associated with the
105 * MediaPlayer2 object can be released immediately. Resource may include
106 * singleton resources such as hardware acceleration components and
107 * failure to call {@link #close()} may cause subsequent instances of
108 * MediaPlayer2 objects to fallback to software implementations or fail
109 * altogether. Once the MediaPlayer2
110 * object is in the <em>End</em> state, it can no longer be used and
111 * there is no way to bring it back to any other state. </li>
112 * <li>Furthermore,
113 * the MediaPlayer2 objects created using <code>new</code> is in the
114 * <em>Idle</em> state.
115 * </li>
116 * </ul>
117 * </li>
118 * <li>In general, some playback control operation may fail due to various
119 * reasons, such as unsupported audio/video format, poorly interleaved
120 * audio/video, resolution too high, streaming timeout, and the like.
121 * Thus, error reporting and recovery is an important concern under
122 * these circumstances. Sometimes, due to programming errors, invoking a playback
123 * control operation in an invalid state may also occur. Under all these
124 * error conditions, the internal player engine invokes a user supplied
125 * MediaPlayer2EventCallback.onError() method if an MediaPlayer2EventCallback has been
126 * registered beforehand via
127 * {@link #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback)}.
128 * <ul>
129 * <li>It is important to note that once an error occurs, the
130 * MediaPlayer2 object enters the <em>Error</em> state (except as noted
131 * above), even if an error listener has not been registered by the application.</li>
132 * <li>In order to reuse a MediaPlayer2 object that is in the <em>
133 * Error</em> state and recover from the error,
134 * {@link #reset()} can be called to restore the object to its <em>Idle</em>
135 * state.</li>
136 * <li>It is good programming practice to have your application
137 * register a OnErrorListener to look out for error notifications from
138 * the internal player engine.</li>
139 * <li>IllegalStateException is
140 * thrown to prevent programming errors such as calling
141 * {@link #prepare()}, {@link #setDataSource(DataSourceDesc)}
142 * methods in an invalid state. </li>
143 * </ul>
144 * </li>
145 * <li>Calling
146 * {@link #setDataSource(DataSourceDesc)} transfers a
147 * MediaPlayer2 object in the <em>Idle</em> state to the
148 * <em>Initialized</em> state.
149 * <ul>
150 * <li>An IllegalStateException is thrown if
151 * setDataSource() is called in any other state.</li>
152 * <li>It is good programming
153 * practice to always look out for <code>IllegalArgumentException</code>
154 * and <code>IOException</code> that may be thrown from
155 * <code>setDataSource</code>.</li>
156 * </ul>
157 * </li>
158 * <li>A MediaPlayer2 object must first enter the <em>Prepared</em> state
159 * before playback can be started.
160 * <ul>
161 * <li>There are an asynchronous way that the <em>Prepared</em> state can be reached:
162 * a call to {@link #prepare()} (asynchronous) which
163 * first transfers the object to the <em>Preparing</em> state after the
164 * call returns (which occurs almost right way) while the internal
165 * player engine continues working on the rest of preparation work
166 * until the preparation work completes. When the preparation completes,
167 * the internal player engine then calls a user supplied callback method,
168 * onInfo() of the MediaPlayer2EventCallback interface with {@link #MEDIA_INFO_PREPARED},
169 * if an MediaPlayer2EventCallback is registered beforehand via
170 * {@link #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback)}.</li>
171 * <li>It is important to note that
172 * the <em>Preparing</em> state is a transient state, and the behavior
173 * of calling any method with side effect while a MediaPlayer2 object is
174 * in the <em>Preparing</em> state is undefined.</li>
175 * <li>An IllegalStateException is
176 * thrown if {@link #prepare()} is called in
177 * any other state.</li>
178 * <li>While in the <em>Prepared</em> state, properties
179 * such as audio/sound volume, screenOnWhilePlaying, looping can be
180 * adjusted by invoking the corresponding set methods.</li>
181 * </ul>
182 * </li>
183 * <li>To start the playback, {@link #play()} must be called. After
184 * {@link #play()} returns successfully, the MediaPlayer2 object is in the
185 * <em>Started</em> state. {@link #getPlayerState()} can be called to test
186 * whether the MediaPlayer2 object is in the <em>Started</em> state.
187 * <ul>
188 * <li>While in the <em>Started</em> state, the internal player engine calls
189 * a user supplied callback method MediaPlayer2EventCallback.onInfo() with
190 * {@link #MEDIA_INFO_BUFFERING_UPDATE} if an MediaPlayer2EventCallback has been
191 * registered beforehand via
192 * {@link #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback)}.
193 * This callback allows applications to keep track of the buffering status
194 * while streaming audio/video.</li>
195 * <li>Calling {@link #play()} has not effect
196 * on a MediaPlayer2 object that is already in the <em>Started</em> state.</li>
197 * </ul>
198 * </li>
199 * <li>Playback can be paused and stopped, and the current playback position
200 * can be adjusted. Playback can be paused via {@link #pause()}. When the call to
201 * {@link #pause()} returns, the MediaPlayer2 object enters the
202 * <em>Paused</em> state. Note that the transition from the <em>Started</em>
203 * state to the <em>Paused</em> state and vice versa happens
204 * asynchronously in the player engine. It may take some time before
205 * the state is updated in calls to {@link #getPlayerState()}, and it can be
206 * a number of seconds in the case of streamed content.
207 * <ul>
208 * <li>Calling {@link #play()} to resume playback for a paused
209 * MediaPlayer2 object, and the resumed playback
210 * position is the same as where it was paused. When the call to
211 * {@link #play()} returns, the paused MediaPlayer2 object goes back to
212 * the <em>Started</em> state.</li>
213 * <li>Calling {@link #pause()} has no effect on
214 * a MediaPlayer2 object that is already in the <em>Paused</em> state.</li>
215 * </ul>
216 * </li>
217 * <li>The playback position can be adjusted with a call to
218 * {@link #seekTo(long, int)}.
219 * <ul>
220 * <li>Although the asynchronuous {@link #seekTo(long, int)}
221 * call returns right away, the actual seek operation may take a while to
222 * finish, especially for audio/video being streamed. When the actual
223 * seek operation completes, the internal player engine calls a user
224 * supplied MediaPlayer2EventCallback.onCallCompleted() with
225 * {@link #CALL_COMPLETED_SEEK_TO}
226 * if an MediaPlayer2EventCallback has been registered beforehand via
227 * {@link #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback)}.</li>
228 * <li>Please
229 * note that {@link #seekTo(long, int)} can also be called in the other states,
230 * such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
231 * </em> state. When {@link #seekTo(long, int)} is called in those states,
232 * one video frame will be displayed if the stream has video and the requested
233 * position is valid.
234 * </li>
235 * <li>Furthermore, the actual current playback position
236 * can be retrieved with a call to {@link #getCurrentPosition()}, which
237 * is helpful for applications such as a Music player that need to keep
238 * track of the playback progress.</li>
239 * </ul>
240 * </li>
241 * <li>When the playback reaches the end of stream, the playback completes.
242 * <ul>
243 * <li>If current source is set to loop by {@link #loopCurrent(boolean)},
244 * the MediaPlayer2 object shall remain in the <em>Started</em> state.</li>
245 * <li>If the looping mode was set to <var>false
246 * </var>, the player engine calls a user supplied callback method,
247 * MediaPlayer2EventCallback.onCompletion(), if an MediaPlayer2EventCallback is
248 * registered beforehand via
249 * {@link #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback)}.
250 * The invoke of the callback signals that the object is now in the <em>
251 * PlaybackCompleted</em> state.</li>
252 * <li>While in the <em>PlaybackCompleted</em>
253 * state, calling {@link #play()} can restart the playback from the
254 * beginning of the audio/video source.</li>
255 * </ul>
256 *
257 *
258 * <a name="Valid_and_Invalid_States"></a>
259 * <h3>Valid and invalid states</h3>
260 *
261 * <table border="0" cellspacing="0" cellpadding="0">
262 * <tr><td>Method Name </p></td>
263 * <td>Valid Sates </p></td>
264 * <td>Invalid States </p></td>
265 * <td>Comments </p></td></tr>
266 * <tr><td>attachAuxEffect </p></td>
267 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
268 * <td>{Idle, Error} </p></td>
269 * <td>This method must be called after setDataSource.
270 * Calling it does not change the object state. </p></td></tr>
271 * <tr><td>getAudioSessionId </p></td>
272 * <td>any </p></td>
273 * <td>{} </p></td>
274 * <td>This method can be called in any state and calling it does not change
275 * the object state. </p></td></tr>
276 * <tr><td>getCurrentPosition </p></td>
277 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
278 * PlaybackCompleted} </p></td>
279 * <td>{Error}</p></td>
280 * <td>Successful invoke of this method in a valid state does not change the
281 * state. Calling this method in an invalid state transfers the object
282 * to the <em>Error</em> state. </p></td></tr>
283 * <tr><td>getDuration </p></td>
284 * <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
285 * <td>{Idle, Initialized, Error} </p></td>
286 * <td>Successful invoke of this method in a valid state does not change the
287 * state. Calling this method in an invalid state transfers the object
288 * to the <em>Error</em> state. </p></td></tr>
289 * <tr><td>getVideoHeight </p></td>
290 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
291 * PlaybackCompleted}</p></td>
292 * <td>{Error}</p></td>
293 * <td>Successful invoke of this method in a valid state does not change the
294 * state. Calling this method in an invalid state transfers the object
295 * to the <em>Error</em> state. </p></td></tr>
296 * <tr><td>getVideoWidth </p></td>
297 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
298 * PlaybackCompleted}</p></td>
299 * <td>{Error}</p></td>
300 * <td>Successful invoke of this method in a valid state does not change
301 * the state. Calling this method in an invalid state transfers the
302 * object to the <em>Error</em> state. </p></td></tr>
303 * <tr><td>getPlayerState </p></td>
304 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
305 * PlaybackCompleted}</p></td>
306 * <td>{Error}</p></td>
307 * <td>Successful invoke of this method in a valid state does not change
308 * the state. Calling this method in an invalid state transfers the
309 * object to the <em>Error</em> state. </p></td></tr>
310 * <tr><td>pause </p></td>
311 * <td>{Started, Paused, PlaybackCompleted}</p></td>
312 * <td>{Idle, Initialized, Prepared, Stopped, Error}</p></td>
313 * <td>Successful invoke of this method in a valid state transfers the
314 * object to the <em>Paused</em> state. Calling this method in an
315 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
316 * <tr><td>prepare </p></td>
317 * <td>{Initialized, Stopped} </p></td>
318 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
319 * <td>Successful invoke of this method in a valid state transfers the
320 * object to the <em>Preparing</em> state. Calling this method in an
321 * invalid state throws an IllegalStateException.</p></td></tr>
322 * <tr><td>release </p></td>
323 * <td>any </p></td>
324 * <td>{} </p></td>
325 * <td>After {@link #close()}, the object is no longer available. </p></td></tr>
326 * <tr><td>reset </p></td>
327 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
328 * PlaybackCompleted, Error}</p></td>
329 * <td>{}</p></td>
330 * <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
331 * <tr><td>seekTo </p></td>
332 * <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
333 * <td>{Idle, Initialized, Stopped, Error}</p></td>
334 * <td>Successful invoke of this method in a valid state does not change
335 * the state. Calling this method in an invalid state transfers the
336 * object to the <em>Error</em> state. </p></td></tr>
337 * <tr><td>setAudioAttributes </p></td>
338 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
339 * PlaybackCompleted}</p></td>
340 * <td>{Error}</p></td>
341 * <td>Successful invoke of this method does not change the state. In order for the
342 * target audio attributes type to become effective, this method must be called before
343 * prepare().</p></td></tr>
344 * <tr><td>setAudioSessionId </p></td>
345 * <td>{Idle} </p></td>
346 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
347 * Error} </p></td>
348 * <td>This method must be called in idle state as the audio session ID must be known before
349 * calling setDataSource. Calling it does not change the object
350 * state. </p></td></tr>
351 * <tr><td>setAudioStreamType (deprecated)</p></td>
352 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
353 * PlaybackCompleted}</p></td>
354 * <td>{Error}</p></td>
355 * <td>Successful invoke of this method does not change the state. In order for the
356 * target audio stream type to become effective, this method must be called before
357 * prepare().</p></td></tr>
358 * <tr><td>setAuxEffectSendLevel </p></td>
359 * <td>any</p></td>
360 * <td>{} </p></td>
361 * <td>Calling this method does not change the object state. </p></td></tr>
362 * <tr><td>setDataSource </p></td>
363 * <td>{Idle} </p></td>
364 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
365 * Error} </p></td>
366 * <td>Successful invoke of this method in a valid state transfers the
367 * object to the <em>Initialized</em> state. Calling this method in an
368 * invalid state throws an IllegalStateException.</p></td></tr>
369 * <tr><td>setDisplay </p></td>
370 * <td>any </p></td>
371 * <td>{} </p></td>
372 * <td>This method can be called in any state and calling it does not change
373 * the object state. </p></td></tr>
374 * <tr><td>setSurface </p></td>
375 * <td>any </p></td>
376 * <td>{} </p></td>
377 * <td>This method can be called in any state and calling it does not change
378 * the object state. </p></td></tr>
379 * <tr><td>loopCurrent </p></td>
380 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
381 * PlaybackCompleted}</p></td>
382 * <td>{Error}</p></td>
383 * <td>Successful invoke of this method in a valid state does not change
384 * the state. Calling this method in an
385 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
386 * <tr><td>isLooping </p></td>
387 * <td>any </p></td>
388 * <td>{} </p></td>
389 * <td>This method can be called in any state and calling it does not change
390 * the object state. </p></td></tr>
391 * <tr><td>setDrmEventCallback </p></td>
392 * <td>any </p></td>
393 * <td>{} </p></td>
394 * <td>This method can be called in any state and calling it does not change
395 * the object state. </p></td></tr>
396 * <tr><td>setMediaPlayer2EventCallback </p></td>
397 * <td>any </p></td>
398 * <td>{} </p></td>
399 * <td>This method can be called in any state and calling it does not change
400 * the object state. </p></td></tr>
401 * <tr><td>setPlaybackParams</p></td>
402 * <td>{Initialized, Prepared, Started, Paused, PlaybackCompleted, Error}</p></td>
403 * <td>{Idle, Stopped} </p></td>
404 * <td>This method will change state in some cases, depending on when it's called.
405 * </p></td></tr>
406 * <tr><td>setPlayerVolume </p></td>
407 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
408 * PlaybackCompleted}</p></td>
409 * <td>{Error}</p></td>
410 * <td>Successful invoke of this method does not change the state.
411 * <tr><td>play </p></td>
412 * <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
413 * <td>{Idle, Initialized, Stopped, Error}</p></td>
414 * <td>Successful invoke of this method in a valid state transfers the
415 * object to the <em>Started</em> state. Calling this method in an
416 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
417 * <tr><td>stop </p></td>
418 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
419 * <td>{Idle, Initialized, Error}</p></td>
420 * <td>Successful invoke of this method in a valid state transfers the
421 * object to the <em>Stopped</em> state. Calling this method in an
422 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
423 * <tr><td>getTrackInfo </p></td>
424 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
425 * <td>{Idle, Initialized, Error}</p></td>
426 * <td>Successful invoke of this method does not change the state.</p></td></tr>
427 * <tr><td>selectTrack </p></td>
428 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
429 * <td>{Idle, Initialized, Error}</p></td>
430 * <td>Successful invoke of this method does not change the state.</p></td></tr>
431 * <tr><td>deselectTrack </p></td>
432 * <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
433 * <td>{Idle, Initialized, Error}</p></td>
434 * <td>Successful invoke of this method does not change the state.</p></td></tr>
435 *
436 * </table>
437 *
438 * <a name="Permissions"></a>
439 * <h3>Permissions</h3>
440 * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
441 * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
442 * element.
443 *
444 * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
445 * when used with network-based content.
446 *
447 * <a name="Callbacks"></a>
448 * <h3>Callbacks</h3>
449 * <p>Applications may want to register for informational and error
450 * events in order to be informed of some internal state update and
451 * possible runtime errors during playback or streaming. Registration for
452 * these events is done by properly setting the appropriate listeners (via calls
453 * to
454 * {@link #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback)},
455 * {@link #setDrmEventCallback(Executor, DrmEventCallback)}).
456 * In order to receive the respective callback
457 * associated with these listeners, applications are required to create
458 * MediaPlayer2 objects on a thread with its own Looper running (main UI
459 * thread by default has a Looper running).
460 *
461 */
462@TargetApi(Build.VERSION_CODES.P)
463@RestrictTo(LIBRARY_GROUP)
464public abstract class MediaPlayer2 extends MediaPlayerBase {
465 /**
466 * Create a MediaPlayer2 object.
467 *
468 * @return A MediaPlayer2 object created
469 */
470 public static final MediaPlayer2 create() {
471 return new MediaPlayer2Impl();
472 }
473
474 /**
475 * @hide
476 */
477 @RestrictTo(LIBRARY_GROUP)
478 public MediaPlayer2() { }
479
480 /**
481 * Releases the resources held by this {@code MediaPlayer2} object.
482 *
483 * It is considered good practice to call this method when you're
484 * done using the MediaPlayer2. In particular, whenever an Activity
485 * of an application is paused (its onPause() method is called),
486 * or stopped (its onStop() method is called), this method should be
487 * invoked to release the MediaPlayer2 object, unless the application
488 * has a special need to keep the object around. In addition to
489 * unnecessary resources (such as memory and instances of codecs)
490 * being held, failure to call this method immediately if a
491 * MediaPlayer2 object is no longer needed may also lead to
492 * continuous battery consumption for mobile devices, and playback
493 * failure for other applications if no multiple instances of the
494 * same codec are supported on a device. Even if multiple instances
495 * of the same codec are supported, some performance degradation
496 * may be expected when unnecessary multiple instances are used
497 * at the same time.
498 *
499 * {@code close()} may be safely called after a prior {@code close()}.
500 * This class implements the Java {@code AutoCloseable} interface and
501 * may be used with try-with-resources.
502 */
503 // This is a synchronous call.
504 @Override
505 public abstract void close();
506
507 /**
508 * Starts or resumes playback. If playback had previously been paused,
509 * playback will continue from where it was paused. If playback had
510 * reached end of stream and been paused, or never started before,
511 * playback will start at the beginning. If the source had not been
512 * prepared, the player will prepare the source and play.
513 *
514 */
515 // This is an asynchronous call.
516 @Override
517 public abstract void play();
518
519 /**
520 * Prepares the player for playback, asynchronously.
521 *
522 * After setting the datasource and the display surface, you need to
523 * call prepare().
524 *
525 */
526 // This is an asynchronous call.
527 @Override
528 public abstract void prepare();
529
530 /**
531 * Pauses playback. Call play() to resume.
532 */
533 // This is an asynchronous call.
534 @Override
535 public abstract void pause();
536
537 /**
538 * Tries to play next data source if applicable.
539 */
540 // This is an asynchronous call.
541 @Override
542 public abstract void skipToNext();
543
544 /**
545 * Moves the media to specified time position.
546 * Same as {@link #seekTo(long, int)} with {@code mode = SEEK_PREVIOUS_SYNC}.
547 *
548 * @param msec the offset in milliseconds from the start to seek to
549 */
550 // This is an asynchronous call.
551 @Override
552 public void seekTo(long msec) {
553 seekTo(msec, SEEK_PREVIOUS_SYNC /* mode */);
554 }
555
556 /**
557 * Gets the current playback position.
558 *
559 * @return the current position in milliseconds
560 */
561 @Override
562 public abstract long getCurrentPosition();
563
564 /**
565 * Gets the duration of the file.
566 *
567 * @return the duration in milliseconds, if no duration is available
568 * (for example, if streaming live content), -1 is returned.
569 */
570 @Override
571 public abstract long getDuration();
572
573 /**
574 * Gets the current buffered media source position received through progressive downloading.
575 * The received buffering percentage indicates how much of the content has been buffered
576 * or played. For example a buffering update of 80 percent when half the content
577 * has already been played indicates that the next 30 percent of the
578 * content to play has been buffered.
579 *
580 * @return the current buffered media source position in milliseconds
581 */
582 @Override
583 public abstract long getBufferedPosition();
584
585 /**
586 * Gets the current player state.
587 *
588 * @return the current player state.
589 */
590 @Override
591 public abstract @PlayerState int getPlayerState();
592
593 /**
594 * Gets the current buffering state of the player.
595 * During buffering, see {@link #getBufferedPosition()} for the quantifying the amount already
596 * buffered.
597 * @return the buffering state, one of the following:
598 */
599 @Override
600 public abstract @BuffState int getBufferingState();
601
602 /**
603 * Sets the audio attributes for this MediaPlayer2.
604 * See {@link AudioAttributes} for how to build and configure an instance of this class.
605 * You must call this method before {@link #prepare()} in order
606 * for the audio attributes to become effective thereafter.
607 * @param attributes a non-null set of audio attributes
608 */
609 // This is an asynchronous call.
610 @Override
611 public abstract void setAudioAttributes(@NonNull AudioAttributesCompat attributes);
612
613 /**
614 * Gets the audio attributes for this MediaPlayer2.
615 * @return attributes a set of audio attributes
616 */
617 @Override
618 public abstract @Nullable AudioAttributesCompat getAudioAttributes();
619
620 /**
621 * Sets the data source as described by a DataSourceDesc.
622 *
623 * @param dsd the descriptor of data source you want to play
624 */
625 // This is an asynchronous call.
626 @Override
627 public abstract void setDataSource(@NonNull DataSourceDesc dsd);
628
629 /**
630 * Sets a single data source as described by a DataSourceDesc which will be played
631 * after current data source is finished.
632 *
633 * @param dsd the descriptor of data source you want to play after current one
634 */
635 // This is an asynchronous call.
636 @Override
637 public abstract void setNextDataSource(@NonNull DataSourceDesc dsd);
638
639 /**
640 * Sets a list of data sources to be played sequentially after current data source is done.
641 *
642 * @param dsds the list of data sources you want to play after current one
643 */
644 // This is an asynchronous call.
645 @Override
646 public abstract void setNextDataSources(@NonNull List<DataSourceDesc> dsds);
647
648 /**
649 * Gets the current data source as described by a DataSourceDesc.
650 *
651 * @return the current DataSourceDesc
652 */
653 @Override
654 public abstract @NonNull DataSourceDesc getCurrentDataSource();
655
656 /**
657 * Configures the player to loop on the current data source.
658 * @param loop true if the current data source is meant to loop.
659 */
660 // This is an asynchronous call.
661 @Override
662 public abstract void loopCurrent(boolean loop);
663
664 /**
665 * Sets the playback speed.
666 * A value of 1.0f is the default playback value.
667 * A negative value indicates reverse playback, check {@link #isReversePlaybackSupported()}
668 * before using negative values.<br>
669 * After changing the playback speed, it is recommended to query the actual speed supported
670 * by the player, see {@link #getPlaybackSpeed()}.
671 * @param speed the desired playback speed
672 */
673 // This is an asynchronous call.
674 @Override
675 public abstract void setPlaybackSpeed(float speed);
676
677 /**
678 * Returns the actual playback speed to be used by the player when playing.
679 * Note that it may differ from the speed set in {@link #setPlaybackSpeed(float)}.
680 * @return the actual playback speed
681 */
682 @Override
683 public float getPlaybackSpeed() {
684 return 1.0f;
685 }
686
687 /**
688 * Indicates whether reverse playback is supported.
689 * Reverse playback is indicated by negative playback speeds, see
690 * {@link #setPlaybackSpeed(float)}.
691 * @return true if reverse playback is supported.
692 */
693 @Override
694 public boolean isReversePlaybackSupported() {
695 return false;
696 }
697
698 /**
699 * Sets the volume of the audio of the media to play, expressed as a linear multiplier
700 * on the audio samples.
701 * Note that this volume is specific to the player, and is separate from stream volume
702 * used across the platform.<br>
703 * A value of 0.0f indicates muting, a value of 1.0f is the nominal unattenuated and unamplified
704 * gain. See {@link #getMaxPlayerVolume()} for the volume range supported by this player.
705 * @param volume a value between 0.0f and {@link #getMaxPlayerVolume()}.
706 */
707 // This is an asynchronous call.
708 @Override
709 public abstract void setPlayerVolume(float volume);
710
711 /**
712 * Returns the current volume of this player to this player.
713 * Note that it does not take into account the associated stream volume.
714 * @return the player volume.
715 */
716 @Override
717 public abstract float getPlayerVolume();
718
719 /**
720 * @return the maximum volume that can be used in {@link #setPlayerVolume(float)}.
721 */
722 @Override
723 public float getMaxPlayerVolume() {
724 return 1.0f;
725 }
726
727 /**
728 * Adds a callback to be notified of events for this player.
729 * @param e the {@link Executor} to be used for the events.
730 * @param cb the callback to receive the events.
731 */
732 // This is a synchronous call.
733 @Override
734 public abstract void registerPlayerEventCallback(@NonNull Executor e,
735 @NonNull PlayerEventCallback cb);
736
737 /**
738 * Removes a previously registered callback for player events
739 * @param cb the callback to remove
740 */
741 // This is a synchronous call.
742 @Override
743 public abstract void unregisterPlayerEventCallback(@NonNull PlayerEventCallback cb);
744
745 /**
746 * Insert a task in the command queue to help the client to identify whether a batch
747 * of commands has been finished. When this command is processed, a notification
748 * {@code MediaPlayer2EventCallback.onCommandLabelReached} will be fired with the
749 * given {@code label}.
750 *
751 * @see MediaPlayer2EventCallback#onCommandLabelReached
752 *
753 * @param label An application specific Object used to help to identify the completeness
754 * of a batch of commands.
755 */
756 // This is an asynchronous call.
757 public void notifyWhenCommandLabelReached(@NonNull Object label) { }
758
759 /**
760 * Sets the {@link Surface} to be used as the sink for the video portion of
761 * the media. Setting a
762 * Surface will un-set any Surface or SurfaceHolder that was previously set.
763 * A null surface will result in only the audio track being played.
764 *
765 * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
766 * returned from {@link SurfaceTexture#getTimestamp()} will have an
767 * unspecified zero point. These timestamps cannot be directly compared
768 * between different media sources, different instances of the same media
769 * source, or multiple runs of the same program. The timestamp is normally
770 * monotonically increasing and is unaffected by time-of-day adjustments,
771 * but it is reset when the position is set.
772 *
773 * @param surface The {@link Surface} to be used for the video portion of
774 * the media.
775 * @throws IllegalStateException if the internal player engine has not been
776 * initialized or has been released.
777 */
778 // This is an asynchronous call.
779 public abstract void setSurface(Surface surface);
780
781 /* Do not change these video scaling mode values below without updating
782 * their counterparts in system/window.h! Please do not forget to update
783 * {@link #isVideoScalingModeSupported} when new video scaling modes
784 * are added.
785 */
786 /**
787 * Specifies a video scaling mode. The content is stretched to the
788 * surface rendering area. When the surface has the same aspect ratio
789 * as the content, the aspect ratio of the content is maintained;
790 * otherwise, the aspect ratio of the content is not maintained when video
791 * is being rendered.
792 * There is no content cropping with this video scaling mode.
793 */
794 public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1;
795
796 /**
797 * Discards all pending commands.
798 */
799 // This is a synchronous call.
800 public abstract void clearPendingCommands();
801
802 /**
803 * Returns the width of the video.
804 *
805 * @return the width of the video, or 0 if there is no video,
806 * no display surface was set, or the width has not been determined
807 * yet. The {@code MediaPlayer2EventCallback} can be registered via
808 * {@link #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback)} to provide a
809 * notification {@code MediaPlayer2EventCallback.onVideoSizeChanged} when the width
810 * is available.
811 */
812 public abstract int getVideoWidth();
813
814 /**
815 * Returns the height of the video.
816 *
817 * @return the height of the video, or 0 if there is no video,
818 * no display surface was set, or the height has not been determined
819 * yet. The {@code MediaPlayer2EventCallback} can be registered via
820 * {@link #setMediaPlayer2EventCallback(Executor, MediaPlayer2EventCallback)} to provide a
821 * notification {@code MediaPlayer2EventCallback.onVideoSizeChanged} when the height is
822 * available.
823 */
824 public abstract int getVideoHeight();
825
826 /**
827 * Return Metrics data about the current player.
828 *
829 * @return a {@link PersistableBundle} containing the set of attributes and values
830 * available for the media being handled by this instance of MediaPlayer2
831 * The attributes are descibed in {@link MetricsConstants}.
832 *
833 * Additional vendor-specific fields may also be present in
834 * the return value.
835 * @hide
836 * TODO: This method is not ready for public. Currently returns metrics data in MediaPlayer1.
837 */
838 @RestrictTo(LIBRARY_GROUP)
839 public abstract PersistableBundle getMetrics();
840
841 /**
842 * Sets playback rate using {@link PlaybackParams}. The object sets its internal
843 * PlaybackParams to the input, except that the object remembers previous speed
844 * when input speed is zero. This allows the object to resume at previous speed
845 * when play() is called. Calling it before the object is prepared does not change
846 * the object state. After the object is prepared, calling it with zero speed is
847 * equivalent to calling pause(). After the object is prepared, calling it with
848 * non-zero speed is equivalent to calling play().
849 *
850 * @param params the playback params.
851 */
852 // This is an asynchronous call.
853 public abstract void setPlaybackParams(@NonNull PlaybackParams params);
854
855 /**
856 * Gets the playback params, containing the current playback rate.
857 *
858 * @return the playback params.
859 */
860 @NonNull
861 public abstract PlaybackParams getPlaybackParams();
862
863 /**
864 * Sets A/V sync mode.
865 *
866 * @param params the A/V sync params to apply
867 */
868 // This is an asynchronous call.
869 public abstract void setSyncParams(@NonNull SyncParams params);
870
871 /**
872 * Gets the A/V sync mode.
873 *
874 * @return the A/V sync params
875 */
876 @NonNull
877 public abstract SyncParams getSyncParams();
878
879 /**
880 * Seek modes used in method seekTo(long, int) to move media position
881 * to a specified location.
882 *
883 * Do not change these mode values without updating their counterparts
884 * in include/media/IMediaSource.h!
885 */
886 /**
887 * This mode is used with {@link #seekTo(long, int)} to move media position to
888 * a sync (or key) frame associated with a data source that is located
889 * right before or at the given time.
890 *
891 * @see #seekTo(long, int)
892 */
893 public static final int SEEK_PREVIOUS_SYNC = 0x00;
894 /**
895 * This mode is used with {@link #seekTo(long, int)} to move media position to
896 * a sync (or key) frame associated with a data source that is located
897 * right after or at the given time.
898 *
899 * @see #seekTo(long, int)
900 */
901 public static final int SEEK_NEXT_SYNC = 0x01;
902 /**
903 * This mode is used with {@link #seekTo(long, int)} to move media position to
904 * a sync (or key) frame associated with a data source that is located
905 * closest to (in time) or at the given time.
906 *
907 * @see #seekTo(long, int)
908 */
909 public static final int SEEK_CLOSEST_SYNC = 0x02;
910 /**
911 * This mode is used with {@link #seekTo(long, int)} to move media position to
912 * a frame (not necessarily a key frame) associated with a data source that
913 * is located closest to or at the given time.
914 *
915 * @see #seekTo(long, int)
916 */
917 public static final int SEEK_CLOSEST = 0x03;
918
919 /** @hide */
920 @IntDef(flag = false, /*prefix = "SEEK",*/ value = {
921 SEEK_PREVIOUS_SYNC,
922 SEEK_NEXT_SYNC,
923 SEEK_CLOSEST_SYNC,
924 SEEK_CLOSEST,
925 })
926 @Retention(RetentionPolicy.SOURCE)
927 @RestrictTo(LIBRARY_GROUP)
928 public @interface SeekMode {}
929
930 /**
931 * Moves the media to specified time position by considering the given mode.
932 * <p>
933 * When seekTo is finished, the user will be notified via OnSeekComplete supplied by the user.
934 * There is at most one active seekTo processed at any time. If there is a to-be-completed
935 * seekTo, new seekTo requests will be queued in such a way that only the last request
936 * is kept. When current seekTo is completed, the queued request will be processed if
937 * that request is different from just-finished seekTo operation, i.e., the requested
938 * position or mode is different.
939 *
940 * @param msec the offset in milliseconds from the start to seek to.
941 * When seeking to the given time position, there is no guarantee that the data source
942 * has a frame located at the position. When this happens, a frame nearby will be rendered.
943 * If msec is negative, time position zero will be used.
944 * If msec is larger than duration, duration will be used.
945 * @param mode the mode indicating where exactly to seek to.
946 */
947 // This is an asynchronous call.
948 public abstract void seekTo(long msec, @SeekMode int mode);
949
950 /**
951 * Get current playback position as a {@link MediaTimestamp}.
952 * <p>
953 * The MediaTimestamp represents how the media time correlates to the system time in
954 * a linear fashion using an anchor and a clock rate. During regular playback, the media
955 * time moves fairly constantly (though the anchor frame may be rebased to a current
956 * system time, the linear correlation stays steady). Therefore, this method does not
957 * need to be called often.
958 * <p>
959 * To help users get current playback position, this method always anchors the timestamp
960 * to the current {@link System#nanoTime system time}, so
961 * {@link MediaTimestamp#getAnchorMediaTimeUs} can be used as current playback position.
962 *
963 * @return a MediaTimestamp object if a timestamp is available, or {@code null} if no timestamp
964 * is available, e.g. because the media player has not been initialized.
965 *
966 * @see MediaTimestamp
967 */
968 @Nullable
969 public abstract MediaTimestamp getTimestamp();
970
971 /**
972 * Resets the MediaPlayer2 to its uninitialized state. After calling
973 * this method, you will have to initialize it again by setting the
974 * data source and calling prepare().
975 */
976 // This is a synchronous call.
977 @Override
978 public abstract void reset();
979
980 /**
981 * Sets the audio session ID.
982 *
983 * @param sessionId the audio session ID.
984 * The audio session ID is a system wide unique identifier for the audio stream played by
985 * this MediaPlayer2 instance.
986 * The primary use of the audio session ID is to associate audio effects to a particular
987 * instance of MediaPlayer2: if an audio session ID is provided when creating an audio effect,
988 * this effect will be applied only to the audio content of media players within the same
989 * audio session and not to the output mix.
990 * When created, a MediaPlayer2 instance automatically generates its own audio session ID.
991 * However, it is possible to force this player to be part of an already existing audio session
992 * by calling this method.
993 * This method must be called before one of the overloaded <code> setDataSource </code> methods.
994 */
995 // This is an asynchronous call.
996 public abstract void setAudioSessionId(int sessionId);
997
998 /**
999 * Returns the audio session ID.
1000 *
1001 * @return the audio session ID. {@see #setAudioSessionId(int)}
1002 * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer2 was
1003 * contructed.
1004 */
1005 public abstract int getAudioSessionId();
1006
1007 /**
1008 * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
1009 * effect which can be applied on any sound source that directs a certain amount of its
1010 * energy to this effect. This amount is defined by setAuxEffectSendLevel().
1011 * See {@link #setAuxEffectSendLevel(float)}.
1012 * <p>After creating an auxiliary effect (e.g.
1013 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
1014 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
1015 * to attach the player to the effect.
1016 * <p>To detach the effect from the player, call this method with a null effect id.
1017 * <p>This method must be called after one of the overloaded <code> setDataSource </code>
1018 * methods.
1019 * @param effectId system wide unique id of the effect to attach
1020 */
1021 // This is an asynchronous call.
1022 public abstract void attachAuxEffect(int effectId);
1023
1024
1025 /**
1026 * Sets the send level of the player to the attached auxiliary effect.
1027 * See {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
1028 * <p>By default the send level is 0, so even if an effect is attached to the player
1029 * this method must be called for the effect to be applied.
1030 * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
1031 * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
1032 * so an appropriate conversion from linear UI input x to level is:
1033 * x == 0 -> level = 0
1034 * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
1035 * @param level send level scalar
1036 */
1037 // This is an asynchronous call.
1038 public abstract void setAuxEffectSendLevel(float level);
1039
1040 /**
1041 * Class for MediaPlayer2 to return each audio/video/subtitle track's metadata.
1042 *
1043 * @see MediaPlayer2#getTrackInfo
1044 */
1045 public abstract static class TrackInfo {
1046 /**
1047 * Gets the track type.
1048 * @return TrackType which indicates if the track is video, audio, timed text.
1049 */
1050 public abstract int getTrackType();
1051
1052 /**
1053 * Gets the language code of the track.
1054 * @return a language code in either way of ISO-639-1 or ISO-639-2.
1055 * When the language is unknown or could not be determined,
1056 * ISO-639-2 language code, "und", is returned.
1057 */
1058 public abstract String getLanguage();
1059
1060 /**
1061 * Gets the {@link MediaFormat} of the track. If the format is
1062 * unknown or could not be determined, null is returned.
1063 */
1064 public abstract MediaFormat getFormat();
1065
1066 public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
1067 public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
1068 public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
1069
1070 /** @hide */
1071 @RestrictTo(LIBRARY_GROUP)
1072 public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
1073
1074 public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
1075 public static final int MEDIA_TRACK_TYPE_METADATA = 5;
1076
1077 @Override
1078 public abstract String toString();
1079 };
1080
1081 /**
1082 * Returns a List of track information.
1083 *
1084 * @return List of track info. The total number of tracks is the array length.
1085 * Must be called again if an external timed text source has been added after
1086 * addTimedTextSource method is called.
1087 */
1088 public abstract List<TrackInfo> getTrackInfo();
1089
1090 /**
1091 * Returns the index of the audio, video, or subtitle track currently selected for playback,
1092 * The return value is an index into the array returned by {@link #getTrackInfo()}, and can
1093 * be used in calls to {@link #selectTrack(int)} or {@link #deselectTrack(int)}.
1094 *
1095 * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
1096 * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
1097 * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
1098 * @return index of the audio, video, or subtitle track currently selected for playback;
1099 * a negative integer is returned when there is no selected track for {@code trackType} or
1100 * when {@code trackType} is not one of audio, video, or subtitle.
1101 * @throws IllegalStateException if called after {@link #close()}
1102 *
1103 * @see #getTrackInfo()
1104 * @see #selectTrack(int)
1105 * @see #deselectTrack(int)
1106 */
1107 public abstract int getSelectedTrack(int trackType);
1108
1109 /**
1110 * Selects a track.
1111 * <p>
1112 * If a MediaPlayer2 is in invalid state, it throws an IllegalStateException exception.
1113 * If a MediaPlayer2 is in <em>Started</em> state, the selected track is presented immediately.
1114 * If a MediaPlayer2 is not in Started state, it just marks the track to be played.
1115 * </p>
1116 * <p>
1117 * In any valid state, if it is called multiple times on the same type of track (ie. Video,
1118 * Audio, Timed Text), the most recent one will be chosen.
1119 * </p>
1120 * <p>
1121 * The first audio and video tracks are selected by default if available, even though
1122 * this method is not called. However, no timed text track will be selected until
1123 * this function is called.
1124 * </p>
1125 * <p>
1126 * Currently, only timed text tracks or audio tracks can be selected via this method.
1127 * In addition, the support for selecting an audio track at runtime is pretty limited
1128 * in that an audio track can only be selected in the <em>Prepared</em> state.
1129 * </p>
1130 * @param index the index of the track to be selected. The valid range of the index
1131 * is 0..total number of track - 1. The total number of tracks as well as the type of
1132 * each individual track can be found by calling {@link #getTrackInfo()} method.
1133 * @throws IllegalStateException if called in an invalid state.
1134 *
1135 * @see MediaPlayer2#getTrackInfo
1136 */
1137 // This is an asynchronous call.
1138 public abstract void selectTrack(int index);
1139
1140 /**
1141 * Deselect a track.
1142 * <p>
1143 * Currently, the track must be a timed text track and no audio or video tracks can be
1144 * deselected. If the timed text track identified by index has not been
1145 * selected before, it throws an exception.
1146 * </p>
1147 * @param index the index of the track to be deselected. The valid range of the index
1148 * is 0..total number of tracks - 1. The total number of tracks as well as the type of
1149 * each individual track can be found by calling {@link #getTrackInfo()} method.
1150 * @throws IllegalStateException if called in an invalid state.
1151 *
1152 * @see MediaPlayer2#getTrackInfo
1153 */
1154 // This is an asynchronous call.
1155 public abstract void deselectTrack(int index);
1156
1157 /**
1158 * Interface definition for callbacks to be invoked when the player has the corresponding
1159 * events.
1160 */
1161 public abstract static class MediaPlayer2EventCallback {
1162 /**
1163 * Called to indicate the video size
1164 *
1165 * The video size (width and height) could be 0 if there was no video,
1166 * no display surface was set, or the value was not determined yet.
1167 *
1168 * @param mp the MediaPlayer2 associated with this callback
1169 * @param dsd the DataSourceDesc of this data source
1170 * @param width the width of the video
1171 * @param height the height of the video
1172 */
1173 public void onVideoSizeChanged(
1174 MediaPlayer2 mp, DataSourceDesc dsd, int width, int height) { }
1175
1176 /**
1177 * Called to indicate available timed metadata
1178 * <p>
1179 * This method will be called as timed metadata is extracted from the media,
1180 * in the same order as it occurs in the media. The timing of this event is
1181 * not controlled by the associated timestamp.
1182 * <p>
1183 * Currently only HTTP live streaming data URI's embedded with timed ID3 tags generates
1184 * {@link TimedMetaData}.
1185 *
1186 * @see MediaPlayer2#selectTrack(int)
1187 * @see TimedMetaData
1188 *
1189 * @param mp the MediaPlayer2 associated with this callback
1190 * @param dsd the DataSourceDesc of this data source
1191 * @param data the timed metadata sample associated with this event
1192 */
1193 public void onTimedMetaDataAvailable(
1194 MediaPlayer2 mp, DataSourceDesc dsd, TimedMetaData data) { }
1195
1196 /**
1197 * Called to indicate an error.
1198 *
1199 * @param mp the MediaPlayer2 the error pertains to
1200 * @param dsd the DataSourceDesc of this data source
1201 * @param what the type of error that has occurred.
1202 * @param extra an extra code, specific to the error. Typically
1203 * implementation dependent.
1204 */
1205 public void onError(
1206 MediaPlayer2 mp, DataSourceDesc dsd, @MediaError int what, int extra) { }
1207
1208 /**
1209 * Called to indicate an info or a warning.
1210 *
1211 * @param mp the MediaPlayer2 the info pertains to.
1212 * @param dsd the DataSourceDesc of this data source
1213 * @param what the type of info or warning.
1214 * @param extra an extra code, specific to the info. Typically
1215 * implementation dependent.
1216 */
1217 public void onInfo(MediaPlayer2 mp, DataSourceDesc dsd, @MediaInfo int what, int extra) { }
1218
1219 /**
1220 * Called to acknowledge an API call.
1221 *
1222 * @param mp the MediaPlayer2 the call was made on.
1223 * @param dsd the DataSourceDesc of this data source
1224 * @param what the enum for the API call.
1225 * @param status the returned status code for the call.
1226 */
1227 public void onCallCompleted(
1228 MediaPlayer2 mp, DataSourceDesc dsd, @CallCompleted int what,
1229 @CallStatus int status) { }
1230
1231 /**
1232 * Called to indicate media clock has changed.
1233 *
1234 * @param mp the MediaPlayer2 the media time pertains to.
1235 * @param dsd the DataSourceDesc of this data source
1236 * @param timestamp the new media clock.
1237 */
1238 public void onMediaTimeChanged(
1239 MediaPlayer2 mp, DataSourceDesc dsd, MediaTimestamp timestamp) { }
1240
1241 /**
1242 * Called to indicate {@link #notifyWhenCommandLabelReached(Object)} has been processed.
1243 *
1244 * @param mp the MediaPlayer2 {@link #notifyWhenCommandLabelReached(Object)} was called on.
1245 * @param label the application specific Object given by
1246 * {@link #notifyWhenCommandLabelReached(Object)}.
1247 */
1248 public void onCommandLabelReached(MediaPlayer2 mp, @NonNull Object label) { }
1249
1250 /* TODO : uncomment below once API is available in supportlib.
1251 * Called when when a player subtitle track has new subtitle data available.
1252 * @param mp the player that reports the new subtitle data
1253 * @param data the subtitle data
1254 */
1255 // public void onSubtitleData(MediaPlayer2 mp, @NonNull SubtitleData data) { }
1256 }
1257
1258 /**
1259 * Sets the callback to be invoked when the media source is ready for playback.
1260 *
1261 * @param eventCallback the callback that will be run
1262 * @param executor the executor through which the callback should be invoked
1263 */
1264 // This is a synchronous call.
1265 public abstract void setMediaPlayer2EventCallback(
1266 @NonNull Executor executor, @NonNull MediaPlayer2EventCallback eventCallback);
1267
1268 /**
1269 * Clears the {@link MediaPlayer2EventCallback}.
1270 */
1271 // This is a synchronous call.
1272 public abstract void clearMediaPlayer2EventCallback();
1273
1274 /* Do not change these values without updating their counterparts
1275 * in include/media/mediaplayer2.h!
1276 */
1277 /** Unspecified media player error.
1278 * @see MediaPlayer2.MediaPlayer2EventCallback#onError
1279 */
1280 public static final int MEDIA_ERROR_UNKNOWN = 1;
1281
1282 /** The video is streamed and its container is not valid for progressive
1283 * playback i.e the video's index (e.g moov atom) is not at the start of the
1284 * file.
1285 * @see MediaPlayer2.MediaPlayer2EventCallback#onError
1286 */
1287 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
1288
1289 /** File or network related operation errors. */
1290 public static final int MEDIA_ERROR_IO = -1004;
1291 /** Bitstream is not conforming to the related coding standard or file spec. */
1292 public static final int MEDIA_ERROR_MALFORMED = -1007;
1293 /** Bitstream is conforming to the related coding standard or file spec, but
1294 * the media framework does not support the feature. */
1295 public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
1296 /** Some operation takes too long to complete, usually more than 3-5 seconds. */
1297 public static final int MEDIA_ERROR_TIMED_OUT = -110;
1298
1299 /** Unspecified low-level system error. This value originated from UNKNOWN_ERROR in
1300 * system/core/include/utils/Errors.h
1301 * @see MediaPlayer2.MediaPlayer2EventCallback#onError
1302 * @hide
1303 */
1304 @RestrictTo(LIBRARY_GROUP)
1305 public static final int MEDIA_ERROR_SYSTEM = -2147483648;
1306
1307 /**
1308 * @hide
1309 */
1310 @IntDef(flag = false, /*prefix = "MEDIA_ERROR",*/ value = {
1311 MEDIA_ERROR_UNKNOWN,
1312 MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK,
1313 MEDIA_ERROR_IO,
1314 MEDIA_ERROR_MALFORMED,
1315 MEDIA_ERROR_UNSUPPORTED,
1316 MEDIA_ERROR_TIMED_OUT,
1317 MEDIA_ERROR_SYSTEM
1318 })
1319 @Retention(RetentionPolicy.SOURCE)
1320 @RestrictTo(LIBRARY_GROUP)
1321 public @interface MediaError {}
1322
1323 /* Do not change these values without updating their counterparts
1324 * in include/media/mediaplayer2.h!
1325 */
1326 /** Unspecified media player info.
1327 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1328 */
1329 public static final int MEDIA_INFO_UNKNOWN = 1;
1330
1331 /** The player switched to this datas source because it is the
1332 * next-to-be-played in the playlist.
1333 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1334 */
1335 public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
1336
1337 /** The player just pushed the very first video frame for rendering.
1338 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1339 */
1340 public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
1341
1342 /** The player just rendered the very first audio sample.
1343 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1344 */
1345 public static final int MEDIA_INFO_AUDIO_RENDERING_START = 4;
1346
1347 /** The player just completed the playback of this data source.
1348 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1349 */
1350 public static final int MEDIA_INFO_PLAYBACK_COMPLETE = 5;
1351
1352 /** The player just completed the playback of the full playlist.
1353 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1354 */
1355 public static final int MEDIA_INFO_PLAYLIST_END = 6;
1356
1357 /** The player just prepared a data source.
1358 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1359 */
1360 public static final int MEDIA_INFO_PREPARED = 100;
1361
1362 /** The video is too complex for the decoder: it can't decode frames fast
1363 * enough. Possibly only the audio plays fine at this stage.
1364 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1365 */
1366 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
1367
1368 /** MediaPlayer2 is temporarily pausing playback internally in order to
1369 * buffer more data.
1370 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1371 */
1372 public static final int MEDIA_INFO_BUFFERING_START = 701;
1373
1374 /** MediaPlayer2 is resuming playback after filling buffers.
1375 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1376 */
1377 public static final int MEDIA_INFO_BUFFERING_END = 702;
1378
1379 /** Estimated network bandwidth information (kbps) is available; currently this event fires
1380 * simultaneously as {@link #MEDIA_INFO_BUFFERING_START} and {@link #MEDIA_INFO_BUFFERING_END}
1381 * when playing network files.
1382 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1383 * @hide
1384 */
1385 @RestrictTo(LIBRARY_GROUP)
1386 public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703;
1387
1388 /**
1389 * Update status in buffering a media source received through progressive downloading.
1390 * The received buffering percentage indicates how much of the content has been buffered
1391 * or played. For example a buffering update of 80 percent when half the content
1392 * has already been played indicates that the next 30 percent of the
1393 * content to play has been buffered.
1394 *
1395 * The {@code extra} parameter in {@code MediaPlayer2EventCallback.onInfo} is the
1396 * percentage (0-100) of the content that has been buffered or played thus far.
1397 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1398 */
1399 public static final int MEDIA_INFO_BUFFERING_UPDATE = 704;
1400
1401 /** Bad interleaving means that a media has been improperly interleaved or
1402 * not interleaved at all, e.g has all the video samples first then all the
1403 * audio ones. Video is playing but a lot of disk seeks may be happening.
1404 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1405 */
1406 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
1407
1408 /** The media cannot be seeked (e.g live stream)
1409 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1410 */
1411 public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
1412
1413 /** A new set of metadata is available.
1414 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1415 */
1416 public static final int MEDIA_INFO_METADATA_UPDATE = 802;
1417
1418 /** A new set of external-only metadata is available. Used by
1419 * JAVA framework to avoid triggering track scanning.
1420 * @hide
1421 */
1422 @RestrictTo(LIBRARY_GROUP)
1423 public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
1424
1425 /** Informs that audio is not playing. Note that playback of the video
1426 * is not interrupted.
1427 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1428 */
1429 public static final int MEDIA_INFO_AUDIO_NOT_PLAYING = 804;
1430
1431 /** Informs that video is not playing. Note that playback of the audio
1432 * is not interrupted.
1433 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1434 */
1435 public static final int MEDIA_INFO_VIDEO_NOT_PLAYING = 805;
1436
1437 /** Failed to handle timed text track properly.
1438 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1439 * {@hide}
1440 */
1441 @RestrictTo(LIBRARY_GROUP)
1442 public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
1443
1444 /** Subtitle track was not supported by the media framework.
1445 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1446 */
1447 public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
1448
1449 /** Reading the subtitle track takes too long.
1450 * @see MediaPlayer2.MediaPlayer2EventCallback#onInfo
1451 */
1452 public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
1453
1454 /**
1455 * @hide
1456 */
1457 @IntDef(flag = false, /*prefix = "MEDIA_INFO",*/ value = {
1458 MEDIA_INFO_UNKNOWN,
1459 MEDIA_INFO_STARTED_AS_NEXT,
1460 MEDIA_INFO_VIDEO_RENDERING_START,
1461 MEDIA_INFO_AUDIO_RENDERING_START,
1462 MEDIA_INFO_PLAYBACK_COMPLETE,
1463 MEDIA_INFO_PLAYLIST_END,
1464 MEDIA_INFO_PREPARED,
1465 MEDIA_INFO_VIDEO_TRACK_LAGGING,
1466 MEDIA_INFO_BUFFERING_START,
1467 MEDIA_INFO_BUFFERING_END,
1468 MEDIA_INFO_NETWORK_BANDWIDTH,
1469 MEDIA_INFO_BUFFERING_UPDATE,
1470 MEDIA_INFO_BAD_INTERLEAVING,
1471 MEDIA_INFO_NOT_SEEKABLE,
1472 MEDIA_INFO_METADATA_UPDATE,
1473 MEDIA_INFO_EXTERNAL_METADATA_UPDATE,
1474 MEDIA_INFO_AUDIO_NOT_PLAYING,
1475 MEDIA_INFO_VIDEO_NOT_PLAYING,
1476 MEDIA_INFO_TIMED_TEXT_ERROR,
1477 MEDIA_INFO_UNSUPPORTED_SUBTITLE,
1478 MEDIA_INFO_SUBTITLE_TIMED_OUT
1479 })
1480 @Retention(RetentionPolicy.SOURCE)
1481 @RestrictTo(LIBRARY_GROUP)
1482 public @interface MediaInfo {}
1483
1484 //--------------------------------------------------------------------------
1485 /** The player just completed a call {@link #attachAuxEffect}.
1486 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1487 */
1488 public static final int CALL_COMPLETED_ATTACH_AUX_EFFECT = 1;
1489
1490 /** The player just completed a call {@link #deselectTrack}.
1491 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1492 */
1493 public static final int CALL_COMPLETED_DESELECT_TRACK = 2;
1494
1495 /** The player just completed a call {@link #loopCurrent}.
1496 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1497 */
1498 public static final int CALL_COMPLETED_LOOP_CURRENT = 3;
1499
1500 /** The player just completed a call {@link #pause}.
1501 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1502 */
1503 public static final int CALL_COMPLETED_PAUSE = 4;
1504
1505 /** The player just completed a call {@link #play}.
1506 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1507 */
1508 public static final int CALL_COMPLETED_PLAY = 5;
1509
1510 /** The player just completed a call {@link #prepare}.
1511 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1512 */
1513 public static final int CALL_COMPLETED_PREPARE = 6;
1514
1515 /** The player just completed a call {@link #releaseDrm}.
1516 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1517 */
1518 public static final int CALL_COMPLETED_RELEASE_DRM = 12;
1519
1520 /** The player just completed a call {@link #restoreDrmKeys}.
1521 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1522 */
1523 public static final int CALL_COMPLETED_RESTORE_DRM_KEYS = 13;
1524
1525 /** The player just completed a call {@link #seekTo}.
1526 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1527 */
1528 public static final int CALL_COMPLETED_SEEK_TO = 14;
1529
1530 /** The player just completed a call {@link #selectTrack}.
1531 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1532 */
1533 public static final int CALL_COMPLETED_SELECT_TRACK = 15;
1534
1535 /** The player just completed a call {@link #setAudioAttributes}.
1536 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1537 */
1538 public static final int CALL_COMPLETED_SET_AUDIO_ATTRIBUTES = 16;
1539
1540 /** The player just completed a call {@link #setAudioSessionId}.
1541 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1542 */
1543 public static final int CALL_COMPLETED_SET_AUDIO_SESSION_ID = 17;
1544
1545 /** The player just completed a call {@link #setAuxEffectSendLevel}.
1546 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1547 */
1548 public static final int CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL = 18;
1549
1550 /** The player just completed a call {@link #setDataSource}.
1551 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1552 */
1553 public static final int CALL_COMPLETED_SET_DATA_SOURCE = 19;
1554
1555 /** The player just completed a call {@link #setNextDataSource}.
1556 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1557 */
1558 public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCE = 22;
1559
1560 /** The player just completed a call {@link #setNextDataSources}.
1561 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1562 */
1563 public static final int CALL_COMPLETED_SET_NEXT_DATA_SOURCES = 23;
1564
1565 /** The player just completed a call {@link #setPlaybackParams}.
1566 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1567 */
1568 public static final int CALL_COMPLETED_SET_PLAYBACK_PARAMS = 24;
1569
1570 /** The player just completed a call {@link #setPlaybackSpeed}.
1571 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1572 */
1573 public static final int CALL_COMPLETED_SET_PLAYBACK_SPEED = 25;
1574
1575 /** The player just completed a call {@link #setPlayerVolume}.
1576 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1577 */
1578 public static final int CALL_COMPLETED_SET_PLAYER_VOLUME = 26;
1579
1580 /** The player just completed a call {@link #setSurface}.
1581 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1582 */
1583 public static final int CALL_COMPLETED_SET_SURFACE = 27;
1584
1585 /** The player just completed a call {@link #setSyncParams}.
1586 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1587 */
1588 public static final int CALL_COMPLETED_SET_SYNC_PARAMS = 28;
1589
1590 /** The player just completed a call {@link #skipToNext}.
1591 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1592 */
1593 public static final int CALL_COMPLETED_SKIP_TO_NEXT = 29;
1594
1595 /** The player just completed a call {@code notifyWhenCommandLabelReached}.
1596 * @see MediaPlayer2.MediaPlayer2EventCallback#onCommandLabelReached
1597 * @hide
1598 */
1599 @RestrictTo(LIBRARY_GROUP)
1600 public static final int CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED = 1003;
1601
1602 /**
1603 * @hide
1604 */
1605 @IntDef(flag = false, /*prefix = "CALL_COMPLETED",*/ value = {
1606 CALL_COMPLETED_ATTACH_AUX_EFFECT,
1607 CALL_COMPLETED_DESELECT_TRACK,
1608 CALL_COMPLETED_LOOP_CURRENT,
1609 CALL_COMPLETED_PAUSE,
1610 CALL_COMPLETED_PLAY,
1611 CALL_COMPLETED_PREPARE,
1612 CALL_COMPLETED_RELEASE_DRM,
1613 CALL_COMPLETED_RESTORE_DRM_KEYS,
1614 CALL_COMPLETED_SEEK_TO,
1615 CALL_COMPLETED_SELECT_TRACK,
1616 CALL_COMPLETED_SET_AUDIO_ATTRIBUTES,
1617 CALL_COMPLETED_SET_AUDIO_SESSION_ID,
1618 CALL_COMPLETED_SET_AUX_EFFECT_SEND_LEVEL,
1619 CALL_COMPLETED_SET_DATA_SOURCE,
1620 CALL_COMPLETED_SET_NEXT_DATA_SOURCE,
1621 CALL_COMPLETED_SET_NEXT_DATA_SOURCES,
1622 CALL_COMPLETED_SET_PLAYBACK_PARAMS,
1623 CALL_COMPLETED_SET_PLAYBACK_SPEED,
1624 CALL_COMPLETED_SET_PLAYER_VOLUME,
1625 CALL_COMPLETED_SET_SURFACE,
1626 CALL_COMPLETED_SET_SYNC_PARAMS,
1627 CALL_COMPLETED_SKIP_TO_NEXT,
1628 CALL_COMPLETED_NOTIFY_WHEN_COMMAND_LABEL_REACHED
1629 })
1630 @Retention(RetentionPolicy.SOURCE)
1631 @RestrictTo(LIBRARY_GROUP)
1632 public @interface CallCompleted {}
1633
1634 /** Status code represents that call is completed without an error.
1635 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1636 */
1637 public static final int CALL_STATUS_NO_ERROR = 0;
1638
1639 /** Status code represents that call is ended with an unknown error.
1640 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1641 */
1642 public static final int CALL_STATUS_ERROR_UNKNOWN = Integer.MIN_VALUE;
1643
1644 /** Status code represents that the player is not in valid state for the operation.
1645 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1646 */
1647 public static final int CALL_STATUS_INVALID_OPERATION = 1;
1648
1649 /** Status code represents that the argument is illegal.
1650 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1651 */
1652 public static final int CALL_STATUS_BAD_VALUE = 2;
1653
1654 /** Status code represents that the operation is not allowed.
1655 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1656 */
1657 public static final int CALL_STATUS_PERMISSION_DENIED = 3;
1658
1659 /** Status code represents a file or network related operation error.
1660 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1661 */
1662 public static final int CALL_STATUS_ERROR_IO = 4;
1663
1664 /** Status code represents that DRM operation is called before preparing a DRM scheme through
1665 * {@link #prepareDrm}.
1666 * @see MediaPlayer2.MediaPlayer2EventCallback#onCallCompleted
1667 */
1668 public static final int CALL_STATUS_NO_DRM_SCHEME = 5;
1669
1670 /**
1671 * @hide
1672 */
1673 @IntDef(flag = false, /*prefix = "CALL_STATUS",*/ value = {
1674 CALL_STATUS_NO_ERROR,
1675 CALL_STATUS_ERROR_UNKNOWN,
1676 CALL_STATUS_INVALID_OPERATION,
1677 CALL_STATUS_BAD_VALUE,
1678 CALL_STATUS_PERMISSION_DENIED,
1679 CALL_STATUS_ERROR_IO,
1680 CALL_STATUS_NO_DRM_SCHEME})
1681 @Retention(RetentionPolicy.SOURCE)
1682 @RestrictTo(LIBRARY_GROUP)
1683 public @interface CallStatus {}
1684
1685 // Modular DRM begin
1686
1687 /**
1688 * Interface definition of a callback to be invoked when the app
1689 * can do DRM configuration (get/set properties) before the session
1690 * is opened. This facilitates configuration of the properties, like
1691 * 'securityLevel', which has to be set after DRM scheme creation but
1692 * before the DRM session is opened.
1693 *
1694 * The only allowed DRM calls in this listener are {@link #getDrmPropertyString}
1695 * and {@link #setDrmPropertyString}.
1696 */
1697 public interface OnDrmConfigHelper {
1698 /**
1699 * Called to give the app the opportunity to configure DRM before the session is created
1700 *
1701 * @param mp the {@code MediaPlayer2} associated with this callback
1702 * @param dsd the DataSourceDesc of this data source
1703 */
1704 void onDrmConfig(MediaPlayer2 mp, DataSourceDesc dsd);
1705 }
1706
1707 /**
1708 * Register a callback to be invoked for configuration of the DRM object before
1709 * the session is created.
1710 * The callback will be invoked synchronously during the execution
1711 * of {@link #prepareDrm(UUID uuid)}.
1712 *
1713 * @param listener the callback that will be run
1714 */
1715 // This is a synchronous call.
1716 public abstract void setOnDrmConfigHelper(OnDrmConfigHelper listener);
1717
1718 /**
1719 * Interface definition for callbacks to be invoked when the player has the corresponding
1720 * DRM events.
1721 */
1722 public abstract static class DrmEventCallback {
1723 /**
1724 * Called to indicate DRM info is available
1725 *
1726 * @param mp the {@code MediaPlayer2} associated with this callback
1727 * @param dsd the DataSourceDesc of this data source
1728 * @param drmInfo DRM info of the source including PSSH, and subset
1729 * of crypto schemes supported by this device
1730 */
1731 public void onDrmInfo(MediaPlayer2 mp, DataSourceDesc dsd, DrmInfo drmInfo) { }
1732
1733 /**
1734 * Called to notify the client that {@link #prepareDrm} is finished and ready for
1735 * key request/response.
1736 *
1737 * @param mp the {@code MediaPlayer2} associated with this callback
1738 * @param dsd the DataSourceDesc of this data source
1739 * @param status the result of DRM preparation.
1740 */
1741 public void onDrmPrepared(
1742 MediaPlayer2 mp, DataSourceDesc dsd, @PrepareDrmStatusCode int status) { }
1743 }
1744
1745 /**
1746 * Sets the callback to be invoked when the media source is ready for playback.
1747 *
1748 * @param eventCallback the callback that will be run
1749 * @param executor the executor through which the callback should be invoked
1750 */
1751 // This is a synchronous call.
1752 public abstract void setDrmEventCallback(@NonNull Executor executor,
1753 @NonNull DrmEventCallback eventCallback);
1754
1755 /**
1756 * Clears the {@link DrmEventCallback}.
1757 */
1758 // This is a synchronous call.
1759 public abstract void clearDrmEventCallback();
1760
1761 /**
1762 * The status codes for {@link DrmEventCallback#onDrmPrepared} listener.
1763 * <p>
1764 *
1765 * DRM preparation has succeeded.
1766 */
1767 public static final int PREPARE_DRM_STATUS_SUCCESS = 0;
1768
1769 /**
1770 * The device required DRM provisioning but couldn't reach the provisioning server.
1771 */
1772 public static final int PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR = 1;
1773
1774 /**
1775 * The device required DRM provisioning but the provisioning server denied the request.
1776 */
1777 public static final int PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR = 2;
1778
1779 /**
1780 * The DRM preparation has failed .
1781 */
1782 public static final int PREPARE_DRM_STATUS_PREPARATION_ERROR = 3;
1783
1784
1785 /** @hide */
1786 @IntDef(flag = false, /*prefix = "PREPARE_DRM_STATUS",*/ value = {
1787 PREPARE_DRM_STATUS_SUCCESS,
1788 PREPARE_DRM_STATUS_PROVISIONING_NETWORK_ERROR,
1789 PREPARE_DRM_STATUS_PROVISIONING_SERVER_ERROR,
1790 PREPARE_DRM_STATUS_PREPARATION_ERROR,
1791 })
1792 @Retention(RetentionPolicy.SOURCE)
1793 @RestrictTo(LIBRARY_GROUP)
1794 public @interface PrepareDrmStatusCode {}
1795
1796 /**
1797 * Retrieves the DRM Info associated with the current source
1798 *
1799 * @throws IllegalStateException if called before being prepared
1800 */
1801 public abstract DrmInfo getDrmInfo();
1802
1803 /**
1804 * Prepares the DRM for the current source
1805 * <p>
1806 * If {@link OnDrmConfigHelper} is registered, it will be called during
1807 * preparation to allow configuration of the DRM properties before opening the
1808 * DRM session. Note that the callback is called synchronously in the thread that called
1809 * {@link #prepareDrm}. It should be used only for a series of {@code getDrmPropertyString}
1810 * and {@code setDrmPropertyString} calls and refrain from any lengthy operation.
1811 * <p>
1812 * If the device has not been provisioned before, this call also provisions the device
1813 * which involves accessing the provisioning server and can take a variable time to
1814 * complete depending on the network connectivity.
1815 * If {@code OnDrmPreparedListener} is registered, prepareDrm() runs in non-blocking
1816 * mode by launching the provisioning in the background and returning. The listener
1817 * will be called when provisioning and preparation has finished. If a
1818 * {@code OnDrmPreparedListener} is not registered, prepareDrm() waits till provisioning
1819 * and preparation has finished, i.e., runs in blocking mode.
1820 * <p>
1821 * If {@code OnDrmPreparedListener} is registered, it is called to indicate the DRM
1822 * session being ready. The application should not make any assumption about its call
1823 * sequence (e.g., before or after prepareDrm returns), or the thread context that will
1824 * execute the listener (unless the listener is registered with a handler thread).
1825 * <p>
1826 *
1827 * @param uuid The UUID of the crypto scheme. If not known beforehand, it can be retrieved
1828 * from the source through {@code getDrmInfo} or registering a {@code onDrmInfoListener}.
1829 *
1830 * @throws IllegalStateException if called before being prepared or the DRM was
1831 * prepared already
1832 * @throws UnsupportedSchemeException if the crypto scheme is not supported
1833 * @throws ResourceBusyException if required DRM resources are in use
1834 * @throws ProvisioningNetworkErrorException if provisioning is required but failed due to a
1835 * network error
1836 * @throws ProvisioningServerErrorException if provisioning is required but failed due to
1837 * the request denied by the provisioning server
1838 */
1839 // This is a synchronous call.
1840 public abstract void prepareDrm(@NonNull UUID uuid)
1841 throws UnsupportedSchemeException, ResourceBusyException,
1842 ProvisioningNetworkErrorException, ProvisioningServerErrorException;
1843
1844 /**
1845 * Releases the DRM session
1846 * <p>
1847 * The player has to have an active DRM session and be in stopped, or prepared
1848 * state before this call is made.
1849 * A {@code reset()} call will release the DRM session implicitly.
1850 *
1851 * @throws NoDrmSchemeException if there is no active DRM session to release
1852 */
1853 // This is an asynchronous call.
1854 public abstract void releaseDrm() throws NoDrmSchemeException;
1855
1856 /**
1857 * A key request/response exchange occurs between the app and a license server
1858 * to obtain or release keys used to decrypt encrypted content.
1859 * <p>
1860 * getDrmKeyRequest() is used to obtain an opaque key request byte array that is
1861 * delivered to the license server. The opaque key request byte array is returned
1862 * in KeyRequest.data. The recommended URL to deliver the key request to is
1863 * returned in KeyRequest.defaultUrl.
1864 * <p>
1865 * After the app has received the key request response from the server,
1866 * it should deliver to the response to the DRM engine plugin using the method
1867 * {@link #provideDrmKeyResponse}.
1868 *
1869 * @param keySetId is the key-set identifier of the offline keys being released when keyType is
1870 * {@link MediaDrm#KEY_TYPE_RELEASE}. It should be set to null for other key requests, when
1871 * keyType is {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}.
1872 *
1873 * @param initData is the container-specific initialization data when the keyType is
1874 * {@link MediaDrm#KEY_TYPE_STREAMING} or {@link MediaDrm#KEY_TYPE_OFFLINE}. Its meaning is
1875 * interpreted based on the mime type provided in the mimeType parameter. It could
1876 * contain, for example, the content ID, key ID or other data obtained from the content
1877 * metadata that is required in generating the key request.
1878 * When the keyType is {@link MediaDrm#KEY_TYPE_RELEASE}, it should be set to null.
1879 *
1880 * @param mimeType identifies the mime type of the content
1881 *
1882 * @param keyType specifies the type of the request. The request may be to acquire
1883 * keys for streaming, {@link MediaDrm#KEY_TYPE_STREAMING}, or for offline content
1884 * {@link MediaDrm#KEY_TYPE_OFFLINE}, or to release previously acquired
1885 * keys ({@link MediaDrm#KEY_TYPE_RELEASE}), which are identified by a keySetId.
1886 *
1887 * @param optionalParameters are included in the key request message to
1888 * allow a client application to provide additional message parameters to the server.
1889 * This may be {@code null} if no additional parameters are to be sent.
1890 *
1891 * @throws NoDrmSchemeException if there is no active DRM session
1892 */
1893 @NonNull
1894 public abstract MediaDrm.KeyRequest getDrmKeyRequest(
1895 @Nullable byte[] keySetId, @Nullable byte[] initData,
1896 @Nullable String mimeType, int keyType,
1897 @Nullable Map<String, String> optionalParameters)
1898 throws NoDrmSchemeException;
1899
1900 /**
1901 * A key response is received from the license server by the app, then it is
1902 * provided to the DRM engine plugin using provideDrmKeyResponse. When the
1903 * response is for an offline key request, a key-set identifier is returned that
1904 * can be used to later restore the keys to a new session with the method
1905 * {@ link # restoreDrmKeys}.
1906 * When the response is for a streaming or release request, null is returned.
1907 *
1908 * @param keySetId When the response is for a release request, keySetId identifies
1909 * the saved key associated with the release request (i.e., the same keySetId
1910 * passed to the earlier {@ link # getDrmKeyRequest} call. It MUST be null when the
1911 * response is for either streaming or offline key requests.
1912 *
1913 * @param response the byte array response from the server
1914 *
1915 * @throws NoDrmSchemeException if there is no active DRM session
1916 * @throws DeniedByServerException if the response indicates that the
1917 * server rejected the request
1918 */
1919 // This is a synchronous call.
1920 public abstract byte[] provideDrmKeyResponse(
1921 @Nullable byte[] keySetId, @NonNull byte[] response)
1922 throws NoDrmSchemeException, DeniedByServerException;
1923
1924 /**
1925 * Restore persisted offline keys into a new session. keySetId identifies the
1926 * keys to load, obtained from a prior call to {@link #provideDrmKeyResponse}.
1927 *
1928 * @param keySetId identifies the saved key set to restore
1929 */
1930 // This is an asynchronous call.
1931 public abstract void restoreDrmKeys(@NonNull byte[] keySetId)
1932 throws NoDrmSchemeException;
1933
1934 /**
1935 * Read a DRM engine plugin String property value, given the property name string.
1936 * <p>
1937 * @param propertyName the property name
1938 *
1939 * Standard fields names are:
1940 * {@link MediaDrm#PROPERTY_VENDOR}, {@link MediaDrm#PROPERTY_VERSION},
1941 * {@link MediaDrm#PROPERTY_DESCRIPTION}, {@link MediaDrm#PROPERTY_ALGORITHMS}
1942 */
1943 @NonNull
1944 public abstract String getDrmPropertyString(
1945 @NonNull String propertyName)
1946 throws NoDrmSchemeException;
1947
1948 /**
1949 * Set a DRM engine plugin String property value.
1950 * <p>
1951 * @param propertyName the property name
1952 * @param value the property value
1953 *
1954 * Standard fields names are:
1955 * {@link MediaDrm#PROPERTY_VENDOR}, {@link MediaDrm#PROPERTY_VERSION},
1956 * {@link MediaDrm#PROPERTY_DESCRIPTION}, {@link MediaDrm#PROPERTY_ALGORITHMS}
1957 */
1958 // This is a synchronous call.
1959 public abstract void setDrmPropertyString(
1960 @NonNull String propertyName, @NonNull String value)
1961 throws NoDrmSchemeException;
1962
1963 /**
1964 * Encapsulates the DRM properties of the source.
1965 */
1966 public abstract static class DrmInfo {
1967 /**
1968 * Returns the PSSH info of the data source for each supported DRM scheme.
1969 */
1970 public abstract Map<UUID, byte[]> getPssh();
1971
1972 /**
1973 * Returns the intersection of the data source and the device DRM schemes.
1974 * It effectively identifies the subset of the source's DRM schemes which
1975 * are supported by the device too.
1976 */
1977 public abstract List<UUID> getSupportedSchemes();
1978 }; // DrmInfo
1979
1980 /**
1981 * Thrown when a DRM method is called before preparing a DRM scheme through prepareDrm().
1982 * Extends MediaDrm.MediaDrmException
1983 */
1984 public static class NoDrmSchemeException extends MediaDrmException {
1985 public NoDrmSchemeException(String detailMessage) {
1986 super(detailMessage);
1987 }
1988 }
1989
1990 /**
1991 * Thrown when the device requires DRM provisioning but the provisioning attempt has
1992 * failed due to a network error (Internet reachability, timeout, etc.).
1993 * Extends MediaDrm.MediaDrmException
1994 */
1995 public static class ProvisioningNetworkErrorException extends MediaDrmException {
1996 public ProvisioningNetworkErrorException(String detailMessage) {
1997 super(detailMessage);
1998 }
1999 }
2000
2001 /**
2002 * Thrown when the device requires DRM provisioning but the provisioning attempt has
2003 * failed due to the provisioning server denying the request.
2004 * Extends MediaDrm.MediaDrmException
2005 */
2006 public static class ProvisioningServerErrorException extends MediaDrmException {
2007 public ProvisioningServerErrorException(String detailMessage) {
2008 super(detailMessage);
2009 }
2010 }
2011}