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