Home | History | Annotate | Download | only in media
      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.content.ContentResolver;
     24 import android.content.Context;
     25 import android.content.res.AssetFileDescriptor;
     26 import android.net.Uri;
     27 import android.os.Handler;
     28 import android.os.HandlerThread;
     29 import android.os.IBinder;
     30 import android.os.Looper;
     31 import android.os.Message;
     32 import android.os.Parcel;
     33 import android.os.Parcelable;
     34 import android.os.Process;
     35 import android.os.PowerManager;
     36 import android.os.SystemProperties;
     37 import android.provider.Settings;
     38 import android.system.ErrnoException;
     39 import android.system.OsConstants;
     40 import android.util.Log;
     41 import android.util.Pair;
     42 import android.view.Surface;
     43 import android.view.SurfaceHolder;
     44 import android.widget.VideoView;
     45 import android.graphics.SurfaceTexture;
     46 import android.media.AudioManager;
     47 import android.media.MediaFormat;
     48 import android.media.MediaTimeProvider;
     49 import android.media.PlaybackParams;
     50 import android.media.SubtitleController;
     51 import android.media.SubtitleController.Anchor;
     52 import android.media.SubtitleData;
     53 import android.media.SubtitleTrack.RenderingWidget;
     54 import android.media.SyncParams;
     55 
     56 import com.android.internal.util.Preconditions;
     57 
     58 import libcore.io.IoBridge;
     59 import libcore.io.Libcore;
     60 
     61 import java.io.ByteArrayOutputStream;
     62 import java.io.File;
     63 import java.io.FileDescriptor;
     64 import java.io.FileInputStream;
     65 import java.io.IOException;
     66 import java.io.InputStream;
     67 import java.lang.Runnable;
     68 import java.lang.annotation.Retention;
     69 import java.lang.annotation.RetentionPolicy;
     70 import java.net.InetSocketAddress;
     71 import java.util.BitSet;
     72 import java.util.Map;
     73 import java.util.Scanner;
     74 import java.util.Set;
     75 import java.util.Vector;
     76 import java.lang.ref.WeakReference;
     77 
     78 /**
     79  * MediaPlayer class can be used to control playback
     80  * of audio/video files and streams. An example on how to use the methods in
     81  * this class can be found in {@link android.widget.VideoView}.
     82  *
     83  * <p>Topics covered here are:
     84  * <ol>
     85  * <li><a href="#StateDiagram">State Diagram</a>
     86  * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a>
     87  * <li><a href="#Permissions">Permissions</a>
     88  * <li><a href="#Callbacks">Register informational and error callbacks</a>
     89  * </ol>
     90  *
     91  * <div class="special reference">
     92  * <h3>Developer Guides</h3>
     93  * <p>For more information about how to use MediaPlayer, read the
     94  * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p>
     95  * </div>
     96  *
     97  * <a name="StateDiagram"></a>
     98  * <h3>State Diagram</h3>
     99  *
    100  * <p>Playback control of audio/video files and streams is managed as a state
    101  * machine. The following diagram shows the life cycle and the states of a
    102  * MediaPlayer object driven by the supported playback control operations.
    103  * The ovals represent the states a MediaPlayer object may reside
    104  * in. The arcs represent the playback control operations that drive the object
    105  * state transition. There are two types of arcs. The arcs with a single arrow
    106  * head represent synchronous method calls, while those with
    107  * a double arrow head represent asynchronous method calls.</p>
    108  *
    109  * <p><img src="../../../images/mediaplayer_state_diagram.gif"
    110  *         alt="MediaPlayer State diagram"
    111  *         border="0" /></p>
    112  *
    113  * <p>From this state diagram, one can see that a MediaPlayer object has the
    114  *    following states:</p>
    115  * <ul>
    116  *     <li>When a MediaPlayer object is just created using <code>new</code> or
    117  *         after {@link #reset()} is called, it is in the <em>Idle</em> state; and after
    118  *         {@link #release()} is called, it is in the <em>End</em> state. Between these
    119  *         two states is the life cycle of the MediaPlayer object.
    120  *         <ul>
    121  *         <li>There is a subtle but important difference between a newly constructed
    122  *         MediaPlayer object and the MediaPlayer object after {@link #reset()}
    123  *         is called. It is a programming error to invoke methods such
    124  *         as {@link #getCurrentPosition()},
    125  *         {@link #getDuration()}, {@link #getVideoHeight()},
    126  *         {@link #getVideoWidth()}, {@link #setAudioStreamType(int)},
    127  *         {@link #setLooping(boolean)},
    128  *         {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()},
    129  *         {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or
    130  *         {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these
    131  *         methods is called right after a MediaPlayer object is constructed,
    132  *         the user supplied callback method OnErrorListener.onError() won't be
    133  *         called by the internal player engine and the object state remains
    134  *         unchanged; but if these methods are called right after {@link #reset()},
    135  *         the user supplied callback method OnErrorListener.onError() will be
    136  *         invoked by the internal player engine and the object will be
    137  *         transfered to the <em>Error</em> state. </li>
    138  *         <li>It is also recommended that once
    139  *         a MediaPlayer object is no longer being used, call {@link #release()} immediately
    140  *         so that resources used by the internal player engine associated with the
    141  *         MediaPlayer object can be released immediately. Resource may include
    142  *         singleton resources such as hardware acceleration components and
    143  *         failure to call {@link #release()} may cause subsequent instances of
    144  *         MediaPlayer objects to fallback to software implementations or fail
    145  *         altogether. Once the MediaPlayer
    146  *         object is in the <em>End</em> state, it can no longer be used and
    147  *         there is no way to bring it back to any other state. </li>
    148  *         <li>Furthermore,
    149  *         the MediaPlayer objects created using <code>new</code> is in the
    150  *         <em>Idle</em> state, while those created with one
    151  *         of the overloaded convenient <code>create</code> methods are <em>NOT</em>
    152  *         in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em>
    153  *         state if the creation using <code>create</code> method is successful.
    154  *         </li>
    155  *         </ul>
    156  *         </li>
    157  *     <li>In general, some playback control operation may fail due to various
    158  *         reasons, such as unsupported audio/video format, poorly interleaved
    159  *         audio/video, resolution too high, streaming timeout, and the like.
    160  *         Thus, error reporting and recovery is an important concern under
    161  *         these circumstances. Sometimes, due to programming errors, invoking a playback
    162  *         control operation in an invalid state may also occur. Under all these
    163  *         error conditions, the internal player engine invokes a user supplied
    164  *         OnErrorListener.onError() method if an OnErrorListener has been
    165  *         registered beforehand via
    166  *         {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}.
    167  *         <ul>
    168  *         <li>It is important to note that once an error occurs, the
    169  *         MediaPlayer object enters the <em>Error</em> state (except as noted
    170  *         above), even if an error listener has not been registered by the application.</li>
    171  *         <li>In order to reuse a MediaPlayer object that is in the <em>
    172  *         Error</em> state and recover from the error,
    173  *         {@link #reset()} can be called to restore the object to its <em>Idle</em>
    174  *         state.</li>
    175  *         <li>It is good programming practice to have your application
    176  *         register a OnErrorListener to look out for error notifications from
    177  *         the internal player engine.</li>
    178  *         <li>IllegalStateException is
    179  *         thrown to prevent programming errors such as calling {@link #prepare()},
    180  *         {@link #prepareAsync()}, or one of the overloaded <code>setDataSource
    181  *         </code> methods in an invalid state. </li>
    182  *         </ul>
    183  *         </li>
    184  *     <li>Calling
    185  *         {@link #setDataSource(FileDescriptor)}, or
    186  *         {@link #setDataSource(String)}, or
    187  *         {@link #setDataSource(Context, Uri)}, or
    188  *         {@link #setDataSource(FileDescriptor, long, long)}, or
    189  *         {@link #setDataSource(MediaDataSource)} transfers a
    190  *         MediaPlayer object in the <em>Idle</em> state to the
    191  *         <em>Initialized</em> state.
    192  *         <ul>
    193  *         <li>An IllegalStateException is thrown if
    194  *         setDataSource() is called in any other state.</li>
    195  *         <li>It is good programming
    196  *         practice to always look out for <code>IllegalArgumentException</code>
    197  *         and <code>IOException</code> that may be thrown from the overloaded
    198  *         <code>setDataSource</code> methods.</li>
    199  *         </ul>
    200  *         </li>
    201  *     <li>A MediaPlayer object must first enter the <em>Prepared</em> state
    202  *         before playback can be started.
    203  *         <ul>
    204  *         <li>There are two ways (synchronous vs.
    205  *         asynchronous) that the <em>Prepared</em> state can be reached:
    206  *         either a call to {@link #prepare()} (synchronous) which
    207  *         transfers the object to the <em>Prepared</em> state once the method call
    208  *         returns, or a call to {@link #prepareAsync()} (asynchronous) which
    209  *         first transfers the object to the <em>Preparing</em> state after the
    210  *         call returns (which occurs almost right way) while the internal
    211  *         player engine continues working on the rest of preparation work
    212  *         until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns,
    213  *         the internal player engine then calls a user supplied callback method,
    214  *         onPrepared() of the OnPreparedListener interface, if an
    215  *         OnPreparedListener is registered beforehand via {@link
    216  *         #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li>
    217  *         <li>It is important to note that
    218  *         the <em>Preparing</em> state is a transient state, and the behavior
    219  *         of calling any method with side effect while a MediaPlayer object is
    220  *         in the <em>Preparing</em> state is undefined.</li>
    221  *         <li>An IllegalStateException is
    222  *         thrown if {@link #prepare()} or {@link #prepareAsync()} is called in
    223  *         any other state.</li>
    224  *         <li>While in the <em>Prepared</em> state, properties
    225  *         such as audio/sound volume, screenOnWhilePlaying, looping can be
    226  *         adjusted by invoking the corresponding set methods.</li>
    227  *         </ul>
    228  *         </li>
    229  *     <li>To start the playback, {@link #start()} must be called. After
    230  *         {@link #start()} returns successfully, the MediaPlayer object is in the
    231  *         <em>Started</em> state. {@link #isPlaying()} can be called to test
    232  *         whether the MediaPlayer object is in the <em>Started</em> state.
    233  *         <ul>
    234  *         <li>While in the <em>Started</em> state, the internal player engine calls
    235  *         a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback
    236  *         method if a OnBufferingUpdateListener has been registered beforehand
    237  *         via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}.
    238  *         This callback allows applications to keep track of the buffering status
    239  *         while streaming audio/video.</li>
    240  *         <li>Calling {@link #start()} has not effect
    241  *         on a MediaPlayer object that is already in the <em>Started</em> state.</li>
    242  *         </ul>
    243  *         </li>
    244  *     <li>Playback can be paused and stopped, and the current playback position
    245  *         can be adjusted. Playback can be paused via {@link #pause()}. When the call to
    246  *         {@link #pause()} returns, the MediaPlayer object enters the
    247  *         <em>Paused</em> state. Note that the transition from the <em>Started</em>
    248  *         state to the <em>Paused</em> state and vice versa happens
    249  *         asynchronously in the player engine. It may take some time before
    250  *         the state is updated in calls to {@link #isPlaying()}, and it can be
    251  *         a number of seconds in the case of streamed content.
    252  *         <ul>
    253  *         <li>Calling {@link #start()} to resume playback for a paused
    254  *         MediaPlayer object, and the resumed playback
    255  *         position is the same as where it was paused. When the call to
    256  *         {@link #start()} returns, the paused MediaPlayer object goes back to
    257  *         the <em>Started</em> state.</li>
    258  *         <li>Calling {@link #pause()} has no effect on
    259  *         a MediaPlayer object that is already in the <em>Paused</em> state.</li>
    260  *         </ul>
    261  *         </li>
    262  *     <li>Calling  {@link #stop()} stops playback and causes a
    263  *         MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared
    264  *         </em> or <em>PlaybackCompleted</em> state to enter the
    265  *         <em>Stopped</em> state.
    266  *         <ul>
    267  *         <li>Once in the <em>Stopped</em> state, playback cannot be started
    268  *         until {@link #prepare()} or {@link #prepareAsync()} are called to set
    269  *         the MediaPlayer object to the <em>Prepared</em> state again.</li>
    270  *         <li>Calling {@link #stop()} has no effect on a MediaPlayer
    271  *         object that is already in the <em>Stopped</em> state.</li>
    272  *         </ul>
    273  *         </li>
    274  *     <li>The playback position can be adjusted with a call to
    275  *         {@link #seekTo(int)}.
    276  *         <ul>
    277  *         <li>Although the asynchronuous {@link #seekTo(int)}
    278  *         call returns right way, the actual seek operation may take a while to
    279  *         finish, especially for audio/video being streamed. When the actual
    280  *         seek operation completes, the internal player engine calls a user
    281  *         supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener
    282  *         has been registered beforehand via
    283  *         {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li>
    284  *         <li>Please
    285  *         note that {@link #seekTo(int)} can also be called in the other states,
    286  *         such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted
    287  *         </em> state.</li>
    288  *         <li>Furthermore, the actual current playback position
    289  *         can be retrieved with a call to {@link #getCurrentPosition()}, which
    290  *         is helpful for applications such as a Music player that need to keep
    291  *         track of the playback progress.</li>
    292  *         </ul>
    293  *         </li>
    294  *     <li>When the playback reaches the end of stream, the playback completes.
    295  *         <ul>
    296  *         <li>If the looping mode was being set to <var>true</var>with
    297  *         {@link #setLooping(boolean)}, the MediaPlayer object shall remain in
    298  *         the <em>Started</em> state.</li>
    299  *         <li>If the looping mode was set to <var>false
    300  *         </var>, the player engine calls a user supplied callback method,
    301  *         OnCompletion.onCompletion(), if a OnCompletionListener is registered
    302  *         beforehand via {@link #setOnCompletionListener(OnCompletionListener)}.
    303  *         The invoke of the callback signals that the object is now in the <em>
    304  *         PlaybackCompleted</em> state.</li>
    305  *         <li>While in the <em>PlaybackCompleted</em>
    306  *         state, calling {@link #start()} can restart the playback from the
    307  *         beginning of the audio/video source.</li>
    308  * </ul>
    309  *
    310  *
    311  * <a name="Valid_and_Invalid_States"></a>
    312  * <h3>Valid and invalid states</h3>
    313  *
    314  * <table border="0" cellspacing="0" cellpadding="0">
    315  * <tr><td>Method Name </p></td>
    316  *     <td>Valid Sates </p></td>
    317  *     <td>Invalid States </p></td>
    318  *     <td>Comments </p></td></tr>
    319  * <tr><td>attachAuxEffect </p></td>
    320  *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
    321  *     <td>{Idle, Error} </p></td>
    322  *     <td>This method must be called after setDataSource.
    323  *     Calling it does not change the object state. </p></td></tr>
    324  * <tr><td>getAudioSessionId </p></td>
    325  *     <td>any </p></td>
    326  *     <td>{} </p></td>
    327  *     <td>This method can be called in any state and calling it does not change
    328  *         the object state. </p></td></tr>
    329  * <tr><td>getCurrentPosition </p></td>
    330  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
    331  *         PlaybackCompleted} </p></td>
    332  *     <td>{Error}</p></td>
    333  *     <td>Successful invoke of this method in a valid state does not change the
    334  *         state. Calling this method in an invalid state transfers the object
    335  *         to the <em>Error</em> state. </p></td></tr>
    336  * <tr><td>getDuration </p></td>
    337  *     <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
    338  *     <td>{Idle, Initialized, Error} </p></td>
    339  *     <td>Successful invoke of this method in a valid state does not change the
    340  *         state. Calling this method in an invalid state transfers the object
    341  *         to the <em>Error</em> state. </p></td></tr>
    342  * <tr><td>getVideoHeight </p></td>
    343  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
    344  *         PlaybackCompleted}</p></td>
    345  *     <td>{Error}</p></td>
    346  *     <td>Successful invoke of this method in a valid state does not change the
    347  *         state. Calling this method in an invalid state transfers the object
    348  *         to the <em>Error</em> state.  </p></td></tr>
    349  * <tr><td>getVideoWidth </p></td>
    350  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
    351  *         PlaybackCompleted}</p></td>
    352  *     <td>{Error}</p></td>
    353  *     <td>Successful invoke of this method in a valid state does not change
    354  *         the state. Calling this method in an invalid state transfers the
    355  *         object to the <em>Error</em> state. </p></td></tr>
    356  * <tr><td>isPlaying </p></td>
    357  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
    358  *          PlaybackCompleted}</p></td>
    359  *     <td>{Error}</p></td>
    360  *     <td>Successful invoke of this method in a valid state does not change
    361  *         the state. Calling this method in an invalid state transfers the
    362  *         object to the <em>Error</em> state. </p></td></tr>
    363  * <tr><td>pause </p></td>
    364  *     <td>{Started, Paused, PlaybackCompleted}</p></td>
    365  *     <td>{Idle, Initialized, Prepared, Stopped, Error}</p></td>
    366  *     <td>Successful invoke of this method in a valid state transfers the
    367  *         object to the <em>Paused</em> state. Calling this method in an
    368  *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
    369  * <tr><td>prepare </p></td>
    370  *     <td>{Initialized, Stopped} </p></td>
    371  *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
    372  *     <td>Successful invoke of this method in a valid state transfers the
    373  *         object to the <em>Prepared</em> state. Calling this method in an
    374  *         invalid state throws an IllegalStateException.</p></td></tr>
    375  * <tr><td>prepareAsync </p></td>
    376  *     <td>{Initialized, Stopped} </p></td>
    377  *     <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td>
    378  *     <td>Successful invoke of this method in a valid state transfers the
    379  *         object to the <em>Preparing</em> state. Calling this method in an
    380  *         invalid state throws an IllegalStateException.</p></td></tr>
    381  * <tr><td>release </p></td>
    382  *     <td>any </p></td>
    383  *     <td>{} </p></td>
    384  *     <td>After {@link #release()}, the object is no longer available. </p></td></tr>
    385  * <tr><td>reset </p></td>
    386  *     <td>{Idle, Initialized, Prepared, Started, Paused, Stopped,
    387  *         PlaybackCompleted, Error}</p></td>
    388  *     <td>{}</p></td>
    389  *     <td>After {@link #reset()}, the object is like being just created.</p></td></tr>
    390  * <tr><td>seekTo </p></td>
    391  *     <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td>
    392  *     <td>{Idle, Initialized, Stopped, Error}</p></td>
    393  *     <td>Successful invoke of this method in a valid state does not change
    394  *         the state. Calling this method in an invalid state transfers the
    395  *         object to the <em>Error</em> state. </p></td></tr>
    396  * <tr><td>setAudioAttributes </p></td>
    397  *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
    398  *          PlaybackCompleted}</p></td>
    399  *     <td>{Error}</p></td>
    400  *     <td>Successful invoke of this method does not change the state. In order for the
    401  *         target audio attributes type to become effective, this method must be called before
    402  *         prepare() or prepareAsync().</p></td></tr>
    403  * <tr><td>setAudioSessionId </p></td>
    404  *     <td>{Idle} </p></td>
    405  *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
    406  *          Error} </p></td>
    407  *     <td>This method must be called in idle state as the audio session ID must be known before
    408  *         calling setDataSource. Calling it does not change the object state. </p></td></tr>
    409  * <tr><td>setAudioStreamType </p></td>
    410  *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
    411  *          PlaybackCompleted}</p></td>
    412  *     <td>{Error}</p></td>
    413  *     <td>Successful invoke of this method does not change the state. In order for the
    414  *         target audio stream type to become effective, this method must be called before
    415  *         prepare() or prepareAsync().</p></td></tr>
    416  * <tr><td>setAuxEffectSendLevel </p></td>
    417  *     <td>any</p></td>
    418  *     <td>{} </p></td>
    419  *     <td>Calling this method does not change the object state. </p></td></tr>
    420  * <tr><td>setDataSource </p></td>
    421  *     <td>{Idle} </p></td>
    422  *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted,
    423  *          Error} </p></td>
    424  *     <td>Successful invoke of this method in a valid state transfers the
    425  *         object to the <em>Initialized</em> state. Calling this method in an
    426  *         invalid state throws an IllegalStateException.</p></td></tr>
    427  * <tr><td>setDisplay </p></td>
    428  *     <td>any </p></td>
    429  *     <td>{} </p></td>
    430  *     <td>This method can be called in any state and calling it does not change
    431  *         the object state. </p></td></tr>
    432  * <tr><td>setSurface </p></td>
    433  *     <td>any </p></td>
    434  *     <td>{} </p></td>
    435  *     <td>This method can be called in any state and calling it does not change
    436  *         the object state. </p></td></tr>
    437  * <tr><td>setVideoScalingMode </p></td>
    438  *     <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td>
    439  *     <td>{Idle, Error}</p></td>
    440  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
    441  * <tr><td>setLooping </p></td>
    442  *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
    443  *         PlaybackCompleted}</p></td>
    444  *     <td>{Error}</p></td>
    445  *     <td>Successful invoke of this method in a valid state does not change
    446  *         the state. Calling this method in an
    447  *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
    448  * <tr><td>isLooping </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>setOnBufferingUpdateListener </p></td>
    454  *     <td>any </p></td>
    455  *     <td>{} </p></td>
    456  *     <td>This method can be called in any state and calling it does not change
    457  *         the object state. </p></td></tr>
    458  * <tr><td>setOnCompletionListener </p></td>
    459  *     <td>any </p></td>
    460  *     <td>{} </p></td>
    461  *     <td>This method can be called in any state and calling it does not change
    462  *         the object state. </p></td></tr>
    463  * <tr><td>setOnErrorListener </p></td>
    464  *     <td>any </p></td>
    465  *     <td>{} </p></td>
    466  *     <td>This method can be called in any state and calling it does not change
    467  *         the object state. </p></td></tr>
    468  * <tr><td>setOnPreparedListener </p></td>
    469  *     <td>any </p></td>
    470  *     <td>{} </p></td>
    471  *     <td>This method can be called in any state and calling it does not change
    472  *         the object state. </p></td></tr>
    473  * <tr><td>setOnSeekCompleteListener </p></td>
    474  *     <td>any </p></td>
    475  *     <td>{} </p></td>
    476  *     <td>This method can be called in any state and calling it does not change
    477  *         the object state. </p></td></tr>
    478  * <tr><td>setPlaybackParams</p></td>
    479  *     <td>{Initialized, Prepared, Started, Paused, PlaybackCompleted, Error}</p></td>
    480  *     <td>{Idle, Stopped} </p></td>
    481  *     <td>This method will change state in some cases, depending on when it's called.
    482  *         </p></td></tr>
    483  * <tr><td>setScreenOnWhilePlaying</></td>
    484  *     <td>any </p></td>
    485  *     <td>{} </p></td>
    486  *     <td>This method can be called in any state and calling it does not change
    487  *         the object state.  </p></td></tr>
    488  * <tr><td>setVolume </p></td>
    489  *     <td>{Idle, Initialized, Stopped, Prepared, Started, Paused,
    490  *          PlaybackCompleted}</p></td>
    491  *     <td>{Error}</p></td>
    492  *     <td>Successful invoke of this method does not change the state.
    493  * <tr><td>setWakeMode </p></td>
    494  *     <td>any </p></td>
    495  *     <td>{} </p></td>
    496  *     <td>This method can be called in any state and calling it does not change
    497  *         the object state.</p></td></tr>
    498  * <tr><td>start </p></td>
    499  *     <td>{Prepared, Started, Paused, PlaybackCompleted}</p></td>
    500  *     <td>{Idle, Initialized, Stopped, Error}</p></td>
    501  *     <td>Successful invoke of this method in a valid state transfers the
    502  *         object to the <em>Started</em> state. Calling this method in an
    503  *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
    504  * <tr><td>stop </p></td>
    505  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
    506  *     <td>{Idle, Initialized, Error}</p></td>
    507  *     <td>Successful invoke of this method in a valid state transfers the
    508  *         object to the <em>Stopped</em> state. Calling this method in an
    509  *         invalid state transfers the object to the <em>Error</em> state.</p></td></tr>
    510  * <tr><td>getTrackInfo </p></td>
    511  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
    512  *     <td>{Idle, Initialized, Error}</p></td>
    513  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
    514  * <tr><td>addTimedTextSource </p></td>
    515  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
    516  *     <td>{Idle, Initialized, Error}</p></td>
    517  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
    518  * <tr><td>selectTrack </p></td>
    519  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
    520  *     <td>{Idle, Initialized, Error}</p></td>
    521  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
    522  * <tr><td>deselectTrack </p></td>
    523  *     <td>{Prepared, Started, Stopped, Paused, PlaybackCompleted}</p></td>
    524  *     <td>{Idle, Initialized, Error}</p></td>
    525  *     <td>Successful invoke of this method does not change the state.</p></td></tr>
    526  *
    527  * </table>
    528  *
    529  * <a name="Permissions"></a>
    530  * <h3>Permissions</h3>
    531  * <p>One may need to declare a corresponding WAKE_LOCK permission {@link
    532  * android.R.styleable#AndroidManifestUsesPermission &lt;uses-permission&gt;}
    533  * element.
    534  *
    535  * <p>This class requires the {@link android.Manifest.permission#INTERNET} permission
    536  * when used with network-based content.
    537  *
    538  * <a name="Callbacks"></a>
    539  * <h3>Callbacks</h3>
    540  * <p>Applications may want to register for informational and error
    541  * events in order to be informed of some internal state update and
    542  * possible runtime errors during playback or streaming. Registration for
    543  * these events is done by properly setting the appropriate listeners (via calls
    544  * to
    545  * {@link #setOnPreparedListener(OnPreparedListener)}setOnPreparedListener,
    546  * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}setOnVideoSizeChangedListener,
    547  * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}setOnSeekCompleteListener,
    548  * {@link #setOnCompletionListener(OnCompletionListener)}setOnCompletionListener,
    549  * {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}setOnBufferingUpdateListener,
    550  * {@link #setOnInfoListener(OnInfoListener)}setOnInfoListener,
    551  * {@link #setOnErrorListener(OnErrorListener)}setOnErrorListener, etc).
    552  * In order to receive the respective callback
    553  * associated with these listeners, applications are required to create
    554  * MediaPlayer objects on a thread with its own Looper running (main UI
    555  * thread by default has a Looper running).
    556  *
    557  */
    558 public class MediaPlayer extends PlayerBase
    559                          implements SubtitleController.Listener
    560 {
    561     /**
    562        Constant to retrieve only the new metadata since the last
    563        call.
    564        // FIXME: unhide.
    565        // FIXME: add link to getMetadata(boolean, boolean)
    566        {@hide}
    567      */
    568     public static final boolean METADATA_UPDATE_ONLY = true;
    569 
    570     /**
    571        Constant to retrieve all the metadata.
    572        // FIXME: unhide.
    573        // FIXME: add link to getMetadata(boolean, boolean)
    574        {@hide}
    575      */
    576     public static final boolean METADATA_ALL = false;
    577 
    578     /**
    579        Constant to enable the metadata filter during retrieval.
    580        // FIXME: unhide.
    581        // FIXME: add link to getMetadata(boolean, boolean)
    582        {@hide}
    583      */
    584     public static final boolean APPLY_METADATA_FILTER = true;
    585 
    586     /**
    587        Constant to disable the metadata filter during retrieval.
    588        // FIXME: unhide.
    589        // FIXME: add link to getMetadata(boolean, boolean)
    590        {@hide}
    591      */
    592     public static final boolean BYPASS_METADATA_FILTER = false;
    593 
    594     static {
    595         System.loadLibrary("media_jni");
    596         native_init();
    597     }
    598 
    599     private final static String TAG = "MediaPlayer";
    600     // Name of the remote interface for the media player. Must be kept
    601     // in sync with the 2nd parameter of the IMPLEMENT_META_INTERFACE
    602     // macro invocation in IMediaPlayer.cpp
    603     private final static String IMEDIA_PLAYER = "android.media.IMediaPlayer";
    604 
    605     private long mNativeContext; // accessed by native methods
    606     private long mNativeSurfaceTexture;  // accessed by native methods
    607     private int mListenerContext; // accessed by native methods
    608     private SurfaceHolder mSurfaceHolder;
    609     private EventHandler mEventHandler;
    610     private PowerManager.WakeLock mWakeLock = null;
    611     private boolean mScreenOnWhilePlaying;
    612     private boolean mStayAwake;
    613     private int mStreamType = AudioManager.USE_DEFAULT_STREAM_TYPE;
    614     private int mUsage = -1;
    615     private boolean mBypassInterruptionPolicy;
    616 
    617     /**
    618      * Default constructor. Consider using one of the create() methods for
    619      * synchronously instantiating a MediaPlayer from a Uri or resource.
    620      * <p>When done with the MediaPlayer, you should call  {@link #release()},
    621      * to free the resources. If not released, too many MediaPlayer instances may
    622      * result in an exception.</p>
    623      */
    624     public MediaPlayer() {
    625         super(new AudioAttributes.Builder().build());
    626 
    627         Looper looper;
    628         if ((looper = Looper.myLooper()) != null) {
    629             mEventHandler = new EventHandler(this, looper);
    630         } else if ((looper = Looper.getMainLooper()) != null) {
    631             mEventHandler = new EventHandler(this, looper);
    632         } else {
    633             mEventHandler = null;
    634         }
    635 
    636         mTimeProvider = new TimeProvider(this);
    637         mOpenSubtitleSources = new Vector<InputStream>();
    638 
    639         /* Native setup requires a weak reference to our object.
    640          * It's easier to create it here than in C++.
    641          */
    642         native_setup(new WeakReference<MediaPlayer>(this));
    643     }
    644 
    645     /*
    646      * Update the MediaPlayer SurfaceTexture.
    647      * Call after setting a new display surface.
    648      */
    649     private native void _setVideoSurface(Surface surface);
    650 
    651     /* Do not change these values (starting with INVOKE_ID) without updating
    652      * their counterparts in include/media/mediaplayer.h!
    653      */
    654     private static final int INVOKE_ID_GET_TRACK_INFO = 1;
    655     private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE = 2;
    656     private static final int INVOKE_ID_ADD_EXTERNAL_SOURCE_FD = 3;
    657     private static final int INVOKE_ID_SELECT_TRACK = 4;
    658     private static final int INVOKE_ID_DESELECT_TRACK = 5;
    659     private static final int INVOKE_ID_SET_VIDEO_SCALE_MODE = 6;
    660     private static final int INVOKE_ID_GET_SELECTED_TRACK = 7;
    661 
    662     /**
    663      * Create a request parcel which can be routed to the native media
    664      * player using {@link #invoke(Parcel, Parcel)}. The Parcel
    665      * returned has the proper InterfaceToken set. The caller should
    666      * not overwrite that token, i.e it can only append data to the
    667      * Parcel.
    668      *
    669      * @return A parcel suitable to hold a request for the native
    670      * player.
    671      * {@hide}
    672      */
    673     public Parcel newRequest() {
    674         Parcel parcel = Parcel.obtain();
    675         parcel.writeInterfaceToken(IMEDIA_PLAYER);
    676         return parcel;
    677     }
    678 
    679     /**
    680      * Invoke a generic method on the native player using opaque
    681      * parcels for the request and reply. Both payloads' format is a
    682      * convention between the java caller and the native player.
    683      * Must be called after setDataSource to make sure a native player
    684      * exists. On failure, a RuntimeException is thrown.
    685      *
    686      * @param request Parcel with the data for the extension. The
    687      * caller must use {@link #newRequest()} to get one.
    688      *
    689      * @param reply Output parcel with the data returned by the
    690      * native player.
    691      * {@hide}
    692      */
    693     public void invoke(Parcel request, Parcel reply) {
    694         int retcode = native_invoke(request, reply);
    695         reply.setDataPosition(0);
    696         if (retcode != 0) {
    697             throw new RuntimeException("failure code: " + retcode);
    698         }
    699     }
    700 
    701     /**
    702      * Sets the {@link SurfaceHolder} to use for displaying the video
    703      * portion of the media.
    704      *
    705      * Either a surface holder or surface must be set if a display or video sink
    706      * is needed.  Not calling this method or {@link #setSurface(Surface)}
    707      * when playing back a video will result in only the audio track being played.
    708      * A null surface holder or surface will result in only the audio track being
    709      * played.
    710      *
    711      * @param sh the SurfaceHolder to use for video display
    712      * @throws IllegalStateException if the internal player engine has not been
    713      * initialized or has been released.
    714      */
    715     public void setDisplay(SurfaceHolder sh) {
    716         mSurfaceHolder = sh;
    717         Surface surface;
    718         if (sh != null) {
    719             surface = sh.getSurface();
    720         } else {
    721             surface = null;
    722         }
    723         _setVideoSurface(surface);
    724         updateSurfaceScreenOn();
    725     }
    726 
    727     /**
    728      * Sets the {@link Surface} to be used as the sink for the video portion of
    729      * the media. This is similar to {@link #setDisplay(SurfaceHolder)}, but
    730      * does not support {@link #setScreenOnWhilePlaying(boolean)}.  Setting a
    731      * Surface will un-set any Surface or SurfaceHolder that was previously set.
    732      * A null surface will result in only the audio track being played.
    733      *
    734      * If the Surface sends frames to a {@link SurfaceTexture}, the timestamps
    735      * returned from {@link SurfaceTexture#getTimestamp()} will have an
    736      * unspecified zero point.  These timestamps cannot be directly compared
    737      * between different media sources, different instances of the same media
    738      * source, or multiple runs of the same program.  The timestamp is normally
    739      * monotonically increasing and is unaffected by time-of-day adjustments,
    740      * but it is reset when the position is set.
    741      *
    742      * @param surface The {@link Surface} to be used for the video portion of
    743      * the media.
    744      * @throws IllegalStateException if the internal player engine has not been
    745      * initialized or has been released.
    746      */
    747     public void setSurface(Surface surface) {
    748         if (mScreenOnWhilePlaying && surface != null) {
    749             Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective for Surface");
    750         }
    751         mSurfaceHolder = null;
    752         _setVideoSurface(surface);
    753         updateSurfaceScreenOn();
    754     }
    755 
    756     /* Do not change these video scaling mode values below without updating
    757      * their counterparts in system/window.h! Please do not forget to update
    758      * {@link #isVideoScalingModeSupported} when new video scaling modes
    759      * are added.
    760      */
    761     /**
    762      * Specifies a video scaling mode. The content is stretched to the
    763      * surface rendering area. When the surface has the same aspect ratio
    764      * as the content, the aspect ratio of the content is maintained;
    765      * otherwise, the aspect ratio of the content is not maintained when video
    766      * is being rendered. Unlike {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING},
    767      * there is no content cropping with this video scaling mode.
    768      */
    769     public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT = 1;
    770 
    771     /**
    772      * Specifies a video scaling mode. The content is scaled, maintaining
    773      * its aspect ratio. The whole surface area is always used. When the
    774      * aspect ratio of the content is the same as the surface, no content
    775      * is cropped; otherwise, content is cropped to fit the surface.
    776      */
    777     public static final int VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING = 2;
    778     /**
    779      * Sets video scaling mode. To make the target video scaling mode
    780      * effective during playback, this method must be called after
    781      * data source is set. If not called, the default video
    782      * scaling mode is {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}.
    783      *
    784      * <p> The supported video scaling modes are:
    785      * <ul>
    786      * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT}
    787      * <li> {@link #VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING}
    788      * </ul>
    789      *
    790      * @param mode target video scaling mode. Must be one of the supported
    791      * video scaling modes; otherwise, IllegalArgumentException will be thrown.
    792      *
    793      * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT
    794      * @see MediaPlayer#VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING
    795      */
    796     public void setVideoScalingMode(int mode) {
    797         if (!isVideoScalingModeSupported(mode)) {
    798             final String msg = "Scaling mode " + mode + " is not supported";
    799             throw new IllegalArgumentException(msg);
    800         }
    801         Parcel request = Parcel.obtain();
    802         Parcel reply = Parcel.obtain();
    803         try {
    804             request.writeInterfaceToken(IMEDIA_PLAYER);
    805             request.writeInt(INVOKE_ID_SET_VIDEO_SCALE_MODE);
    806             request.writeInt(mode);
    807             invoke(request, reply);
    808         } finally {
    809             request.recycle();
    810             reply.recycle();
    811         }
    812     }
    813 
    814     /**
    815      * Convenience method to create a MediaPlayer for a given Uri.
    816      * On success, {@link #prepare()} will already have been called and must not be called again.
    817      * <p>When done with the MediaPlayer, you should call  {@link #release()},
    818      * to free the resources. If not released, too many MediaPlayer instances will
    819      * result in an exception.</p>
    820      * <p>Note that since {@link #prepare()} is called automatically in this method,
    821      * you cannot change the audio stream type (see {@link #setAudioStreamType(int)}), audio
    822      * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
    823      * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
    824      *
    825      * @param context the Context to use
    826      * @param uri the Uri from which to get the datasource
    827      * @return a MediaPlayer object, or null if creation failed
    828      */
    829     public static MediaPlayer create(Context context, Uri uri) {
    830         return create (context, uri, null);
    831     }
    832 
    833     /**
    834      * Convenience method to create a MediaPlayer for a given Uri.
    835      * On success, {@link #prepare()} will already have been called and must not be called again.
    836      * <p>When done with the MediaPlayer, you should call  {@link #release()},
    837      * to free the resources. If not released, too many MediaPlayer instances will
    838      * result in an exception.</p>
    839      * <p>Note that since {@link #prepare()} is called automatically in this method,
    840      * you cannot change the audio stream type (see {@link #setAudioStreamType(int)}), audio
    841      * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
    842      * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
    843      *
    844      * @param context the Context to use
    845      * @param uri the Uri from which to get the datasource
    846      * @param holder the SurfaceHolder to use for displaying the video
    847      * @return a MediaPlayer object, or null if creation failed
    848      */
    849     public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder) {
    850         int s = AudioSystem.newAudioSessionId();
    851         return create(context, uri, holder, null, s > 0 ? s : 0);
    852     }
    853 
    854     /**
    855      * Same factory method as {@link #create(Context, Uri, SurfaceHolder)} but that lets you specify
    856      * the audio attributes and session ID to be used by the new MediaPlayer instance.
    857      * @param context the Context to use
    858      * @param uri the Uri from which to get the datasource
    859      * @param holder the SurfaceHolder to use for displaying the video, may be null.
    860      * @param audioAttributes the {@link AudioAttributes} to be used by the media player.
    861      * @param audioSessionId the audio session ID to be used by the media player,
    862      *     see {@link AudioManager#generateAudioSessionId()} to obtain a new session.
    863      * @return a MediaPlayer object, or null if creation failed
    864      */
    865     public static MediaPlayer create(Context context, Uri uri, SurfaceHolder holder,
    866             AudioAttributes audioAttributes, int audioSessionId) {
    867 
    868         try {
    869             MediaPlayer mp = new MediaPlayer();
    870             final AudioAttributes aa = audioAttributes != null ? audioAttributes :
    871                 new AudioAttributes.Builder().build();
    872             mp.setAudioAttributes(aa);
    873             mp.setAudioSessionId(audioSessionId);
    874             mp.setDataSource(context, uri);
    875             if (holder != null) {
    876                 mp.setDisplay(holder);
    877             }
    878             mp.prepare();
    879             return mp;
    880         } catch (IOException ex) {
    881             Log.d(TAG, "create failed:", ex);
    882             // fall through
    883         } catch (IllegalArgumentException ex) {
    884             Log.d(TAG, "create failed:", ex);
    885             // fall through
    886         } catch (SecurityException ex) {
    887             Log.d(TAG, "create failed:", ex);
    888             // fall through
    889         }
    890 
    891         return null;
    892     }
    893 
    894     // Note no convenience method to create a MediaPlayer with SurfaceTexture sink.
    895 
    896     /**
    897      * Convenience method to create a MediaPlayer for a given resource id.
    898      * On success, {@link #prepare()} will already have been called and must not be called again.
    899      * <p>When done with the MediaPlayer, you should call  {@link #release()},
    900      * to free the resources. If not released, too many MediaPlayer instances will
    901      * result in an exception.</p>
    902      * <p>Note that since {@link #prepare()} is called automatically in this method,
    903      * you cannot change the audio stream type (see {@link #setAudioStreamType(int)}), audio
    904      * session ID (see {@link #setAudioSessionId(int)}) or audio attributes
    905      * (see {@link #setAudioAttributes(AudioAttributes)} of the new MediaPlayer.</p>
    906      *
    907      * @param context the Context to use
    908      * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
    909      *              the resource to use as the datasource
    910      * @return a MediaPlayer object, or null if creation failed
    911      */
    912     public static MediaPlayer create(Context context, int resid) {
    913         int s = AudioSystem.newAudioSessionId();
    914         return create(context, resid, null, s > 0 ? s : 0);
    915     }
    916 
    917     /**
    918      * Same factory method as {@link #create(Context, int)} but that lets you specify the audio
    919      * attributes and session ID to be used by the new MediaPlayer instance.
    920      * @param context the Context to use
    921      * @param resid the raw resource id (<var>R.raw.&lt;something></var>) for
    922      *              the resource to use as the datasource
    923      * @param audioAttributes the {@link AudioAttributes} to be used by the media player.
    924      * @param audioSessionId the audio session ID to be used by the media player,
    925      *     see {@link AudioManager#generateAudioSessionId()} to obtain a new session.
    926      * @return a MediaPlayer object, or null if creation failed
    927      */
    928     public static MediaPlayer create(Context context, int resid,
    929             AudioAttributes audioAttributes, int audioSessionId) {
    930         try {
    931             AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid);
    932             if (afd == null) return null;
    933 
    934             MediaPlayer mp = new MediaPlayer();
    935 
    936             final AudioAttributes aa = audioAttributes != null ? audioAttributes :
    937                 new AudioAttributes.Builder().build();
    938             mp.setAudioAttributes(aa);
    939             mp.setAudioSessionId(audioSessionId);
    940 
    941             mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
    942             afd.close();
    943             mp.prepare();
    944             return mp;
    945         } catch (IOException ex) {
    946             Log.d(TAG, "create failed:", ex);
    947             // fall through
    948         } catch (IllegalArgumentException ex) {
    949             Log.d(TAG, "create failed:", ex);
    950            // fall through
    951         } catch (SecurityException ex) {
    952             Log.d(TAG, "create failed:", ex);
    953             // fall through
    954         }
    955         return null;
    956     }
    957 
    958     /**
    959      * Sets the data source as a content Uri.
    960      *
    961      * @param context the Context to use when resolving the Uri
    962      * @param uri the Content URI of the data you want to play
    963      * @throws IllegalStateException if it is called in an invalid state
    964      */
    965     public void setDataSource(@NonNull Context context, @NonNull Uri uri)
    966             throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
    967         setDataSource(context, uri, null);
    968     }
    969 
    970     /**
    971      * Sets the data source as a content Uri.
    972      *
    973      * @param context the Context to use when resolving the Uri
    974      * @param uri the Content URI of the data you want to play
    975      * @param headers the headers to be sent together with the request for the data
    976      *                Note that the cross domain redirection is allowed by default, but that can be
    977      *                changed with key/value pairs through the headers parameter with
    978      *                "android-allow-cross-domain-redirect" as the key and "0" or "1" as the value
    979      *                to disallow or allow cross domain redirection.
    980      * @throws IllegalStateException if it is called in an invalid state
    981      */
    982     public void setDataSource(@NonNull Context context, @NonNull Uri uri,
    983             @Nullable Map<String, String> headers) throws IOException, IllegalArgumentException,
    984                     SecurityException, IllegalStateException {
    985         final ContentResolver resolver = context.getContentResolver();
    986         final String scheme = uri.getScheme();
    987         if (ContentResolver.SCHEME_FILE.equals(scheme)) {
    988             setDataSource(uri.getPath());
    989             return;
    990         } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)
    991                 && Settings.AUTHORITY.equals(uri.getAuthority())) {
    992             // Try cached ringtone first since the actual provider may not be
    993             // encryption aware, or it may be stored on CE media storage
    994             final int type = RingtoneManager.getDefaultType(uri);
    995             final Uri cacheUri = RingtoneManager.getCacheForType(type);
    996             final Uri actualUri = RingtoneManager.getActualDefaultRingtoneUri(context, type);
    997             if (attemptDataSource(resolver, cacheUri)) {
    998                 return;
    999             } else if (attemptDataSource(resolver, actualUri)) {
   1000                 return;
   1001             } else {
   1002                 setDataSource(uri.toString(), headers);
   1003             }
   1004         } else {
   1005             // Try requested Uri locally first, or fallback to media server
   1006             if (attemptDataSource(resolver, uri)) {
   1007                 return;
   1008             } else {
   1009                 setDataSource(uri.toString(), headers);
   1010             }
   1011         }
   1012     }
   1013 
   1014     private boolean attemptDataSource(ContentResolver resolver, Uri uri) {
   1015         try (AssetFileDescriptor afd = resolver.openAssetFileDescriptor(uri, "r")) {
   1016             setDataSource(afd);
   1017             return true;
   1018         } catch (NullPointerException | SecurityException | IOException ex) {
   1019             Log.w(TAG, "Couldn't open " + uri + ": " + ex);
   1020             return false;
   1021         }
   1022     }
   1023 
   1024     /**
   1025      * Sets the data source (file-path or http/rtsp URL) to use.
   1026      *
   1027      * @param path the path of the file, or the http/rtsp URL of the stream you want to play
   1028      * @throws IllegalStateException if it is called in an invalid state
   1029      *
   1030      * <p>When <code>path</code> refers to a local file, the file may actually be opened by a
   1031      * process other than the calling application.  This implies that the pathname
   1032      * should be an absolute path (as any other process runs with unspecified current working
   1033      * directory), and that the pathname should reference a world-readable file.
   1034      * As an alternative, the application could first open the file for reading,
   1035      * and then use the file descriptor form {@link #setDataSource(FileDescriptor)}.
   1036      */
   1037     public void setDataSource(String path)
   1038             throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
   1039         setDataSource(path, null, null);
   1040     }
   1041 
   1042     /**
   1043      * Sets the data source (file-path or http/rtsp URL) to use.
   1044      *
   1045      * @param path the path of the file, or the http/rtsp URL of the stream you want to play
   1046      * @param headers the headers associated with the http request for the stream you want to play
   1047      * @throws IllegalStateException if it is called in an invalid state
   1048      * @hide pending API council
   1049      */
   1050     public void setDataSource(String path, Map<String, String> headers)
   1051             throws IOException, IllegalArgumentException, SecurityException, IllegalStateException
   1052     {
   1053         String[] keys = null;
   1054         String[] values = null;
   1055 
   1056         if (headers != null) {
   1057             keys = new String[headers.size()];
   1058             values = new String[headers.size()];
   1059 
   1060             int i = 0;
   1061             for (Map.Entry<String, String> entry: headers.entrySet()) {
   1062                 keys[i] = entry.getKey();
   1063                 values[i] = entry.getValue();
   1064                 ++i;
   1065             }
   1066         }
   1067         setDataSource(path, keys, values);
   1068     }
   1069 
   1070     private void setDataSource(String path, String[] keys, String[] values)
   1071             throws IOException, IllegalArgumentException, SecurityException, IllegalStateException {
   1072         final Uri uri = Uri.parse(path);
   1073         final String scheme = uri.getScheme();
   1074         if ("file".equals(scheme)) {
   1075             path = uri.getPath();
   1076         } else if (scheme != null) {
   1077             // handle non-file sources
   1078             nativeSetDataSource(
   1079                 MediaHTTPService.createHttpServiceBinderIfNecessary(path),
   1080                 path,
   1081                 keys,
   1082                 values);
   1083             return;
   1084         }
   1085 
   1086         final File file = new File(path);
   1087         if (file.exists()) {
   1088             FileInputStream is = new FileInputStream(file);
   1089             FileDescriptor fd = is.getFD();
   1090             setDataSource(fd);
   1091             is.close();
   1092         } else {
   1093             throw new IOException("setDataSource failed.");
   1094         }
   1095     }
   1096 
   1097     private native void nativeSetDataSource(
   1098         IBinder httpServiceBinder, String path, String[] keys, String[] values)
   1099         throws IOException, IllegalArgumentException, SecurityException, IllegalStateException;
   1100 
   1101     /**
   1102      * Sets the data source (AssetFileDescriptor) to use. It is the caller's
   1103      * responsibility to close the file descriptor. It is safe to do so as soon
   1104      * as this call returns.
   1105      *
   1106      * @param afd the AssetFileDescriptor for the file you want to play
   1107      * @throws IllegalStateException if it is called in an invalid state
   1108      * @throws IllegalArgumentException if afd is not a valid AssetFileDescriptor
   1109      * @throws IOException if afd can not be read
   1110      */
   1111     public void setDataSource(@NonNull AssetFileDescriptor afd)
   1112             throws IOException, IllegalArgumentException, IllegalStateException {
   1113         Preconditions.checkNotNull(afd);
   1114         // Note: using getDeclaredLength so that our behavior is the same
   1115         // as previous versions when the content provider is returning
   1116         // a full file.
   1117         if (afd.getDeclaredLength() < 0) {
   1118             setDataSource(afd.getFileDescriptor());
   1119         } else {
   1120             setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getDeclaredLength());
   1121         }
   1122     }
   1123 
   1124     /**
   1125      * Sets the data source (FileDescriptor) to use. It is the caller's responsibility
   1126      * to close the file descriptor. It is safe to do so as soon as this call returns.
   1127      *
   1128      * @param fd the FileDescriptor for the file you want to play
   1129      * @throws IllegalStateException if it is called in an invalid state
   1130      * @throws IllegalArgumentException if fd is not a valid FileDescriptor
   1131      * @throws IOException if fd can not be read
   1132      */
   1133     public void setDataSource(FileDescriptor fd)
   1134             throws IOException, IllegalArgumentException, IllegalStateException {
   1135         // intentionally less than LONG_MAX
   1136         setDataSource(fd, 0, 0x7ffffffffffffffL);
   1137     }
   1138 
   1139     /**
   1140      * Sets the data source (FileDescriptor) to use.  The FileDescriptor must be
   1141      * seekable (N.B. a LocalSocket is not seekable). It is the caller's responsibility
   1142      * to close the file descriptor. It is safe to do so as soon as this call returns.
   1143      *
   1144      * @param fd the FileDescriptor for the file you want to play
   1145      * @param offset the offset into the file where the data to be played starts, in bytes
   1146      * @param length the length in bytes of the data to be played
   1147      * @throws IllegalStateException if it is called in an invalid state
   1148      * @throws IllegalArgumentException if fd is not a valid FileDescriptor
   1149      * @throws IOException if fd can not be read
   1150      */
   1151     public void setDataSource(FileDescriptor fd, long offset, long length)
   1152             throws IOException, IllegalArgumentException, IllegalStateException {
   1153         _setDataSource(fd, offset, length);
   1154     }
   1155 
   1156     private native void _setDataSource(FileDescriptor fd, long offset, long length)
   1157             throws IOException, IllegalArgumentException, IllegalStateException;
   1158 
   1159     /**
   1160      * Sets the data source (MediaDataSource) to use.
   1161      *
   1162      * @param dataSource the MediaDataSource for the media you want to play
   1163      * @throws IllegalStateException if it is called in an invalid state
   1164      * @throws IllegalArgumentException if dataSource is not a valid MediaDataSource
   1165      */
   1166     public void setDataSource(MediaDataSource dataSource)
   1167             throws IllegalArgumentException, IllegalStateException {
   1168         _setDataSource(dataSource);
   1169     }
   1170 
   1171     private native void _setDataSource(MediaDataSource dataSource)
   1172           throws IllegalArgumentException, IllegalStateException;
   1173 
   1174     /**
   1175      * Prepares the player for playback, synchronously.
   1176      *
   1177      * After setting the datasource and the display surface, you need to either
   1178      * call prepare() or prepareAsync(). For files, it is OK to call prepare(),
   1179      * which blocks until MediaPlayer is ready for playback.
   1180      *
   1181      * @throws IllegalStateException if it is called in an invalid state
   1182      */
   1183     public void prepare() throws IOException, IllegalStateException {
   1184         _prepare();
   1185         scanInternalSubtitleTracks();
   1186     }
   1187 
   1188     private native void _prepare() throws IOException, IllegalStateException;
   1189 
   1190     /**
   1191      * Prepares the player for playback, asynchronously.
   1192      *
   1193      * After setting the datasource and the display surface, you need to either
   1194      * call prepare() or prepareAsync(). For streams, you should call prepareAsync(),
   1195      * which returns immediately, rather than blocking until enough data has been
   1196      * buffered.
   1197      *
   1198      * @throws IllegalStateException if it is called in an invalid state
   1199      */
   1200     public native void prepareAsync() throws IllegalStateException;
   1201 
   1202     /**
   1203      * Starts or resumes playback. If playback had previously been paused,
   1204      * playback will continue from where it was paused. If playback had
   1205      * been stopped, or never started before, playback will start at the
   1206      * beginning.
   1207      *
   1208      * @throws IllegalStateException if it is called in an invalid state
   1209      */
   1210     public void start() throws IllegalStateException {
   1211         baseStart();
   1212         stayAwake(true);
   1213         _start();
   1214     }
   1215 
   1216     private native void _start() throws IllegalStateException;
   1217 
   1218 
   1219     private int getAudioStreamType() {
   1220         if (mStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) {
   1221             mStreamType = _getAudioStreamType();
   1222         }
   1223         return mStreamType;
   1224     }
   1225 
   1226     private native int _getAudioStreamType() throws IllegalStateException;
   1227 
   1228     /**
   1229      * Stops playback after playback has been stopped or paused.
   1230      *
   1231      * @throws IllegalStateException if the internal player engine has not been
   1232      * initialized.
   1233      */
   1234     public void stop() throws IllegalStateException {
   1235         stayAwake(false);
   1236         _stop();
   1237     }
   1238 
   1239     private native void _stop() throws IllegalStateException;
   1240 
   1241     /**
   1242      * Pauses playback. Call start() to resume.
   1243      *
   1244      * @throws IllegalStateException if the internal player engine has not been
   1245      * initialized.
   1246      */
   1247     public void pause() throws IllegalStateException {
   1248         stayAwake(false);
   1249         _pause();
   1250     }
   1251 
   1252     private native void _pause() throws IllegalStateException;
   1253 
   1254     /**
   1255      * Set the low-level power management behavior for this MediaPlayer.  This
   1256      * can be used when the MediaPlayer is not playing through a SurfaceHolder
   1257      * set with {@link #setDisplay(SurfaceHolder)} and thus can use the
   1258      * high-level {@link #setScreenOnWhilePlaying(boolean)} feature.
   1259      *
   1260      * <p>This function has the MediaPlayer access the low-level power manager
   1261      * service to control the device's power usage while playing is occurring.
   1262      * The parameter is a combination of {@link android.os.PowerManager} wake flags.
   1263      * Use of this method requires {@link android.Manifest.permission#WAKE_LOCK}
   1264      * permission.
   1265      * By default, no attempt is made to keep the device awake during playback.
   1266      *
   1267      * @param context the Context to use
   1268      * @param mode    the power/wake mode to set
   1269      * @see android.os.PowerManager
   1270      */
   1271     public void setWakeMode(Context context, int mode) {
   1272         boolean washeld = false;
   1273 
   1274         /* Disable persistant wakelocks in media player based on property */
   1275         if (SystemProperties.getBoolean("audio.offload.ignore_setawake", false) == true) {
   1276             Log.w(TAG, "IGNORING setWakeMode " + mode);
   1277             return;
   1278         }
   1279 
   1280         if (mWakeLock != null) {
   1281             if (mWakeLock.isHeld()) {
   1282                 washeld = true;
   1283                 mWakeLock.release();
   1284             }
   1285             mWakeLock = null;
   1286         }
   1287 
   1288         PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
   1289         mWakeLock = pm.newWakeLock(mode|PowerManager.ON_AFTER_RELEASE, MediaPlayer.class.getName());
   1290         mWakeLock.setReferenceCounted(false);
   1291         if (washeld) {
   1292             mWakeLock.acquire();
   1293         }
   1294     }
   1295 
   1296     /**
   1297      * Control whether we should use the attached SurfaceHolder to keep the
   1298      * screen on while video playback is occurring.  This is the preferred
   1299      * method over {@link #setWakeMode} where possible, since it doesn't
   1300      * require that the application have permission for low-level wake lock
   1301      * access.
   1302      *
   1303      * @param screenOn Supply true to keep the screen on, false to allow it
   1304      * to turn off.
   1305      */
   1306     public void setScreenOnWhilePlaying(boolean screenOn) {
   1307         if (mScreenOnWhilePlaying != screenOn) {
   1308             if (screenOn && mSurfaceHolder == null) {
   1309                 Log.w(TAG, "setScreenOnWhilePlaying(true) is ineffective without a SurfaceHolder");
   1310             }
   1311             mScreenOnWhilePlaying = screenOn;
   1312             updateSurfaceScreenOn();
   1313         }
   1314     }
   1315 
   1316     private void stayAwake(boolean awake) {
   1317         if (mWakeLock != null) {
   1318             if (awake && !mWakeLock.isHeld()) {
   1319                 mWakeLock.acquire();
   1320             } else if (!awake && mWakeLock.isHeld()) {
   1321                 mWakeLock.release();
   1322             }
   1323         }
   1324         mStayAwake = awake;
   1325         updateSurfaceScreenOn();
   1326     }
   1327 
   1328     private void updateSurfaceScreenOn() {
   1329         if (mSurfaceHolder != null) {
   1330             mSurfaceHolder.setKeepScreenOn(mScreenOnWhilePlaying && mStayAwake);
   1331         }
   1332     }
   1333 
   1334     /**
   1335      * Returns the width of the video.
   1336      *
   1337      * @return the width of the video, or 0 if there is no video,
   1338      * no display surface was set, or the width has not been determined
   1339      * yet. The OnVideoSizeChangedListener can be registered via
   1340      * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
   1341      * to provide a notification when the width is available.
   1342      */
   1343     public native int getVideoWidth();
   1344 
   1345     /**
   1346      * Returns the height of the video.
   1347      *
   1348      * @return the height of the video, or 0 if there is no video,
   1349      * no display surface was set, or the height has not been determined
   1350      * yet. The OnVideoSizeChangedListener can be registered via
   1351      * {@link #setOnVideoSizeChangedListener(OnVideoSizeChangedListener)}
   1352      * to provide a notification when the height is available.
   1353      */
   1354     public native int getVideoHeight();
   1355 
   1356     /**
   1357      * Checks whether the MediaPlayer is playing.
   1358      *
   1359      * @return true if currently playing, false otherwise
   1360      * @throws IllegalStateException if the internal player engine has not been
   1361      * initialized or has been released.
   1362      */
   1363     public native boolean isPlaying();
   1364 
   1365     /**
   1366      * Change playback speed of audio by resampling the audio.
   1367      * <p>
   1368      * Specifies resampling as audio mode for variable rate playback, i.e.,
   1369      * resample the waveform based on the requested playback rate to get
   1370      * a new waveform, and play back the new waveform at the original sampling
   1371      * frequency.
   1372      * When rate is larger than 1.0, pitch becomes higher.
   1373      * When rate is smaller than 1.0, pitch becomes lower.
   1374      *
   1375      * @hide
   1376      */
   1377     public static final int PLAYBACK_RATE_AUDIO_MODE_RESAMPLE = 2;
   1378 
   1379     /**
   1380      * Change playback speed of audio without changing its pitch.
   1381      * <p>
   1382      * Specifies time stretching as audio mode for variable rate playback.
   1383      * Time stretching changes the duration of the audio samples without
   1384      * affecting its pitch.
   1385      * <p>
   1386      * This mode is only supported for a limited range of playback speed factors,
   1387      * e.g. between 1/2x and 2x.
   1388      *
   1389      * @hide
   1390      */
   1391     public static final int PLAYBACK_RATE_AUDIO_MODE_STRETCH = 1;
   1392 
   1393     /**
   1394      * Change playback speed of audio without changing its pitch, and
   1395      * possibly mute audio if time stretching is not supported for the playback
   1396      * speed.
   1397      * <p>
   1398      * Try to keep audio pitch when changing the playback rate, but allow the
   1399      * system to determine how to change audio playback if the rate is out
   1400      * of range.
   1401      *
   1402      * @hide
   1403      */
   1404     public static final int PLAYBACK_RATE_AUDIO_MODE_DEFAULT = 0;
   1405 
   1406     /** @hide */
   1407     @IntDef(
   1408         value = {
   1409             PLAYBACK_RATE_AUDIO_MODE_DEFAULT,
   1410             PLAYBACK_RATE_AUDIO_MODE_STRETCH,
   1411             PLAYBACK_RATE_AUDIO_MODE_RESAMPLE,
   1412     })
   1413     @Retention(RetentionPolicy.SOURCE)
   1414     public @interface PlaybackRateAudioMode {}
   1415 
   1416     /**
   1417      * Sets playback rate and audio mode.
   1418      *
   1419      * @param rate the ratio between desired playback rate and normal one.
   1420      * @param audioMode audio playback mode. Must be one of the supported
   1421      * audio modes.
   1422      *
   1423      * @throws IllegalStateException if the internal player engine has not been
   1424      * initialized.
   1425      * @throws IllegalArgumentException if audioMode is not supported.
   1426      *
   1427      * @hide
   1428      */
   1429     @NonNull
   1430     public PlaybackParams easyPlaybackParams(float rate, @PlaybackRateAudioMode int audioMode) {
   1431         PlaybackParams params = new PlaybackParams();
   1432         params.allowDefaults();
   1433         switch (audioMode) {
   1434         case PLAYBACK_RATE_AUDIO_MODE_DEFAULT:
   1435             params.setSpeed(rate).setPitch(1.0f);
   1436             break;
   1437         case PLAYBACK_RATE_AUDIO_MODE_STRETCH:
   1438             params.setSpeed(rate).setPitch(1.0f)
   1439                     .setAudioFallbackMode(params.AUDIO_FALLBACK_MODE_FAIL);
   1440             break;
   1441         case PLAYBACK_RATE_AUDIO_MODE_RESAMPLE:
   1442             params.setSpeed(rate).setPitch(rate);
   1443             break;
   1444         default:
   1445             final String msg = "Audio playback mode " + audioMode + " is not supported";
   1446             throw new IllegalArgumentException(msg);
   1447         }
   1448         return params;
   1449     }
   1450 
   1451     /**
   1452      * Sets playback rate using {@link PlaybackParams}. The object sets its internal
   1453      * PlaybackParams to the input, except that the object remembers previous speed
   1454      * when input speed is zero. This allows the object to resume at previous speed
   1455      * when start() is called. Calling it before the object is prepared does not change
   1456      * the object state. After the object is prepared, calling it with zero speed is
   1457      * equivalent to calling pause(). After the object is prepared, calling it with
   1458      * non-zero speed is equivalent to calling start().
   1459      *
   1460      * @param params the playback params.
   1461      *
   1462      * @throws IllegalStateException if the internal player engine has not been
   1463      * initialized or has been released.
   1464      * @throws IllegalArgumentException if params is not supported.
   1465      */
   1466     public native void setPlaybackParams(@NonNull PlaybackParams params);
   1467 
   1468     /**
   1469      * Gets the playback params, containing the current playback rate.
   1470      *
   1471      * @return the playback params.
   1472      * @throws IllegalStateException if the internal player engine has not been
   1473      * initialized.
   1474      */
   1475     @NonNull
   1476     public native PlaybackParams getPlaybackParams();
   1477 
   1478     /**
   1479      * Sets A/V sync mode.
   1480      *
   1481      * @param params the A/V sync params to apply
   1482      *
   1483      * @throws IllegalStateException if the internal player engine has not been
   1484      * initialized.
   1485      * @throws IllegalArgumentException if params are not supported.
   1486      */
   1487     public native void setSyncParams(@NonNull SyncParams params);
   1488 
   1489     /**
   1490      * Gets the A/V sync mode.
   1491      *
   1492      * @return the A/V sync params
   1493      *
   1494      * @throws IllegalStateException if the internal player engine has not been
   1495      * initialized.
   1496      */
   1497     @NonNull
   1498     public native SyncParams getSyncParams();
   1499 
   1500     /**
   1501      * Seeks to specified time position.
   1502      *
   1503      * @param msec the offset in milliseconds from the start to seek to
   1504      * @throws IllegalStateException if the internal player engine has not been
   1505      * initialized
   1506      */
   1507     public native void seekTo(int msec) throws IllegalStateException;
   1508 
   1509     /**
   1510      * Get current playback position as a {@link MediaTimestamp}.
   1511      * <p>
   1512      * The MediaTimestamp represents how the media time correlates to the system time in
   1513      * a linear fashion using an anchor and a clock rate. During regular playback, the media
   1514      * time moves fairly constantly (though the anchor frame may be rebased to a current
   1515      * system time, the linear correlation stays steady). Therefore, this method does not
   1516      * need to be called often.
   1517      * <p>
   1518      * To help users get current playback position, this method always anchors the timestamp
   1519      * to the current {@link System#nanoTime system time}, so
   1520      * {@link MediaTimestamp#getAnchorMediaTimeUs} can be used as current playback position.
   1521      *
   1522      * @return a MediaTimestamp object if a timestamp is available, or {@code null} if no timestamp
   1523      *         is available, e.g. because the media player has not been initialized.
   1524      *
   1525      * @see MediaTimestamp
   1526      */
   1527     @Nullable
   1528     public MediaTimestamp getTimestamp()
   1529     {
   1530         try {
   1531             // TODO: get the timestamp from native side
   1532             return new MediaTimestamp(
   1533                     getCurrentPosition() * 1000L,
   1534                     System.nanoTime(),
   1535                     isPlaying() ? getPlaybackParams().getSpeed() : 0.f);
   1536         } catch (IllegalStateException e) {
   1537             return null;
   1538         }
   1539     }
   1540 
   1541     /**
   1542      * Gets the current playback position.
   1543      *
   1544      * @return the current position in milliseconds
   1545      */
   1546     public native int getCurrentPosition();
   1547 
   1548     /**
   1549      * Gets the duration of the file.
   1550      *
   1551      * @return the duration in milliseconds, if no duration is available
   1552      *         (for example, if streaming live content), -1 is returned.
   1553      */
   1554     public native int getDuration();
   1555 
   1556     /**
   1557      * Gets the media metadata.
   1558      *
   1559      * @param update_only controls whether the full set of available
   1560      * metadata is returned or just the set that changed since the
   1561      * last call. See {@see #METADATA_UPDATE_ONLY} and {@see
   1562      * #METADATA_ALL}.
   1563      *
   1564      * @param apply_filter if true only metadata that matches the
   1565      * filter is returned. See {@see #APPLY_METADATA_FILTER} and {@see
   1566      * #BYPASS_METADATA_FILTER}.
   1567      *
   1568      * @return The metadata, possibly empty. null if an error occured.
   1569      // FIXME: unhide.
   1570      * {@hide}
   1571      */
   1572     public Metadata getMetadata(final boolean update_only,
   1573                                 final boolean apply_filter) {
   1574         Parcel reply = Parcel.obtain();
   1575         Metadata data = new Metadata();
   1576 
   1577         if (!native_getMetadata(update_only, apply_filter, reply)) {
   1578             reply.recycle();
   1579             return null;
   1580         }
   1581 
   1582         // Metadata takes over the parcel, don't recycle it unless
   1583         // there is an error.
   1584         if (!data.parse(reply)) {
   1585             reply.recycle();
   1586             return null;
   1587         }
   1588         return data;
   1589     }
   1590 
   1591     /**
   1592      * Set a filter for the metadata update notification and update
   1593      * retrieval. The caller provides 2 set of metadata keys, allowed
   1594      * and blocked. The blocked set always takes precedence over the
   1595      * allowed one.
   1596      * Metadata.MATCH_ALL and Metadata.MATCH_NONE are 2 sets available as
   1597      * shorthands to allow/block all or no metadata.
   1598      *
   1599      * By default, there is no filter set.
   1600      *
   1601      * @param allow Is the set of metadata the client is interested
   1602      *              in receiving new notifications for.
   1603      * @param block Is the set of metadata the client is not interested
   1604      *              in receiving new notifications for.
   1605      * @return The call status code.
   1606      *
   1607      // FIXME: unhide.
   1608      * {@hide}
   1609      */
   1610     public int setMetadataFilter(Set<Integer> allow, Set<Integer> block) {
   1611         // Do our serialization manually instead of calling
   1612         // Parcel.writeArray since the sets are made of the same type
   1613         // we avoid paying the price of calling writeValue (used by
   1614         // writeArray) which burns an extra int per element to encode
   1615         // the type.
   1616         Parcel request =  newRequest();
   1617 
   1618         // The parcel starts already with an interface token. There
   1619         // are 2 filters. Each one starts with a 4bytes number to
   1620         // store the len followed by a number of int (4 bytes as well)
   1621         // representing the metadata type.
   1622         int capacity = request.dataSize() + 4 * (1 + allow.size() + 1 + block.size());
   1623 
   1624         if (request.dataCapacity() < capacity) {
   1625             request.setDataCapacity(capacity);
   1626         }
   1627 
   1628         request.writeInt(allow.size());
   1629         for(Integer t: allow) {
   1630             request.writeInt(t);
   1631         }
   1632         request.writeInt(block.size());
   1633         for(Integer t: block) {
   1634             request.writeInt(t);
   1635         }
   1636         return native_setMetadataFilter(request);
   1637     }
   1638 
   1639     /**
   1640      * Set the MediaPlayer to start when this MediaPlayer finishes playback
   1641      * (i.e. reaches the end of the stream).
   1642      * The media framework will attempt to transition from this player to
   1643      * the next as seamlessly as possible. The next player can be set at
   1644      * any time before completion, but shall be after setDataSource has been
   1645      * called successfully. The next player must be prepared by the
   1646      * app, and the application should not call start() on it.
   1647      * The next MediaPlayer must be different from 'this'. An exception
   1648      * will be thrown if next == this.
   1649      * The application may call setNextMediaPlayer(null) to indicate no
   1650      * next player should be started at the end of playback.
   1651      * If the current player is looping, it will keep looping and the next
   1652      * player will not be started.
   1653      *
   1654      * @param next the player to start after this one completes playback.
   1655      *
   1656      */
   1657     public native void setNextMediaPlayer(MediaPlayer next);
   1658 
   1659     /**
   1660      * Releases resources associated with this MediaPlayer object.
   1661      * It is considered good practice to call this method when you're
   1662      * done using the MediaPlayer. In particular, whenever an Activity
   1663      * of an application is paused (its onPause() method is called),
   1664      * or stopped (its onStop() method is called), this method should be
   1665      * invoked to release the MediaPlayer object, unless the application
   1666      * has a special need to keep the object around. In addition to
   1667      * unnecessary resources (such as memory and instances of codecs)
   1668      * being held, failure to call this method immediately if a
   1669      * MediaPlayer object is no longer needed may also lead to
   1670      * continuous battery consumption for mobile devices, and playback
   1671      * failure for other applications if no multiple instances of the
   1672      * same codec are supported on a device. Even if multiple instances
   1673      * of the same codec are supported, some performance degradation
   1674      * may be expected when unnecessary multiple instances are used
   1675      * at the same time.
   1676      */
   1677     public void release() {
   1678         baseRelease();
   1679         stayAwake(false);
   1680         updateSurfaceScreenOn();
   1681         mOnPreparedListener = null;
   1682         mOnBufferingUpdateListener = null;
   1683         mOnCompletionListener = null;
   1684         mOnSeekCompleteListener = null;
   1685         mOnErrorListener = null;
   1686         mOnInfoListener = null;
   1687         mOnVideoSizeChangedListener = null;
   1688         mOnTimedTextListener = null;
   1689         if (mTimeProvider != null) {
   1690             mTimeProvider.close();
   1691             mTimeProvider = null;
   1692         }
   1693         mOnSubtitleDataListener = null;
   1694         _release();
   1695     }
   1696 
   1697     private native void _release();
   1698 
   1699     /**
   1700      * Resets the MediaPlayer to its uninitialized state. After calling
   1701      * this method, you will have to initialize it again by setting the
   1702      * data source and calling prepare().
   1703      */
   1704     public void reset() {
   1705         mSelectedSubtitleTrackIndex = -1;
   1706         synchronized(mOpenSubtitleSources) {
   1707             for (final InputStream is: mOpenSubtitleSources) {
   1708                 try {
   1709                     is.close();
   1710                 } catch (IOException e) {
   1711                 }
   1712             }
   1713             mOpenSubtitleSources.clear();
   1714         }
   1715         if (mSubtitleController != null) {
   1716             mSubtitleController.reset();
   1717         }
   1718         if (mTimeProvider != null) {
   1719             mTimeProvider.close();
   1720             mTimeProvider = null;
   1721         }
   1722 
   1723         stayAwake(false);
   1724         _reset();
   1725         // make sure none of the listeners get called anymore
   1726         if (mEventHandler != null) {
   1727             mEventHandler.removeCallbacksAndMessages(null);
   1728         }
   1729 
   1730         synchronized (mIndexTrackPairs) {
   1731             mIndexTrackPairs.clear();
   1732             mInbandTrackIndices.clear();
   1733         };
   1734     }
   1735 
   1736     private native void _reset();
   1737 
   1738     /**
   1739      * Sets the audio stream type for this MediaPlayer. See {@link AudioManager}
   1740      * for a list of stream types. Must call this method before prepare() or
   1741      * prepareAsync() in order for the target stream type to become effective
   1742      * thereafter.
   1743      *
   1744      * @param streamtype the audio stream type
   1745      * @see android.media.AudioManager
   1746      */
   1747     public void setAudioStreamType(int streamtype) {
   1748         baseUpdateAudioAttributes(
   1749                 new AudioAttributes.Builder().setInternalLegacyStreamType(streamtype).build());
   1750         _setAudioStreamType(streamtype);
   1751         mStreamType = streamtype;
   1752     }
   1753 
   1754     private native void _setAudioStreamType(int streamtype);
   1755 
   1756     // Keep KEY_PARAMETER_* in sync with include/media/mediaplayer.h
   1757     private final static int KEY_PARAMETER_AUDIO_ATTRIBUTES = 1400;
   1758     /**
   1759      * Sets the parameter indicated by key.
   1760      * @param key key indicates the parameter to be set.
   1761      * @param value value of the parameter to be set.
   1762      * @return true if the parameter is set successfully, false otherwise
   1763      * {@hide}
   1764      */
   1765     private native boolean setParameter(int key, Parcel value);
   1766 
   1767     /**
   1768      * Sets the audio attributes for this MediaPlayer.
   1769      * See {@link AudioAttributes} for how to build and configure an instance of this class.
   1770      * You must call this method before {@link #prepare()} or {@link #prepareAsync()} in order
   1771      * for the audio attributes to become effective thereafter.
   1772      * @param attributes a non-null set of audio attributes
   1773      */
   1774     public void setAudioAttributes(AudioAttributes attributes) throws IllegalArgumentException {
   1775         if (attributes == null) {
   1776             final String msg = "Cannot set AudioAttributes to null";
   1777             throw new IllegalArgumentException(msg);
   1778         }
   1779         baseUpdateAudioAttributes(attributes);
   1780         mUsage = attributes.getUsage();
   1781         mBypassInterruptionPolicy = (attributes.getAllFlags()
   1782                 & AudioAttributes.FLAG_BYPASS_INTERRUPTION_POLICY) != 0;
   1783         Parcel pattributes = Parcel.obtain();
   1784         attributes.writeToParcel(pattributes, AudioAttributes.FLATTEN_TAGS);
   1785         setParameter(KEY_PARAMETER_AUDIO_ATTRIBUTES, pattributes);
   1786         pattributes.recycle();
   1787     }
   1788 
   1789     /**
   1790      * Sets the player to be looping or non-looping.
   1791      *
   1792      * @param looping whether to loop or not
   1793      */
   1794     public native void setLooping(boolean looping);
   1795 
   1796     /**
   1797      * Checks whether the MediaPlayer is looping or non-looping.
   1798      *
   1799      * @return true if the MediaPlayer is currently looping, false otherwise
   1800      */
   1801     public native boolean isLooping();
   1802 
   1803     /**
   1804      * Sets the volume on this player.
   1805      * This API is recommended for balancing the output of audio streams
   1806      * within an application. Unless you are writing an application to
   1807      * control user settings, this API should be used in preference to
   1808      * {@link AudioManager#setStreamVolume(int, int, int)} which sets the volume of ALL streams of
   1809      * a particular type. Note that the passed volume values are raw scalars in range 0.0 to 1.0.
   1810      * UI controls should be scaled logarithmically.
   1811      *
   1812      * @param leftVolume left volume scalar
   1813      * @param rightVolume right volume scalar
   1814      */
   1815     /*
   1816      * FIXME: Merge this into javadoc comment above when setVolume(float) is not @hide.
   1817      * The single parameter form below is preferred if the channel volumes don't need
   1818      * to be set independently.
   1819      */
   1820     public void setVolume(float leftVolume, float rightVolume) {
   1821         baseSetVolume(leftVolume, rightVolume);
   1822     }
   1823 
   1824     @Override
   1825     void playerSetVolume(float leftVolume, float rightVolume) {
   1826         _setVolume(leftVolume, rightVolume);
   1827     }
   1828 
   1829     private native void _setVolume(float leftVolume, float rightVolume);
   1830 
   1831     /**
   1832      * Similar, excepts sets volume of all channels to same value.
   1833      * @hide
   1834      */
   1835     public void setVolume(float volume) {
   1836         setVolume(volume, volume);
   1837     }
   1838 
   1839     /**
   1840      * Sets the audio session ID.
   1841      *
   1842      * @param sessionId the audio session ID.
   1843      * The audio session ID is a system wide unique identifier for the audio stream played by
   1844      * this MediaPlayer instance.
   1845      * The primary use of the audio session ID  is to associate audio effects to a particular
   1846      * instance of MediaPlayer: if an audio session ID is provided when creating an audio effect,
   1847      * this effect will be applied only to the audio content of media players within the same
   1848      * audio session and not to the output mix.
   1849      * When created, a MediaPlayer instance automatically generates its own audio session ID.
   1850      * However, it is possible to force this player to be part of an already existing audio session
   1851      * by calling this method.
   1852      * This method must be called before one of the overloaded <code> setDataSource </code> methods.
   1853      * @throws IllegalStateException if it is called in an invalid state
   1854      */
   1855     public native void setAudioSessionId(int sessionId)  throws IllegalArgumentException, IllegalStateException;
   1856 
   1857     /**
   1858      * Returns the audio session ID.
   1859      *
   1860      * @return the audio session ID. {@see #setAudioSessionId(int)}
   1861      * Note that the audio session ID is 0 only if a problem occured when the MediaPlayer was contructed.
   1862      */
   1863     public native int getAudioSessionId();
   1864 
   1865     /**
   1866      * Attaches an auxiliary effect to the player. A typical auxiliary effect is a reverberation
   1867      * effect which can be applied on any sound source that directs a certain amount of its
   1868      * energy to this effect. This amount is defined by setAuxEffectSendLevel().
   1869      * See {@link #setAuxEffectSendLevel(float)}.
   1870      * <p>After creating an auxiliary effect (e.g.
   1871      * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with
   1872      * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling this method
   1873      * to attach the player to the effect.
   1874      * <p>To detach the effect from the player, call this method with a null effect id.
   1875      * <p>This method must be called after one of the overloaded <code> setDataSource </code>
   1876      * methods.
   1877      * @param effectId system wide unique id of the effect to attach
   1878      */
   1879     public native void attachAuxEffect(int effectId);
   1880 
   1881 
   1882     /**
   1883      * Sets the send level of the player to the attached auxiliary effect.
   1884      * See {@link #attachAuxEffect(int)}. The level value range is 0 to 1.0.
   1885      * <p>By default the send level is 0, so even if an effect is attached to the player
   1886      * this method must be called for the effect to be applied.
   1887      * <p>Note that the passed level value is a raw scalar. UI controls should be scaled
   1888      * logarithmically: the gain applied by audio framework ranges from -72dB to 0dB,
   1889      * so an appropriate conversion from linear UI input x to level is:
   1890      * x == 0 -> level = 0
   1891      * 0 < x <= R -> level = 10^(72*(x-R)/20/R)
   1892      * @param level send level scalar
   1893      */
   1894     public void setAuxEffectSendLevel(float level) {
   1895         baseSetAuxEffectSendLevel(level);
   1896     }
   1897 
   1898     @Override
   1899     int playerSetAuxEffectSendLevel(float level) {
   1900         _setAuxEffectSendLevel(level);
   1901         return AudioSystem.SUCCESS;
   1902     }
   1903 
   1904     private native void _setAuxEffectSendLevel(float level);
   1905 
   1906     /*
   1907      * @param request Parcel destinated to the media player. The
   1908      *                Interface token must be set to the IMediaPlayer
   1909      *                one to be routed correctly through the system.
   1910      * @param reply[out] Parcel that will contain the reply.
   1911      * @return The status code.
   1912      */
   1913     private native final int native_invoke(Parcel request, Parcel reply);
   1914 
   1915 
   1916     /*
   1917      * @param update_only If true fetch only the set of metadata that have
   1918      *                    changed since the last invocation of getMetadata.
   1919      *                    The set is built using the unfiltered
   1920      *                    notifications the native player sent to the
   1921      *                    MediaPlayerService during that period of
   1922      *                    time. If false, all the metadatas are considered.
   1923      * @param apply_filter  If true, once the metadata set has been built based on
   1924      *                     the value update_only, the current filter is applied.
   1925      * @param reply[out] On return contains the serialized
   1926      *                   metadata. Valid only if the call was successful.
   1927      * @return The status code.
   1928      */
   1929     private native final boolean native_getMetadata(boolean update_only,
   1930                                                     boolean apply_filter,
   1931                                                     Parcel reply);
   1932 
   1933     /*
   1934      * @param request Parcel with the 2 serialized lists of allowed
   1935      *                metadata types followed by the one to be
   1936      *                dropped. Each list starts with an integer
   1937      *                indicating the number of metadata type elements.
   1938      * @return The status code.
   1939      */
   1940     private native final int native_setMetadataFilter(Parcel request);
   1941 
   1942     private static native final void native_init();
   1943     private native final void native_setup(Object mediaplayer_this);
   1944     private native final void native_finalize();
   1945 
   1946     /**
   1947      * Class for MediaPlayer to return each audio/video/subtitle track's metadata.
   1948      *
   1949      * @see android.media.MediaPlayer#getTrackInfo
   1950      */
   1951     static public class TrackInfo implements Parcelable {
   1952         /**
   1953          * Gets the track type.
   1954          * @return TrackType which indicates if the track is video, audio, timed text.
   1955          */
   1956         public int getTrackType() {
   1957             return mTrackType;
   1958         }
   1959 
   1960         /**
   1961          * Gets the language code of the track.
   1962          * @return a language code in either way of ISO-639-1 or ISO-639-2.
   1963          * When the language is unknown or could not be determined,
   1964          * ISO-639-2 language code, "und", is returned.
   1965          */
   1966         public String getLanguage() {
   1967             String language = mFormat.getString(MediaFormat.KEY_LANGUAGE);
   1968             return language == null ? "und" : language;
   1969         }
   1970 
   1971         /**
   1972          * Gets the {@link MediaFormat} of the track.  If the format is
   1973          * unknown or could not be determined, null is returned.
   1974          */
   1975         public MediaFormat getFormat() {
   1976             if (mTrackType == MEDIA_TRACK_TYPE_TIMEDTEXT
   1977                     || mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
   1978                 return mFormat;
   1979             }
   1980             return null;
   1981         }
   1982 
   1983         public static final int MEDIA_TRACK_TYPE_UNKNOWN = 0;
   1984         public static final int MEDIA_TRACK_TYPE_VIDEO = 1;
   1985         public static final int MEDIA_TRACK_TYPE_AUDIO = 2;
   1986         public static final int MEDIA_TRACK_TYPE_TIMEDTEXT = 3;
   1987         public static final int MEDIA_TRACK_TYPE_SUBTITLE = 4;
   1988         public static final int MEDIA_TRACK_TYPE_METADATA = 5;
   1989 
   1990         final int mTrackType;
   1991         final MediaFormat mFormat;
   1992 
   1993         TrackInfo(Parcel in) {
   1994             mTrackType = in.readInt();
   1995             // TODO: parcel in the full MediaFormat; currently we are using createSubtitleFormat
   1996             // even for audio/video tracks, meaning we only set the mime and language.
   1997             String mime = in.readString();
   1998             String language = in.readString();
   1999             mFormat = MediaFormat.createSubtitleFormat(mime, language);
   2000 
   2001             if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
   2002                 mFormat.setInteger(MediaFormat.KEY_IS_AUTOSELECT, in.readInt());
   2003                 mFormat.setInteger(MediaFormat.KEY_IS_DEFAULT, in.readInt());
   2004                 mFormat.setInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE, in.readInt());
   2005             }
   2006         }
   2007 
   2008         /** @hide */
   2009         TrackInfo(int type, MediaFormat format) {
   2010             mTrackType = type;
   2011             mFormat = format;
   2012         }
   2013 
   2014         /**
   2015          * {@inheritDoc}
   2016          */
   2017         @Override
   2018         public int describeContents() {
   2019             return 0;
   2020         }
   2021 
   2022         /**
   2023          * {@inheritDoc}
   2024          */
   2025         @Override
   2026         public void writeToParcel(Parcel dest, int flags) {
   2027             dest.writeInt(mTrackType);
   2028             dest.writeString(getLanguage());
   2029 
   2030             if (mTrackType == MEDIA_TRACK_TYPE_SUBTITLE) {
   2031                 dest.writeString(mFormat.getString(MediaFormat.KEY_MIME));
   2032                 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_AUTOSELECT));
   2033                 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_DEFAULT));
   2034                 dest.writeInt(mFormat.getInteger(MediaFormat.KEY_IS_FORCED_SUBTITLE));
   2035             }
   2036         }
   2037 
   2038         @Override
   2039         public String toString() {
   2040             StringBuilder out = new StringBuilder(128);
   2041             out.append(getClass().getName());
   2042             out.append('{');
   2043             switch (mTrackType) {
   2044             case MEDIA_TRACK_TYPE_VIDEO:
   2045                 out.append("VIDEO");
   2046                 break;
   2047             case MEDIA_TRACK_TYPE_AUDIO:
   2048                 out.append("AUDIO");
   2049                 break;
   2050             case MEDIA_TRACK_TYPE_TIMEDTEXT:
   2051                 out.append("TIMEDTEXT");
   2052                 break;
   2053             case MEDIA_TRACK_TYPE_SUBTITLE:
   2054                 out.append("SUBTITLE");
   2055                 break;
   2056             default:
   2057                 out.append("UNKNOWN");
   2058                 break;
   2059             }
   2060             out.append(", " + mFormat.toString());
   2061             out.append("}");
   2062             return out.toString();
   2063         }
   2064 
   2065         /**
   2066          * Used to read a TrackInfo from a Parcel.
   2067          */
   2068         static final Parcelable.Creator<TrackInfo> CREATOR
   2069                 = new Parcelable.Creator<TrackInfo>() {
   2070                     @Override
   2071                     public TrackInfo createFromParcel(Parcel in) {
   2072                         return new TrackInfo(in);
   2073                     }
   2074 
   2075                     @Override
   2076                     public TrackInfo[] newArray(int size) {
   2077                         return new TrackInfo[size];
   2078                     }
   2079                 };
   2080 
   2081     };
   2082 
   2083     // We would like domain specific classes with more informative names than the `first` and `second`
   2084     // in generic Pair, but we would also like to avoid creating new/trivial classes. As a compromise
   2085     // we document the meanings of `first` and `second` here:
   2086     //
   2087     // Pair.first - inband track index; non-null iff representing an inband track.
   2088     // Pair.second - a SubtitleTrack registered with mSubtitleController; non-null iff representing
   2089     //               an inband subtitle track or any out-of-band track (subtitle or timedtext).
   2090     private Vector<Pair<Integer, SubtitleTrack>> mIndexTrackPairs = new Vector<>();
   2091     private BitSet mInbandTrackIndices = new BitSet();
   2092 
   2093     /**
   2094      * Returns an array of track information.
   2095      *
   2096      * @return Array of track info. The total number of tracks is the array length.
   2097      * Must be called again if an external timed text source has been added after any of the
   2098      * addTimedTextSource methods are called.
   2099      * @throws IllegalStateException if it is called in an invalid state.
   2100      */
   2101     public TrackInfo[] getTrackInfo() throws IllegalStateException {
   2102         TrackInfo trackInfo[] = getInbandTrackInfo();
   2103         // add out-of-band tracks
   2104         synchronized (mIndexTrackPairs) {
   2105             TrackInfo allTrackInfo[] = new TrackInfo[mIndexTrackPairs.size()];
   2106             for (int i = 0; i < allTrackInfo.length; i++) {
   2107                 Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
   2108                 if (p.first != null) {
   2109                     // inband track
   2110                     allTrackInfo[i] = trackInfo[p.first];
   2111                 } else {
   2112                     SubtitleTrack track = p.second;
   2113                     allTrackInfo[i] = new TrackInfo(track.getTrackType(), track.getFormat());
   2114                 }
   2115             }
   2116             return allTrackInfo;
   2117         }
   2118     }
   2119 
   2120     private TrackInfo[] getInbandTrackInfo() throws IllegalStateException {
   2121         Parcel request = Parcel.obtain();
   2122         Parcel reply = Parcel.obtain();
   2123         try {
   2124             request.writeInterfaceToken(IMEDIA_PLAYER);
   2125             request.writeInt(INVOKE_ID_GET_TRACK_INFO);
   2126             invoke(request, reply);
   2127             TrackInfo trackInfo[] = reply.createTypedArray(TrackInfo.CREATOR);
   2128             return trackInfo;
   2129         } finally {
   2130             request.recycle();
   2131             reply.recycle();
   2132         }
   2133     }
   2134 
   2135     /* Do not change these values without updating their counterparts
   2136      * in include/media/stagefright/MediaDefs.h and media/libstagefright/MediaDefs.cpp!
   2137      */
   2138     /**
   2139      * MIME type for SubRip (SRT) container. Used in addTimedTextSource APIs.
   2140      */
   2141     public static final String MEDIA_MIMETYPE_TEXT_SUBRIP = "application/x-subrip";
   2142 
   2143     /**
   2144      * MIME type for WebVTT subtitle data.
   2145      * @hide
   2146      */
   2147     public static final String MEDIA_MIMETYPE_TEXT_VTT = "text/vtt";
   2148 
   2149     /**
   2150      * MIME type for CEA-608 closed caption data.
   2151      * @hide
   2152      */
   2153     public static final String MEDIA_MIMETYPE_TEXT_CEA_608 = "text/cea-608";
   2154 
   2155     /**
   2156      * MIME type for CEA-708 closed caption data.
   2157      * @hide
   2158      */
   2159     public static final String MEDIA_MIMETYPE_TEXT_CEA_708 = "text/cea-708";
   2160 
   2161     /*
   2162      * A helper function to check if the mime type is supported by media framework.
   2163      */
   2164     private static boolean availableMimeTypeForExternalSource(String mimeType) {
   2165         if (MEDIA_MIMETYPE_TEXT_SUBRIP.equals(mimeType)) {
   2166             return true;
   2167         }
   2168         return false;
   2169     }
   2170 
   2171     private SubtitleController mSubtitleController;
   2172 
   2173     /** @hide */
   2174     public void setSubtitleAnchor(
   2175             SubtitleController controller,
   2176             SubtitleController.Anchor anchor) {
   2177         // TODO: create SubtitleController in MediaPlayer
   2178         mSubtitleController = controller;
   2179         mSubtitleController.setAnchor(anchor);
   2180     }
   2181 
   2182     /**
   2183      * The private version of setSubtitleAnchor is used internally to set mSubtitleController if
   2184      * necessary when clients don't provide their own SubtitleControllers using the public version
   2185      * {@link #setSubtitleAnchor(SubtitleController, Anchor)} (e.g. {@link VideoView} provides one).
   2186      */
   2187     private synchronized void setSubtitleAnchor() {
   2188         if (mSubtitleController == null) {
   2189             final HandlerThread thread = new HandlerThread("SetSubtitleAnchorThread");
   2190             thread.start();
   2191             Handler handler = new Handler(thread.getLooper());
   2192             handler.post(new Runnable() {
   2193                 @Override
   2194                 public void run() {
   2195                     Context context = ActivityThread.currentApplication();
   2196                     mSubtitleController = new SubtitleController(context, mTimeProvider, MediaPlayer.this);
   2197                     mSubtitleController.setAnchor(new Anchor() {
   2198                         @Override
   2199                         public void setSubtitleWidget(RenderingWidget subtitleWidget) {
   2200                         }
   2201 
   2202                         @Override
   2203                         public Looper getSubtitleLooper() {
   2204                             return Looper.getMainLooper();
   2205                         }
   2206                     });
   2207                     thread.getLooper().quitSafely();
   2208                 }
   2209             });
   2210             try {
   2211                 thread.join();
   2212             } catch (InterruptedException e) {
   2213                 Thread.currentThread().interrupt();
   2214                 Log.w(TAG, "failed to join SetSubtitleAnchorThread");
   2215             }
   2216         }
   2217     }
   2218 
   2219     private int mSelectedSubtitleTrackIndex = -1;
   2220     private Vector<InputStream> mOpenSubtitleSources;
   2221 
   2222     private OnSubtitleDataListener mSubtitleDataListener = new OnSubtitleDataListener() {
   2223         @Override
   2224         public void onSubtitleData(MediaPlayer mp, SubtitleData data) {
   2225             int index = data.getTrackIndex();
   2226             synchronized (mIndexTrackPairs) {
   2227                 for (Pair<Integer, SubtitleTrack> p : mIndexTrackPairs) {
   2228                     if (p.first != null && p.first == index && p.second != null) {
   2229                         // inband subtitle track that owns data
   2230                         SubtitleTrack track = p.second;
   2231                         track.onData(data);
   2232                     }
   2233                 }
   2234             }
   2235         }
   2236     };
   2237 
   2238     /** @hide */
   2239     @Override
   2240     public void onSubtitleTrackSelected(SubtitleTrack track) {
   2241         if (mSelectedSubtitleTrackIndex >= 0) {
   2242             try {
   2243                 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, false);
   2244             } catch (IllegalStateException e) {
   2245             }
   2246             mSelectedSubtitleTrackIndex = -1;
   2247         }
   2248         setOnSubtitleDataListener(null);
   2249         if (track == null) {
   2250             return;
   2251         }
   2252 
   2253         synchronized (mIndexTrackPairs) {
   2254             for (Pair<Integer, SubtitleTrack> p : mIndexTrackPairs) {
   2255                 if (p.first != null && p.second == track) {
   2256                     // inband subtitle track that is selected
   2257                     mSelectedSubtitleTrackIndex = p.first;
   2258                     break;
   2259                 }
   2260             }
   2261         }
   2262 
   2263         if (mSelectedSubtitleTrackIndex >= 0) {
   2264             try {
   2265                 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, true);
   2266             } catch (IllegalStateException e) {
   2267             }
   2268             setOnSubtitleDataListener(mSubtitleDataListener);
   2269         }
   2270         // no need to select out-of-band tracks
   2271     }
   2272 
   2273     /** @hide */
   2274     public void addSubtitleSource(InputStream is, MediaFormat format)
   2275             throws IllegalStateException
   2276     {
   2277         final InputStream fIs = is;
   2278         final MediaFormat fFormat = format;
   2279 
   2280         if (is != null) {
   2281             // Ensure all input streams are closed.  It is also a handy
   2282             // way to implement timeouts in the future.
   2283             synchronized(mOpenSubtitleSources) {
   2284                 mOpenSubtitleSources.add(is);
   2285             }
   2286         } else {
   2287             Log.w(TAG, "addSubtitleSource called with null InputStream");
   2288         }
   2289 
   2290         getMediaTimeProvider();
   2291 
   2292         // process each subtitle in its own thread
   2293         final HandlerThread thread = new HandlerThread("SubtitleReadThread",
   2294               Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
   2295         thread.start();
   2296         Handler handler = new Handler(thread.getLooper());
   2297         handler.post(new Runnable() {
   2298             private int addTrack() {
   2299                 if (fIs == null || mSubtitleController == null) {
   2300                     return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
   2301                 }
   2302 
   2303                 SubtitleTrack track = mSubtitleController.addTrack(fFormat);
   2304                 if (track == null) {
   2305                     return MEDIA_INFO_UNSUPPORTED_SUBTITLE;
   2306                 }
   2307 
   2308                 // TODO: do the conversion in the subtitle track
   2309                 Scanner scanner = new Scanner(fIs, "UTF-8");
   2310                 String contents = scanner.useDelimiter("\\A").next();
   2311                 synchronized(mOpenSubtitleSources) {
   2312                     mOpenSubtitleSources.remove(fIs);
   2313                 }
   2314                 scanner.close();
   2315                 synchronized (mIndexTrackPairs) {
   2316                     mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(null, track));
   2317                 }
   2318                 Handler h = mTimeProvider.mEventHandler;
   2319                 int what = TimeProvider.NOTIFY;
   2320                 int arg1 = TimeProvider.NOTIFY_TRACK_DATA;
   2321                 Pair<SubtitleTrack, byte[]> trackData = Pair.create(track, contents.getBytes());
   2322                 Message m = h.obtainMessage(what, arg1, 0, trackData);
   2323                 h.sendMessage(m);
   2324                 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
   2325             }
   2326 
   2327             public void run() {
   2328                 int res = addTrack();
   2329                 if (mEventHandler != null) {
   2330                     Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
   2331                     mEventHandler.sendMessage(m);
   2332                 }
   2333                 thread.getLooper().quitSafely();
   2334             }
   2335         });
   2336     }
   2337 
   2338     private void scanInternalSubtitleTracks() {
   2339         if (mSubtitleController == null) {
   2340             Log.d(TAG, "setSubtitleAnchor in MediaPlayer");
   2341             setSubtitleAnchor();
   2342         }
   2343 
   2344         populateInbandTracks();
   2345 
   2346         if (mSubtitleController != null) {
   2347             mSubtitleController.selectDefaultTrack();
   2348         }
   2349     }
   2350 
   2351     private void populateInbandTracks() {
   2352         TrackInfo[] tracks = getInbandTrackInfo();
   2353         synchronized (mIndexTrackPairs) {
   2354             for (int i = 0; i < tracks.length; i++) {
   2355                 if (mInbandTrackIndices.get(i)) {
   2356                     continue;
   2357                 } else {
   2358                     mInbandTrackIndices.set(i);
   2359                 }
   2360 
   2361                 // newly appeared inband track
   2362                 if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) {
   2363                     SubtitleTrack track = mSubtitleController.addTrack(
   2364                             tracks[i].getFormat());
   2365                     mIndexTrackPairs.add(Pair.create(i, track));
   2366                 } else {
   2367                     mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(i, null));
   2368                 }
   2369             }
   2370         }
   2371     }
   2372 
   2373     /* TODO: Limit the total number of external timed text source to a reasonable number.
   2374      */
   2375     /**
   2376      * Adds an external timed text source file.
   2377      *
   2378      * Currently supported format is SubRip with the file extension .srt, case insensitive.
   2379      * Note that a single external timed text source may contain multiple tracks in it.
   2380      * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
   2381      * additional tracks become available after this method call.
   2382      *
   2383      * @param path The file path of external timed text source file.
   2384      * @param mimeType The mime type of the file. Must be one of the mime types listed above.
   2385      * @throws IOException if the file cannot be accessed or is corrupted.
   2386      * @throws IllegalArgumentException if the mimeType is not supported.
   2387      * @throws IllegalStateException if called in an invalid state.
   2388      */
   2389     public void addTimedTextSource(String path, String mimeType)
   2390             throws IOException, IllegalArgumentException, IllegalStateException {
   2391         if (!availableMimeTypeForExternalSource(mimeType)) {
   2392             final String msg = "Illegal mimeType for timed text source: " + mimeType;
   2393             throw new IllegalArgumentException(msg);
   2394         }
   2395 
   2396         File file = new File(path);
   2397         if (file.exists()) {
   2398             FileInputStream is = new FileInputStream(file);
   2399             FileDescriptor fd = is.getFD();
   2400             addTimedTextSource(fd, mimeType);
   2401             is.close();
   2402         } else {
   2403             // We do not support the case where the path is not a file.
   2404             throw new IOException(path);
   2405         }
   2406     }
   2407 
   2408     /**
   2409      * Adds an external timed text source file (Uri).
   2410      *
   2411      * Currently supported format is SubRip with the file extension .srt, case insensitive.
   2412      * Note that a single external timed text source may contain multiple tracks in it.
   2413      * One can find the total number of available tracks using {@link #getTrackInfo()} to see what
   2414      * additional tracks become available after this method call.
   2415      *
   2416      * @param context the Context to use when resolving the Uri
   2417      * @param uri the Content URI of the data you want to play
   2418      * @param mimeType The mime type of the file. Must be one of the mime types listed above.
   2419      * @throws IOException if the file cannot be accessed or is corrupted.
   2420      * @throws IllegalArgumentException if the mimeType is not supported.
   2421      * @throws IllegalStateException if called in an invalid state.
   2422      */
   2423     public void addTimedTextSource(Context context, Uri uri, String mimeType)
   2424             throws IOException, IllegalArgumentException, IllegalStateException {
   2425         String scheme = uri.getScheme();
   2426         if(scheme == null || scheme.equals("file")) {
   2427             addTimedTextSource(uri.getPath(), mimeType);
   2428             return;
   2429         }
   2430 
   2431         AssetFileDescriptor fd = null;
   2432         try {
   2433             ContentResolver resolver = context.getContentResolver();
   2434             fd = resolver.openAssetFileDescriptor(uri, "r");
   2435             if (fd == null) {
   2436                 return;
   2437             }
   2438             addTimedTextSource(fd.getFileDescriptor(), mimeType);
   2439             return;
   2440         } catch (SecurityException ex) {
   2441         } catch (IOException ex) {
   2442         } finally {
   2443             if (fd != null) {
   2444                 fd.close();
   2445             }
   2446         }
   2447     }
   2448 
   2449     /**
   2450      * Adds an external timed text source file (FileDescriptor).
   2451      *
   2452      * It is the caller's responsibility to close the file descriptor.
   2453      * It is safe to do so as soon as this call returns.
   2454      *
   2455      * Currently supported format is SubRip. Note that a single external timed text source may
   2456      * contain multiple tracks in it. One can find the total number of available tracks
   2457      * using {@link #getTrackInfo()} to see what additional tracks become available
   2458      * after this method call.
   2459      *
   2460      * @param fd the FileDescriptor for the file you want to play
   2461      * @param mimeType The mime type of the file. Must be one of the mime types listed above.
   2462      * @throws IllegalArgumentException if the mimeType is not supported.
   2463      * @throws IllegalStateException if called in an invalid state.
   2464      */
   2465     public void addTimedTextSource(FileDescriptor fd, String mimeType)
   2466             throws IllegalArgumentException, IllegalStateException {
   2467         // intentionally less than LONG_MAX
   2468         addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType);
   2469     }
   2470 
   2471     /**
   2472      * Adds an external timed text file (FileDescriptor).
   2473      *
   2474      * It is the caller's responsibility to close the file descriptor.
   2475      * It is safe to do so as soon as this call returns.
   2476      *
   2477      * Currently supported format is SubRip. Note that a single external timed text source may
   2478      * contain multiple tracks in it. One can find the total number of available tracks
   2479      * using {@link #getTrackInfo()} to see what additional tracks become available
   2480      * after this method call.
   2481      *
   2482      * @param fd the FileDescriptor for the file you want to play
   2483      * @param offset the offset into the file where the data to be played starts, in bytes
   2484      * @param length the length in bytes of the data to be played
   2485      * @param mime The mime type of the file. Must be one of the mime types listed above.
   2486      * @throws IllegalArgumentException if the mimeType is not supported.
   2487      * @throws IllegalStateException if called in an invalid state.
   2488      */
   2489     public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mime)
   2490             throws IllegalArgumentException, IllegalStateException {
   2491         if (!availableMimeTypeForExternalSource(mime)) {
   2492             throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mime);
   2493         }
   2494 
   2495         FileDescriptor fd2;
   2496         try {
   2497             fd2 = Libcore.os.dup(fd);
   2498         } catch (ErrnoException ex) {
   2499             Log.e(TAG, ex.getMessage(), ex);
   2500             throw new RuntimeException(ex);
   2501         }
   2502 
   2503         final MediaFormat fFormat = new MediaFormat();
   2504         fFormat.setString(MediaFormat.KEY_MIME, mime);
   2505         fFormat.setInteger(MediaFormat.KEY_IS_TIMED_TEXT, 1);
   2506 
   2507         // A MediaPlayer created by a VideoView should already have its mSubtitleController set.
   2508         if (mSubtitleController == null) {
   2509             setSubtitleAnchor();
   2510         }
   2511 
   2512         if (!mSubtitleController.hasRendererFor(fFormat)) {
   2513             // test and add not atomic
   2514             Context context = ActivityThread.currentApplication();
   2515             mSubtitleController.registerRenderer(new SRTRenderer(context, mEventHandler));
   2516         }
   2517         final SubtitleTrack track = mSubtitleController.addTrack(fFormat);
   2518         synchronized (mIndexTrackPairs) {
   2519             mIndexTrackPairs.add(Pair.<Integer, SubtitleTrack>create(null, track));
   2520         }
   2521 
   2522         getMediaTimeProvider();
   2523 
   2524         final FileDescriptor fd3 = fd2;
   2525         final long offset2 = offset;
   2526         final long length2 = length;
   2527         final HandlerThread thread = new HandlerThread(
   2528                 "TimedTextReadThread",
   2529                 Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE);
   2530         thread.start();
   2531         Handler handler = new Handler(thread.getLooper());
   2532         handler.post(new Runnable() {
   2533             private int addTrack() {
   2534                 InputStream is = null;
   2535                 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
   2536                 try {
   2537                     Libcore.os.lseek(fd3, offset2, OsConstants.SEEK_SET);
   2538                     byte[] buffer = new byte[4096];
   2539                     for (long total = 0; total < length2;) {
   2540                         int bytesToRead = (int) Math.min(buffer.length, length2 - total);
   2541                         int bytes = IoBridge.read(fd3, buffer, 0, bytesToRead);
   2542                         if (bytes < 0) {
   2543                             break;
   2544                         } else {
   2545                             bos.write(buffer, 0, bytes);
   2546                             total += bytes;
   2547                         }
   2548                     }
   2549                     Handler h = mTimeProvider.mEventHandler;
   2550                     int what = TimeProvider.NOTIFY;
   2551                     int arg1 = TimeProvider.NOTIFY_TRACK_DATA;
   2552                     Pair<SubtitleTrack, byte[]> trackData = Pair.create(track, bos.toByteArray());
   2553                     Message m = h.obtainMessage(what, arg1, 0, trackData);
   2554                     h.sendMessage(m);
   2555                     return MEDIA_INFO_EXTERNAL_METADATA_UPDATE;
   2556                 } catch (Exception e) {
   2557                     Log.e(TAG, e.getMessage(), e);
   2558                     return MEDIA_INFO_TIMED_TEXT_ERROR;
   2559                 } finally {
   2560                     if (is != null) {
   2561                         try {
   2562                             is.close();
   2563                         } catch (IOException e) {
   2564                             Log.e(TAG, e.getMessage(), e);
   2565                         }
   2566                     }
   2567                 }
   2568             }
   2569 
   2570             public void run() {
   2571                 int res = addTrack();
   2572                 if (mEventHandler != null) {
   2573                     Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null);
   2574                     mEventHandler.sendMessage(m);
   2575                 }
   2576                 thread.getLooper().quitSafely();
   2577             }
   2578         });
   2579     }
   2580 
   2581     /**
   2582      * Returns the index of the audio, video, or subtitle track currently selected for playback,
   2583      * The return value is an index into the array returned by {@link #getTrackInfo()}, and can
   2584      * be used in calls to {@link #selectTrack(int)} or {@link #deselectTrack(int)}.
   2585      *
   2586      * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO},
   2587      * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or
   2588      * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE}
   2589      * @return index of the audio, video, or subtitle track currently selected for playback;
   2590      * a negative integer is returned when there is no selected track for {@code trackType} or
   2591      * when {@code trackType} is not one of audio, video, or subtitle.
   2592      * @throws IllegalStateException if called after {@link #release()}
   2593      *
   2594      * @see #getTrackInfo()
   2595      * @see #selectTrack(int)
   2596      * @see #deselectTrack(int)
   2597      */
   2598     public int getSelectedTrack(int trackType) throws IllegalStateException {
   2599         if (mSubtitleController != null
   2600                 && (trackType == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE
   2601                 || trackType == TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT)) {
   2602             SubtitleTrack subtitleTrack = mSubtitleController.getSelectedTrack();
   2603             if (subtitleTrack != null) {
   2604                 synchronized (mIndexTrackPairs) {
   2605                     for (int i = 0; i < mIndexTrackPairs.size(); i++) {
   2606                         Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
   2607                         if (p.second == subtitleTrack && subtitleTrack.getTrackType() == trackType) {
   2608                             return i;
   2609                         }
   2610                     }
   2611                 }
   2612             }
   2613         }
   2614 
   2615         Parcel request = Parcel.obtain();
   2616         Parcel reply = Parcel.obtain();
   2617         try {
   2618             request.writeInterfaceToken(IMEDIA_PLAYER);
   2619             request.writeInt(INVOKE_ID_GET_SELECTED_TRACK);
   2620             request.writeInt(trackType);
   2621             invoke(request, reply);
   2622             int inbandTrackIndex = reply.readInt();
   2623             synchronized (mIndexTrackPairs) {
   2624                 for (int i = 0; i < mIndexTrackPairs.size(); i++) {
   2625                     Pair<Integer, SubtitleTrack> p = mIndexTrackPairs.get(i);
   2626                     if (p.first != null && p.first == inbandTrackIndex) {
   2627                         return i;
   2628                     }
   2629                 }
   2630             }
   2631             return -1;
   2632         } finally {
   2633             request.recycle();
   2634             reply.recycle();
   2635         }
   2636     }
   2637 
   2638     /**
   2639      * Selects a track.
   2640      * <p>
   2641      * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception.
   2642      * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately.
   2643      * If a MediaPlayer is not in Started state, it just marks the track to be played.
   2644      * </p>
   2645      * <p>
   2646      * In any valid state, if it is called multiple times on the same type of track (ie. Video,
   2647      * Audio, Timed Text), the most recent one will be chosen.
   2648      * </p>
   2649      * <p>
   2650      * The first audio and video tracks are selected by default if available, even though
   2651      * this method is not called. However, no timed text track will be selected until
   2652      * this function is called.
   2653      * </p>
   2654      * <p>
   2655      * Currently, only timed text tracks or audio tracks can be selected via this method.
   2656      * In addition, the support for selecting an audio track at runtime is pretty limited
   2657      * in that an audio track can only be selected in the <em>Prepared</em> state.
   2658      * </p>
   2659      * @param index the index of the track to be selected. The valid range of the index
   2660      * is 0..total number of track - 1. The total number of tracks as well as the type of
   2661      * each individual track can be found by calling {@link #getTrackInfo()} method.
   2662      * @throws IllegalStateException if called in an invalid state.
   2663      *
   2664      * @see android.media.MediaPlayer#getTrackInfo
   2665      */
   2666     public void selectTrack(int index) throws IllegalStateException {
   2667         selectOrDeselectTrack(index, true /* select */);
   2668     }
   2669 
   2670     /**
   2671      * Deselect a track.
   2672      * <p>
   2673      * Currently, the track must be a timed text track and no audio or video tracks can be
   2674      * deselected. If the timed text track identified by index has not been
   2675      * selected before, it throws an exception.
   2676      * </p>
   2677      * @param index the index of the track to be deselected. The valid range of the index
   2678      * is 0..total number of tracks - 1. The total number of tracks as well as the type of
   2679      * each individual track can be found by calling {@link #getTrackInfo()} method.
   2680      * @throws IllegalStateException if called in an invalid state.
   2681      *
   2682      * @see android.media.MediaPlayer#getTrackInfo
   2683      */
   2684     public void deselectTrack(int index) throws IllegalStateException {
   2685         selectOrDeselectTrack(index, false /* select */);
   2686     }
   2687 
   2688     private void selectOrDeselectTrack(int index, boolean select)
   2689             throws IllegalStateException {
   2690         // handle subtitle track through subtitle controller
   2691         populateInbandTracks();
   2692 
   2693         Pair<Integer,SubtitleTrack> p = null;
   2694         try {
   2695             p = mIndexTrackPairs.get(index);
   2696         } catch (ArrayIndexOutOfBoundsException e) {
   2697             // ignore bad index
   2698             return;
   2699         }
   2700 
   2701         SubtitleTrack track = p.second;
   2702         if (track == null) {
   2703             // inband (de)select
   2704             selectOrDeselectInbandTrack(p.first, select);
   2705             return;
   2706         }
   2707 
   2708         if (mSubtitleController == null) {
   2709             return;
   2710         }
   2711 
   2712         if (!select) {
   2713             // out-of-band deselect
   2714             if (mSubtitleController.getSelectedTrack() == track) {
   2715                 mSubtitleController.selectTrack(null);
   2716             } else {
   2717                 Log.w(TAG, "trying to deselect track that was not selected");
   2718             }
   2719             return;
   2720         }
   2721 
   2722         // out-of-band select
   2723         if (track.getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT) {
   2724             int ttIndex = getSelectedTrack(TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT);
   2725             synchronized (mIndexTrackPairs) {
   2726                 if (ttIndex >= 0 && ttIndex < mIndexTrackPairs.size()) {
   2727                     Pair<Integer,SubtitleTrack> p2 = mIndexTrackPairs.get(ttIndex);
   2728                     if (p2.first != null && p2.second == null) {
   2729                         // deselect inband counterpart
   2730                         selectOrDeselectInbandTrack(p2.first, false);
   2731                     }
   2732                 }
   2733             }
   2734         }
   2735         mSubtitleController.selectTrack(track);
   2736     }
   2737 
   2738     private void selectOrDeselectInbandTrack(int index, boolean select)
   2739             throws IllegalStateException {
   2740         Parcel request = Parcel.obtain();
   2741         Parcel reply = Parcel.obtain();
   2742         try {
   2743             request.writeInterfaceToken(IMEDIA_PLAYER);
   2744             request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK);
   2745             request.writeInt(index);
   2746             invoke(request, reply);
   2747         } finally {
   2748             request.recycle();
   2749             reply.recycle();
   2750         }
   2751     }
   2752 
   2753 
   2754     /**
   2755      * @param reply Parcel with audio/video duration info for battery
   2756                     tracking usage
   2757      * @return The status code.
   2758      * {@hide}
   2759      */
   2760     public native static int native_pullBatteryData(Parcel reply);
   2761 
   2762     /**
   2763      * Sets the target UDP re-transmit endpoint for the low level player.
   2764      * Generally, the address portion of the endpoint is an IP multicast
   2765      * address, although a unicast address would be equally valid.  When a valid
   2766      * retransmit endpoint has been set, the media player will not decode and
   2767      * render the media presentation locally.  Instead, the player will attempt
   2768      * to re-multiplex its media data using the Android@Home RTP profile and
   2769      * re-transmit to the target endpoint.  Receiver devices (which may be
   2770      * either the same as the transmitting device or different devices) may
   2771      * instantiate, prepare, and start a receiver player using a setDataSource
   2772      * URL of the form...
   2773      *
   2774      * aahRX://&lt;multicastIP&gt;:&lt;port&gt;
   2775      *
   2776      * to receive, decode and render the re-transmitted content.
   2777      *
   2778      * setRetransmitEndpoint may only be called before setDataSource has been
   2779      * called; while the player is in the Idle state.
   2780      *
   2781      * @param endpoint the address and UDP port of the re-transmission target or
   2782      * null if no re-transmission is to be performed.
   2783      * @throws IllegalStateException if it is called in an invalid state
   2784      * @throws IllegalArgumentException if the retransmit endpoint is supplied,
   2785      * but invalid.
   2786      *
   2787      * {@hide} pending API council
   2788      */
   2789     public void setRetransmitEndpoint(InetSocketAddress endpoint)
   2790             throws IllegalStateException, IllegalArgumentException
   2791     {
   2792         String addrString = null;
   2793         int port = 0;
   2794 
   2795         if (null != endpoint) {
   2796             addrString = endpoint.getAddress().getHostAddress();
   2797             port = endpoint.getPort();
   2798         }
   2799 
   2800         int ret = native_setRetransmitEndpoint(addrString, port);
   2801         if (ret != 0) {
   2802             throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret);
   2803         }
   2804     }
   2805 
   2806     private native final int native_setRetransmitEndpoint(String addrString, int port);
   2807 
   2808     @Override
   2809     protected void finalize() {
   2810         baseRelease();
   2811         native_finalize();
   2812     }
   2813 
   2814     /* Do not change these values without updating their counterparts
   2815      * in include/media/mediaplayer.h!
   2816      */
   2817     private static final int MEDIA_NOP = 0; // interface test message
   2818     private static final int MEDIA_PREPARED = 1;
   2819     private static final int MEDIA_PLAYBACK_COMPLETE = 2;
   2820     private static final int MEDIA_BUFFERING_UPDATE = 3;
   2821     private static final int MEDIA_SEEK_COMPLETE = 4;
   2822     private static final int MEDIA_SET_VIDEO_SIZE = 5;
   2823     private static final int MEDIA_STARTED = 6;
   2824     private static final int MEDIA_PAUSED = 7;
   2825     private static final int MEDIA_STOPPED = 8;
   2826     private static final int MEDIA_SKIPPED = 9;
   2827     private static final int MEDIA_TIMED_TEXT = 99;
   2828     private static final int MEDIA_ERROR = 100;
   2829     private static final int MEDIA_INFO = 200;
   2830     private static final int MEDIA_SUBTITLE_DATA = 201;
   2831     private static final int MEDIA_META_DATA = 202;
   2832 
   2833     private TimeProvider mTimeProvider;
   2834 
   2835     /** @hide */
   2836     public MediaTimeProvider getMediaTimeProvider() {
   2837         if (mTimeProvider == null) {
   2838             mTimeProvider = new TimeProvider(this);
   2839         }
   2840         return mTimeProvider;
   2841     }
   2842 
   2843     private class EventHandler extends Handler
   2844     {
   2845         private MediaPlayer mMediaPlayer;
   2846 
   2847         public EventHandler(MediaPlayer mp, Looper looper) {
   2848             super(looper);
   2849             mMediaPlayer = mp;
   2850         }
   2851 
   2852         @Override
   2853         public void handleMessage(Message msg) {
   2854             if (mMediaPlayer.mNativeContext == 0) {
   2855                 Log.w(TAG, "mediaplayer went away with unhandled events");
   2856                 return;
   2857             }
   2858             switch(msg.what) {
   2859             case MEDIA_PREPARED:
   2860                 try {
   2861                     scanInternalSubtitleTracks();
   2862                 } catch (RuntimeException e) {
   2863                     // send error message instead of crashing;
   2864                     // send error message instead of inlining a call to onError
   2865                     // to avoid code duplication.
   2866                     Message msg2 = obtainMessage(
   2867                             MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_UNSUPPORTED, null);
   2868                     sendMessage(msg2);
   2869                 }
   2870                 OnPreparedListener onPreparedListener = mOnPreparedListener;
   2871                 if (onPreparedListener != null)
   2872                     onPreparedListener.onPrepared(mMediaPlayer);
   2873                 return;
   2874 
   2875             case MEDIA_PLAYBACK_COMPLETE:
   2876                 {
   2877                     OnCompletionListener onCompletionListener = mOnCompletionListener;
   2878                     if (onCompletionListener != null)
   2879                         onCompletionListener.onCompletion(mMediaPlayer);
   2880                 }
   2881                 stayAwake(false);
   2882                 return;
   2883 
   2884             case MEDIA_STOPPED:
   2885                 {
   2886                     TimeProvider timeProvider = mTimeProvider;
   2887                     if (timeProvider != null) {
   2888                         timeProvider.onStopped();
   2889                     }
   2890                 }
   2891                 break;
   2892 
   2893             case MEDIA_STARTED:
   2894             case MEDIA_PAUSED:
   2895                 {
   2896                     TimeProvider timeProvider = mTimeProvider;
   2897                     if (timeProvider != null) {
   2898                         timeProvider.onPaused(msg.what == MEDIA_PAUSED);
   2899                     }
   2900                 }
   2901                 break;
   2902 
   2903             case MEDIA_BUFFERING_UPDATE:
   2904                 OnBufferingUpdateListener onBufferingUpdateListener = mOnBufferingUpdateListener;
   2905                 if (onBufferingUpdateListener != null)
   2906                     onBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1);
   2907                 return;
   2908 
   2909             case MEDIA_SEEK_COMPLETE:
   2910                 OnSeekCompleteListener onSeekCompleteListener = mOnSeekCompleteListener;
   2911                 if (onSeekCompleteListener != null) {
   2912                     onSeekCompleteListener.onSeekComplete(mMediaPlayer);
   2913                 }
   2914                 // fall through
   2915 
   2916             case MEDIA_SKIPPED:
   2917                 {
   2918                     TimeProvider timeProvider = mTimeProvider;
   2919                     if (timeProvider != null) {
   2920                         timeProvider.onSeekComplete(mMediaPlayer);
   2921                     }
   2922                 }
   2923                 return;
   2924 
   2925             case MEDIA_SET_VIDEO_SIZE:
   2926                 OnVideoSizeChangedListener onVideoSizeChangedListener = mOnVideoSizeChangedListener;
   2927                 if (onVideoSizeChangedListener != null) {
   2928                     onVideoSizeChangedListener.onVideoSizeChanged(
   2929                         mMediaPlayer, msg.arg1, msg.arg2);
   2930                 }
   2931                 return;
   2932 
   2933             case MEDIA_ERROR:
   2934                 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")");
   2935                 boolean error_was_handled = false;
   2936                 OnErrorListener onErrorListener = mOnErrorListener;
   2937                 if (onErrorListener != null) {
   2938                     error_was_handled = onErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2);
   2939                 }
   2940                 {
   2941                     OnCompletionListener onCompletionListener = mOnCompletionListener;
   2942                     if (onCompletionListener != null && ! error_was_handled) {
   2943                         onCompletionListener.onCompletion(mMediaPlayer);
   2944                     }
   2945                 }
   2946                 stayAwake(false);
   2947                 return;
   2948 
   2949             case MEDIA_INFO:
   2950                 switch (msg.arg1) {
   2951                 case MEDIA_INFO_VIDEO_TRACK_LAGGING:
   2952                     Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")");
   2953                     break;
   2954                 case MEDIA_INFO_METADATA_UPDATE:
   2955                     try {
   2956                         scanInternalSubtitleTracks();
   2957                     } catch (RuntimeException e) {
   2958                         Message msg2 = obtainMessage(
   2959                                 MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, MEDIA_ERROR_UNSUPPORTED, null);
   2960                         sendMessage(msg2);
   2961                     }
   2962                     // fall through
   2963 
   2964                 case MEDIA_INFO_EXTERNAL_METADATA_UPDATE:
   2965                     msg.arg1 = MEDIA_INFO_METADATA_UPDATE;
   2966                     // update default track selection
   2967                     if (mSubtitleController != null) {
   2968                         mSubtitleController.selectDefaultTrack();
   2969                     }
   2970                     break;
   2971                 case MEDIA_INFO_BUFFERING_START:
   2972                 case MEDIA_INFO_BUFFERING_END:
   2973                     TimeProvider timeProvider = mTimeProvider;
   2974                     if (timeProvider != null) {
   2975                         timeProvider.onBuffering(msg.arg1 == MEDIA_INFO_BUFFERING_START);
   2976                     }
   2977                     break;
   2978                 }
   2979 
   2980                 OnInfoListener onInfoListener = mOnInfoListener;
   2981                 if (onInfoListener != null) {
   2982                     onInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2);
   2983                 }
   2984                 // No real default action so far.
   2985                 return;
   2986             case MEDIA_TIMED_TEXT:
   2987                 OnTimedTextListener onTimedTextListener = mOnTimedTextListener;
   2988                 if (onTimedTextListener == null)
   2989                     return;
   2990                 if (msg.obj == null) {
   2991                     onTimedTextListener.onTimedText(mMediaPlayer, null);
   2992                 } else {
   2993                     if (msg.obj instanceof Parcel) {
   2994                         Parcel parcel = (Parcel)msg.obj;
   2995                         TimedText text = new TimedText(parcel);
   2996                         parcel.recycle();
   2997                         onTimedTextListener.onTimedText(mMediaPlayer, text);
   2998                     }
   2999                 }
   3000                 return;
   3001 
   3002             case MEDIA_SUBTITLE_DATA:
   3003                 OnSubtitleDataListener onSubtitleDataListener = mOnSubtitleDataListener;
   3004                 if (onSubtitleDataListener == null) {
   3005                     return;
   3006                 }
   3007                 if (msg.obj instanceof Parcel) {
   3008                     Parcel parcel = (Parcel) msg.obj;
   3009                     SubtitleData data = new SubtitleData(parcel);
   3010                     parcel.recycle();
   3011                     onSubtitleDataListener.onSubtitleData(mMediaPlayer, data);
   3012                 }
   3013                 return;
   3014 
   3015             case MEDIA_META_DATA:
   3016                 OnTimedMetaDataAvailableListener onTimedMetaDataAvailableListener =
   3017                     mOnTimedMetaDataAvailableListener;
   3018                 if (onTimedMetaDataAvailableListener == null) {
   3019                     return;
   3020                 }
   3021                 if (msg.obj instanceof Parcel) {
   3022                     Parcel parcel = (Parcel) msg.obj;
   3023                     TimedMetaData data = TimedMetaData.createTimedMetaDataFromParcel(parcel);
   3024                     parcel.recycle();
   3025                     onTimedMetaDataAvailableListener.onTimedMetaDataAvailable(mMediaPlayer, data);
   3026                 }
   3027                 return;
   3028 
   3029             case MEDIA_NOP: // interface test message - ignore
   3030                 break;
   3031 
   3032             default:
   3033                 Log.e(TAG, "Unknown message type " + msg.what);
   3034                 return;
   3035             }
   3036         }
   3037     }
   3038 
   3039     /*
   3040      * Called from native code when an interesting event happens.  This method
   3041      * just uses the EventHandler system to post the event back to the main app thread.
   3042      * We use a weak reference to the original MediaPlayer object so that the native
   3043      * code is safe from the object disappearing from underneath it.  (This is
   3044      * the cookie passed to native_setup().)
   3045      */
   3046     private static void postEventFromNative(Object mediaplayer_ref,
   3047                                             int what, int arg1, int arg2, Object obj)
   3048     {
   3049         MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get();
   3050         if (mp == null) {
   3051             return;
   3052         }
   3053 
   3054         if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) {
   3055             // this acquires the wakelock if needed, and sets the client side state
   3056             mp.start();
   3057         }
   3058         if (mp.mEventHandler != null) {
   3059             Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj);
   3060             mp.mEventHandler.sendMessage(m);
   3061         }
   3062     }
   3063 
   3064     /**
   3065      * Interface definition for a callback to be invoked when the media
   3066      * source is ready for playback.
   3067      */
   3068     public interface OnPreparedListener
   3069     {
   3070         /**
   3071          * Called when the media file is ready for playback.
   3072          *
   3073          * @param mp the MediaPlayer that is ready for playback
   3074          */
   3075         void onPrepared(MediaPlayer mp);
   3076     }
   3077 
   3078     /**
   3079      * Register a callback to be invoked when the media source is ready
   3080      * for playback.
   3081      *
   3082      * @param listener the callback that will be run
   3083      */
   3084     public void setOnPreparedListener(OnPreparedListener listener)
   3085     {
   3086         mOnPreparedListener = listener;
   3087     }
   3088 
   3089     private OnPreparedListener mOnPreparedListener;
   3090 
   3091     /**
   3092      * Interface definition for a callback to be invoked when playback of
   3093      * a media source has completed.
   3094      */
   3095     public interface OnCompletionListener
   3096     {
   3097         /**
   3098          * Called when the end of a media source is reached during playback.
   3099          *
   3100          * @param mp the MediaPlayer that reached the end of the file
   3101          */
   3102         void onCompletion(MediaPlayer mp);
   3103     }
   3104 
   3105     /**
   3106      * Register a callback to be invoked when the end of a media source
   3107      * has been reached during playback.
   3108      *
   3109      * @param listener the callback that will be run
   3110      */
   3111     public void setOnCompletionListener(OnCompletionListener listener)
   3112     {
   3113         mOnCompletionListener = listener;
   3114     }
   3115 
   3116     private OnCompletionListener mOnCompletionListener;
   3117 
   3118     /**
   3119      * Interface definition of a callback to be invoked indicating buffering
   3120      * status of a media resource being streamed over the network.
   3121      */
   3122     public interface OnBufferingUpdateListener
   3123     {
   3124         /**
   3125          * Called to update status in buffering a media stream received through
   3126          * progressive HTTP download. The received buffering percentage
   3127          * indicates how much of the content has been buffered or played.
   3128          * For example a buffering update of 80 percent when half the content
   3129          * has already been played indicates that the next 30 percent of the
   3130          * content to play has been buffered.
   3131          *
   3132          * @param mp      the MediaPlayer the update pertains to
   3133          * @param percent the percentage (0-100) of the content
   3134          *                that has been buffered or played thus far
   3135          */
   3136         void onBufferingUpdate(MediaPlayer mp, int percent);
   3137     }
   3138 
   3139     /**
   3140      * Register a callback to be invoked when the status of a network
   3141      * stream's buffer has changed.
   3142      *
   3143      * @param listener the callback that will be run.
   3144      */
   3145     public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener)
   3146     {
   3147         mOnBufferingUpdateListener = listener;
   3148     }
   3149 
   3150     private OnBufferingUpdateListener mOnBufferingUpdateListener;
   3151 
   3152     /**
   3153      * Interface definition of a callback to be invoked indicating
   3154      * the completion of a seek operation.
   3155      */
   3156     public interface OnSeekCompleteListener
   3157     {
   3158         /**
   3159          * Called to indicate the completion of a seek operation.
   3160          *
   3161          * @param mp the MediaPlayer that issued the seek operation
   3162          */
   3163         public void onSeekComplete(MediaPlayer mp);
   3164     }
   3165 
   3166     /**
   3167      * Register a callback to be invoked when a seek operation has been
   3168      * completed.
   3169      *
   3170      * @param listener the callback that will be run
   3171      */
   3172     public void setOnSeekCompleteListener(OnSeekCompleteListener listener)
   3173     {
   3174         mOnSeekCompleteListener = listener;
   3175     }
   3176 
   3177     private OnSeekCompleteListener mOnSeekCompleteListener;
   3178 
   3179     /**
   3180      * Interface definition of a callback to be invoked when the
   3181      * video size is first known or updated
   3182      */
   3183     public interface OnVideoSizeChangedListener
   3184     {
   3185         /**
   3186          * Called to indicate the video size
   3187          *
   3188          * The video size (width and height) could be 0 if there was no video,
   3189          * no display surface was set, or the value was not determined yet.
   3190          *
   3191          * @param mp        the MediaPlayer associated with this callback
   3192          * @param width     the width of the video
   3193          * @param height    the height of the video
   3194          */
   3195         public void onVideoSizeChanged(MediaPlayer mp, int width, int height);
   3196     }
   3197 
   3198     /**
   3199      * Register a callback to be invoked when the video size is
   3200      * known or updated.
   3201      *
   3202      * @param listener the callback that will be run
   3203      */
   3204     public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener)
   3205     {
   3206         mOnVideoSizeChangedListener = listener;
   3207     }
   3208 
   3209     private OnVideoSizeChangedListener mOnVideoSizeChangedListener;
   3210 
   3211     /**
   3212      * Interface definition of a callback to be invoked when a
   3213      * timed text is available for display.
   3214      */
   3215     public interface OnTimedTextListener
   3216     {
   3217         /**
   3218          * Called to indicate an avaliable timed text
   3219          *
   3220          * @param mp             the MediaPlayer associated with this callback
   3221          * @param text           the timed text sample which contains the text
   3222          *                       needed to be displayed and the display format.
   3223          */
   3224         public void onTimedText(MediaPlayer mp, TimedText text);
   3225     }
   3226 
   3227     /**
   3228      * Register a callback to be invoked when a timed text is available
   3229      * for display.
   3230      *
   3231      * @param listener the callback that will be run
   3232      */
   3233     public void setOnTimedTextListener(OnTimedTextListener listener)
   3234     {
   3235         mOnTimedTextListener = listener;
   3236     }
   3237 
   3238     private OnTimedTextListener mOnTimedTextListener;
   3239 
   3240     /**
   3241      * Interface definition of a callback to be invoked when a
   3242      * track has data available.
   3243      *
   3244      * @hide
   3245      */
   3246     public interface OnSubtitleDataListener
   3247     {
   3248         public void onSubtitleData(MediaPlayer mp, SubtitleData data);
   3249     }
   3250 
   3251     /**
   3252      * Register a callback to be invoked when a track has data available.
   3253      *
   3254      * @param listener the callback that will be run
   3255      *
   3256      * @hide
   3257      */
   3258     public void setOnSubtitleDataListener(OnSubtitleDataListener listener)
   3259     {
   3260         mOnSubtitleDataListener = listener;
   3261     }
   3262 
   3263     private OnSubtitleDataListener mOnSubtitleDataListener;
   3264 
   3265     /**
   3266      * Interface definition of a callback to be invoked when a
   3267      * track has timed metadata available.
   3268      *
   3269      * @see MediaPlayer#setOnTimedMetaDataAvailableListener(OnTimedMetaDataAvailableListener)
   3270      */
   3271     public interface OnTimedMetaDataAvailableListener
   3272     {
   3273         /**
   3274          * Called to indicate avaliable timed metadata
   3275          * <p>
   3276          * This method will be called as timed metadata is extracted from the media,
   3277          * in the same order as it occurs in the media. The timing of this event is
   3278          * not controlled by the associated timestamp.
   3279          *
   3280          * @param mp             the MediaPlayer associated with this callback
   3281          * @param data           the timed metadata sample associated with this event
   3282          */
   3283         public void onTimedMetaDataAvailable(MediaPlayer mp, TimedMetaData data);
   3284     }
   3285 
   3286     /**
   3287      * Register a callback to be invoked when a selected track has timed metadata available.
   3288      * <p>
   3289      * Currently only HTTP live streaming data URI's embedded with timed ID3 tags generates
   3290      * {@link TimedMetaData}.
   3291      *
   3292      * @see MediaPlayer#selectTrack(int)
   3293      * @see MediaPlayer.OnTimedMetaDataAvailableListener
   3294      * @see TimedMetaData
   3295      *
   3296      * @param listener the callback that will be run
   3297      */
   3298     public void setOnTimedMetaDataAvailableListener(OnTimedMetaDataAvailableListener listener)
   3299     {
   3300         mOnTimedMetaDataAvailableListener = listener;
   3301     }
   3302 
   3303     private OnTimedMetaDataAvailableListener mOnTimedMetaDataAvailableListener;
   3304 
   3305     /* Do not change these values without updating their counterparts
   3306      * in include/media/mediaplayer.h!
   3307      */
   3308     /** Unspecified media player error.
   3309      * @see android.media.MediaPlayer.OnErrorListener
   3310      */
   3311     public static final int MEDIA_ERROR_UNKNOWN = 1;
   3312 
   3313     /** Media server died. In this case, the application must release the
   3314      * MediaPlayer object and instantiate a new one.
   3315      * @see android.media.MediaPlayer.OnErrorListener
   3316      */
   3317     public static final int MEDIA_ERROR_SERVER_DIED = 100;
   3318 
   3319     /** The video is streamed and its container is not valid for progressive
   3320      * playback i.e the video's index (e.g moov atom) is not at the start of the
   3321      * file.
   3322      * @see android.media.MediaPlayer.OnErrorListener
   3323      */
   3324     public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200;
   3325 
   3326     /** File or network related operation errors. */
   3327     public static final int MEDIA_ERROR_IO = -1004;
   3328     /** Bitstream is not conforming to the related coding standard or file spec. */
   3329     public static final int MEDIA_ERROR_MALFORMED = -1007;
   3330     /** Bitstream is conforming to the related coding standard or file spec, but
   3331      * the media framework does not support the feature. */
   3332     public static final int MEDIA_ERROR_UNSUPPORTED = -1010;
   3333     /** Some operation takes too long to complete, usually more than 3-5 seconds. */
   3334     public static final int MEDIA_ERROR_TIMED_OUT = -110;
   3335 
   3336     /** Unspecified low-level system error. This value originated from UNKNOWN_ERROR in
   3337      * system/core/include/utils/Errors.h
   3338      * @see android.media.MediaPlayer.OnErrorListener
   3339      * @hide
   3340      */
   3341     public static final int MEDIA_ERROR_SYSTEM = -2147483648;
   3342 
   3343     /**
   3344      * Interface definition of a callback to be invoked when there
   3345      * has been an error during an asynchronous operation (other errors
   3346      * will throw exceptions at method call time).
   3347      */
   3348     public interface OnErrorListener
   3349     {
   3350         /**
   3351          * Called to indicate an error.
   3352          *
   3353          * @param mp      the MediaPlayer the error pertains to
   3354          * @param what    the type of error that has occurred:
   3355          * <ul>
   3356          * <li>{@link #MEDIA_ERROR_UNKNOWN}
   3357          * <li>{@link #MEDIA_ERROR_SERVER_DIED}
   3358          * </ul>
   3359          * @param extra an extra code, specific to the error. Typically
   3360          * implementation dependent.
   3361          * <ul>
   3362          * <li>{@link #MEDIA_ERROR_IO}
   3363          * <li>{@link #MEDIA_ERROR_MALFORMED}
   3364          * <li>{@link #MEDIA_ERROR_UNSUPPORTED}
   3365          * <li>{@link #MEDIA_ERROR_TIMED_OUT}
   3366          * <li><code>MEDIA_ERROR_SYSTEM (-2147483648)</code> - low-level system error.
   3367          * </ul>
   3368          * @return True if the method handled the error, false if it didn't.
   3369          * Returning false, or not having an OnErrorListener at all, will
   3370          * cause the OnCompletionListener to be called.
   3371          */
   3372         boolean onError(MediaPlayer mp, int what, int extra);
   3373     }
   3374 
   3375     /**
   3376      * Register a callback to be invoked when an error has happened
   3377      * during an asynchronous operation.
   3378      *
   3379      * @param listener the callback that will be run
   3380      */
   3381     public void setOnErrorListener(OnErrorListener listener)
   3382     {
   3383         mOnErrorListener = listener;
   3384     }
   3385 
   3386     private OnErrorListener mOnErrorListener;
   3387 
   3388 
   3389     /* Do not change these values without updating their counterparts
   3390      * in include/media/mediaplayer.h!
   3391      */
   3392     /** Unspecified media player info.
   3393      * @see android.media.MediaPlayer.OnInfoListener
   3394      */
   3395     public static final int MEDIA_INFO_UNKNOWN = 1;
   3396 
   3397     /** The player was started because it was used as the next player for another
   3398      * player, which just completed playback.
   3399      * @see android.media.MediaPlayer.OnInfoListener
   3400      * @hide
   3401      */
   3402     public static final int MEDIA_INFO_STARTED_AS_NEXT = 2;
   3403 
   3404     /** The player just pushed the very first video frame for rendering.
   3405      * @see android.media.MediaPlayer.OnInfoListener
   3406      */
   3407     public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3;
   3408 
   3409     /** The video is too complex for the decoder: it can't decode frames fast
   3410      *  enough. Possibly only the audio plays fine at this stage.
   3411      * @see android.media.MediaPlayer.OnInfoListener
   3412      */
   3413     public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700;
   3414 
   3415     /** MediaPlayer is temporarily pausing playback internally in order to
   3416      * buffer more data.
   3417      * @see android.media.MediaPlayer.OnInfoListener
   3418      */
   3419     public static final int MEDIA_INFO_BUFFERING_START = 701;
   3420 
   3421     /** MediaPlayer is resuming playback after filling buffers.
   3422      * @see android.media.MediaPlayer.OnInfoListener
   3423      */
   3424     public static final int MEDIA_INFO_BUFFERING_END = 702;
   3425 
   3426     /** Estimated network bandwidth information (kbps) is available; currently this event fires
   3427      * simultaneously as {@link #MEDIA_INFO_BUFFERING_START} and {@link #MEDIA_INFO_BUFFERING_END}
   3428      * when playing network files.
   3429      * @see android.media.MediaPlayer.OnInfoListener
   3430      * @hide
   3431      */
   3432     public static final int MEDIA_INFO_NETWORK_BANDWIDTH = 703;
   3433 
   3434     /** Bad interleaving means that a media has been improperly interleaved or
   3435      * not interleaved at all, e.g has all the video samples first then all the
   3436      * audio ones. Video is playing but a lot of disk seeks may be happening.
   3437      * @see android.media.MediaPlayer.OnInfoListener
   3438      */
   3439     public static final int MEDIA_INFO_BAD_INTERLEAVING = 800;
   3440 
   3441     /** The media cannot be seeked (e.g live stream)
   3442      * @see android.media.MediaPlayer.OnInfoListener
   3443      */
   3444     public static final int MEDIA_INFO_NOT_SEEKABLE = 801;
   3445 
   3446     /** A new set of metadata is available.
   3447      * @see android.media.MediaPlayer.OnInfoListener
   3448      */
   3449     public static final int MEDIA_INFO_METADATA_UPDATE = 802;
   3450 
   3451     /** A new set of external-only metadata is available.  Used by
   3452      *  JAVA framework to avoid triggering track scanning.
   3453      * @hide
   3454      */
   3455     public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803;
   3456 
   3457     /** Failed to handle timed text track properly.
   3458      * @see android.media.MediaPlayer.OnInfoListener
   3459      *
   3460      * {@hide}
   3461      */
   3462     public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900;
   3463 
   3464     /** Subtitle track was not supported by the media framework.
   3465      * @see android.media.MediaPlayer.OnInfoListener
   3466      */
   3467     public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901;
   3468 
   3469     /** Reading the subtitle track takes too long.
   3470      * @see android.media.MediaPlayer.OnInfoListener
   3471      */
   3472     public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902;
   3473 
   3474     /**
   3475      * Interface definition of a callback to be invoked to communicate some
   3476      * info and/or warning about the media or its playback.
   3477      */
   3478     public interface OnInfoListener
   3479     {
   3480         /**
   3481          * Called to indicate an info or a warning.
   3482          *
   3483          * @param mp      the MediaPlayer the info pertains to.
   3484          * @param what    the type of info or warning.
   3485          * <ul>
   3486          * <li>{@link #MEDIA_INFO_UNKNOWN}
   3487          * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING}
   3488          * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START}
   3489          * <li>{@link #MEDIA_INFO_BUFFERING_START}
   3490          * <li>{@link #MEDIA_INFO_BUFFERING_END}
   3491          * <li><code>MEDIA_INFO_NETWORK_BANDWIDTH (703)</code> -
   3492          *     bandwidth information is available (as <code>extra</code> kbps)
   3493          * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING}
   3494          * <li>{@link #MEDIA_INFO_NOT_SEEKABLE}
   3495          * <li>{@link #MEDIA_INFO_METADATA_UPDATE}
   3496          * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE}
   3497          * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT}
   3498          * </ul>
   3499          * @param extra an extra code, specific to the info. Typically
   3500          * implementation dependent.
   3501          * @return True if the method handled the info, false if it didn't.
   3502          * Returning false, or not having an OnInfoListener at all, will
   3503          * cause the info to be discarded.
   3504          */
   3505         boolean onInfo(MediaPlayer mp, int what, int extra);
   3506     }
   3507 
   3508     /**
   3509      * Register a callback to be invoked when an info/warning is available.
   3510      *
   3511      * @param listener the callback that will be run
   3512      */
   3513     public void setOnInfoListener(OnInfoListener listener)
   3514     {
   3515         mOnInfoListener = listener;
   3516     }
   3517 
   3518     private OnInfoListener mOnInfoListener;
   3519 
   3520     /*
   3521      * Test whether a given video scaling mode is supported.
   3522      */
   3523     private boolean isVideoScalingModeSupported(int mode) {
   3524         return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT ||
   3525                 mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING);
   3526     }
   3527 
   3528     /** @hide */
   3529     static class TimeProvider implements MediaPlayer.OnSeekCompleteListener,
   3530             MediaTimeProvider {
   3531         private static final String TAG = "MTP";
   3532         private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L;
   3533         private static final long MAX_EARLY_CALLBACK_US = 1000;
   3534         private static final long TIME_ADJUSTMENT_RATE = 2;  /* meaning 1/2 */
   3535         private long mLastTimeUs = 0;
   3536         private MediaPlayer mPlayer;
   3537         private boolean mPaused = true;
   3538         private boolean mStopped = true;
   3539         private boolean mBuffering;
   3540         private long mLastReportedTime;
   3541         private long mTimeAdjustment;
   3542         // since we are expecting only a handful listeners per stream, there is
   3543         // no need for log(N) search performance
   3544         private MediaTimeProvider.OnMediaTimeListener mListeners[];
   3545         private long mTimes[];
   3546         private long mLastNanoTime;
   3547         private Handler mEventHandler;
   3548         private boolean mRefresh = false;
   3549         private boolean mPausing = false;
   3550         private boolean mSeeking = false;
   3551         private static final int NOTIFY = 1;
   3552         private static final int NOTIFY_TIME = 0;
   3553         private static final int REFRESH_AND_NOTIFY_TIME = 1;
   3554         private static final int NOTIFY_STOP = 2;
   3555         private static final int NOTIFY_SEEK = 3;
   3556         private static final int NOTIFY_TRACK_DATA = 4;
   3557         private HandlerThread mHandlerThread;
   3558 
   3559         /** @hide */
   3560         public boolean DEBUG = false;
   3561 
   3562         public TimeProvider(MediaPlayer mp) {
   3563             mPlayer = mp;
   3564             try {
   3565                 getCurrentTimeUs(true, false);
   3566             } catch (IllegalStateException e) {
   3567                 // we assume starting position
   3568                 mRefresh = true;
   3569             }
   3570 
   3571             Looper looper;
   3572             if ((looper = Looper.myLooper()) == null &&
   3573                 (looper = Looper.getMainLooper()) == null) {
   3574                 // Create our own looper here in case MP was created without one
   3575                 mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread",
   3576                       Process.THREAD_PRIORITY_FOREGROUND);
   3577                 mHandlerThread.start();
   3578                 looper = mHandlerThread.getLooper();
   3579             }
   3580             mEventHandler = new EventHandler(looper);
   3581 
   3582             mListeners = new MediaTimeProvider.OnMediaTimeListener[0];
   3583             mTimes = new long[0];
   3584             mLastTimeUs = 0;
   3585             mTimeAdjustment = 0;
   3586         }
   3587 
   3588         private void scheduleNotification(int type, long delayUs) {
   3589             // ignore time notifications until seek is handled
   3590             if (mSeeking &&
   3591                     (type == NOTIFY_TIME || type == REFRESH_AND_NOTIFY_TIME)) {
   3592                 return;
   3593             }
   3594 
   3595             if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs);
   3596             mEventHandler.removeMessages(NOTIFY);
   3597             Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0);
   3598             mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000));
   3599         }
   3600 
   3601         /** @hide */
   3602         public void close() {
   3603             mEventHandler.removeMessages(NOTIFY);
   3604             if (mHandlerThread != null) {
   3605                 mHandlerThread.quitSafely();
   3606                 mHandlerThread = null;
   3607             }
   3608         }
   3609 
   3610         /** @hide */
   3611         protected void finalize() {
   3612             if (mHandlerThread != null) {
   3613                 mHandlerThread.quitSafely();
   3614             }
   3615         }
   3616 
   3617         /** @hide */
   3618         public void onPaused(boolean paused) {
   3619             synchronized(this) {
   3620                 if (DEBUG) Log.d(TAG, "onPaused: " + paused);
   3621                 if (mStopped) { // handle as seek if we were stopped
   3622                     mStopped = false;
   3623                     mSeeking = true;
   3624                     scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
   3625                 } else {
   3626                     mPausing = paused;  // special handling if player disappeared
   3627                     mSeeking = false;
   3628                     scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
   3629                 }
   3630             }
   3631         }
   3632 
   3633         /** @hide */
   3634         public void onBuffering(boolean buffering) {
   3635             synchronized (this) {
   3636                 if (DEBUG) Log.d(TAG, "onBuffering: " + buffering);
   3637                 mBuffering = buffering;
   3638                 scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */);
   3639             }
   3640         }
   3641 
   3642         /** @hide */
   3643         public void onStopped() {
   3644             synchronized(this) {
   3645                 if (DEBUG) Log.d(TAG, "onStopped");
   3646                 mPaused = true;
   3647                 mStopped = true;
   3648                 mSeeking = false;
   3649                 mBuffering = false;
   3650                 scheduleNotification(NOTIFY_STOP, 0 /* delay */);
   3651             }
   3652         }
   3653 
   3654         /** @hide */
   3655         @Override
   3656         public void onSeekComplete(MediaPlayer mp) {
   3657             synchronized(this) {
   3658                 mStopped = false;
   3659                 mSeeking = true;
   3660                 scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
   3661             }
   3662         }
   3663 
   3664         /** @hide */
   3665         public void onNewPlayer() {
   3666             if (mRefresh) {
   3667                 synchronized(this) {
   3668                     mStopped = false;
   3669                     mSeeking = true;
   3670                     mBuffering = false;
   3671                     scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
   3672                 }
   3673             }
   3674         }
   3675 
   3676         private synchronized void notifySeek() {
   3677             mSeeking = false;
   3678             try {
   3679                 long timeUs = getCurrentTimeUs(true, false);
   3680                 if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs);
   3681 
   3682                 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
   3683                     if (listener == null) {
   3684                         break;
   3685                     }
   3686                     listener.onSeek(timeUs);
   3687                 }
   3688             } catch (IllegalStateException e) {
   3689                 // we should not be there, but at least signal pause
   3690                 if (DEBUG) Log.d(TAG, "onSeekComplete but no player");
   3691                 mPausing = true;  // special handling if player disappeared
   3692                 notifyTimedEvent(false /* refreshTime */);
   3693             }
   3694         }
   3695 
   3696         private synchronized void notifyTrackData(Pair<SubtitleTrack, byte[]> trackData) {
   3697             SubtitleTrack track = trackData.first;
   3698             byte[] data = trackData.second;
   3699             track.onData(data, true /* eos */, ~0 /* runID: keep forever */);
   3700         }
   3701 
   3702         private synchronized void notifyStop() {
   3703             for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) {
   3704                 if (listener == null) {
   3705                     break;
   3706                 }
   3707                 listener.onStop();
   3708             }
   3709         }
   3710 
   3711         private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) {
   3712             int i = 0;
   3713             for (; i < mListeners.length; i++) {
   3714                 if (mListeners[i] == listener || mListeners[i] == null) {
   3715                     break;
   3716                 }
   3717             }
   3718 
   3719             // new listener
   3720             if (i >= mListeners.length) {
   3721                 MediaTimeProvider.OnMediaTimeListener[] newListeners =
   3722                     new MediaTimeProvider.OnMediaTimeListener[i + 1];
   3723                 long[] newTimes = new long[i + 1];
   3724                 System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length);
   3725                 System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length);
   3726                 mListeners = newListeners;
   3727                 mTimes = newTimes;
   3728             }
   3729 
   3730             if (mListeners[i] == null) {
   3731                 mListeners[i] = listener;
   3732                 mTimes[i] = MediaTimeProvider.NO_TIME;
   3733             }
   3734             return i;
   3735         }
   3736 
   3737         public void notifyAt(
   3738                 long timeUs, MediaTimeProvider.OnMediaTimeListener listener) {
   3739             synchronized(this) {
   3740                 if (DEBUG) Log.d(TAG, "notifyAt " + timeUs);
   3741                 mTimes[registerListener(listener)] = timeUs;
   3742                 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
   3743             }
   3744         }
   3745 
   3746         public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) {
   3747             synchronized(this) {
   3748                 if (DEBUG) Log.d(TAG, "scheduleUpdate");
   3749                 int i = registerListener(listener);
   3750 
   3751                 if (!mStopped) {
   3752                     mTimes[i] = 0;
   3753                     scheduleNotification(NOTIFY_TIME, 0 /* delay */);
   3754                 }
   3755             }
   3756         }
   3757 
   3758         public void cancelNotifications(
   3759                 MediaTimeProvider.OnMediaTimeListener listener) {
   3760             synchronized(this) {
   3761                 int i = 0;
   3762                 for (; i < mListeners.length; i++) {
   3763                     if (mListeners[i] == listener) {
   3764                         System.arraycopy(mListeners, i + 1,
   3765                                 mListeners, i, mListeners.length - i - 1);
   3766                         System.arraycopy(mTimes, i + 1,
   3767                                 mTimes, i, mTimes.length - i - 1);
   3768                         mListeners[mListeners.length - 1] = null;
   3769                         mTimes[mTimes.length - 1] = NO_TIME;
   3770                         break;
   3771                     } else if (mListeners[i] == null) {
   3772                         break;
   3773                     }
   3774                 }
   3775 
   3776                 scheduleNotification(NOTIFY_TIME, 0 /* delay */);
   3777             }
   3778         }
   3779 
   3780         private synchronized void notifyTimedEvent(boolean refreshTime) {
   3781             // figure out next callback
   3782             long nowUs;
   3783             try {
   3784                 nowUs = getCurrentTimeUs(refreshTime, true);
   3785             } catch (IllegalStateException e) {
   3786                 // assume we paused until new player arrives
   3787                 mRefresh = true;
   3788                 mPausing = true; // this ensures that call succeeds
   3789                 nowUs = getCurrentTimeUs(refreshTime, true);
   3790             }
   3791             long nextTimeUs = nowUs;
   3792 
   3793             if (mSeeking) {
   3794                 // skip timed-event notifications until seek is complete
   3795                 return;
   3796             }
   3797 
   3798             if (DEBUG) {
   3799                 StringBuilder sb = new StringBuilder();
   3800                 sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ")
   3801                         .append(nowUs).append(") from {");
   3802                 boolean first = true;
   3803                 for (long time: mTimes) {
   3804                     if (time == NO_TIME) {
   3805                         continue;
   3806                     }
   3807                     if (!first) sb.append(", ");
   3808                     sb.append(time);
   3809                     first = false;
   3810                 }
   3811                 sb.append("}");
   3812                 Log.d(TAG, sb.toString());
   3813             }
   3814 
   3815             Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners =
   3816                 new Vector<MediaTimeProvider.OnMediaTimeListener>();
   3817             for (int ix = 0; ix < mTimes.length; ix++) {
   3818                 if (mListeners[ix] == null) {
   3819                     break;
   3820                 }
   3821                 if (mTimes[ix] <= NO_TIME) {
   3822                     // ignore, unless we were stopped
   3823                 } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) {
   3824                     activatedListeners.add(mListeners[ix]);
   3825                     if (DEBUG) Log.d(TAG, "removed");
   3826                     mTimes[ix] = NO_TIME;
   3827                 } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) {
   3828                     nextTimeUs = mTimes[ix];
   3829                 }
   3830             }
   3831 
   3832             if (nextTimeUs > nowUs && !mPaused) {
   3833                 // schedule callback at nextTimeUs
   3834                 if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs);
   3835                 scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs);
   3836             } else {
   3837                 mEventHandler.removeMessages(NOTIFY);
   3838                 // no more callbacks
   3839             }
   3840 
   3841             for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) {
   3842                 listener.onTimedEvent(nowUs);
   3843             }
   3844         }
   3845 
   3846         private long getEstimatedTime(long nanoTime, boolean monotonic) {
   3847             if (mPaused) {
   3848                 mLastReportedTime = mLastTimeUs + mTimeAdjustment;
   3849             } else {
   3850                 long timeSinceRead = (nanoTime - mLastNanoTime) / 1000;
   3851                 mLastReportedTime = mLastTimeUs + timeSinceRead;
   3852                 if (mTimeAdjustment > 0) {
   3853                     long adjustment =
   3854                         mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE;
   3855                     if (adjustment <= 0) {
   3856                         mTimeAdjustment = 0;
   3857                     } else {
   3858                         mLastReportedTime += adjustment;
   3859                     }
   3860                 }
   3861             }
   3862             return mLastReportedTime;
   3863         }
   3864 
   3865         public long getCurrentTimeUs(boolean refreshTime, boolean monotonic)
   3866                 throws IllegalStateException {
   3867             synchronized (this) {
   3868                 // we always refresh the time when the paused-state changes, because
   3869                 // we expect to have received the pause-change event delayed.
   3870                 if (mPaused && !refreshTime) {
   3871                     return mLastReportedTime;
   3872                 }
   3873 
   3874                 long nanoTime = System.nanoTime();
   3875                 if (refreshTime ||
   3876                         nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) {
   3877                     try {
   3878                         mLastTimeUs = mPlayer.getCurrentPosition() * 1000L;
   3879                         mPaused = !mPlayer.isPlaying() || mBuffering;
   3880                         if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs);
   3881                     } catch (IllegalStateException e) {
   3882                         if (mPausing) {
   3883                             // if we were pausing, get last estimated timestamp
   3884                             mPausing = false;
   3885                             getEstimatedTime(nanoTime, monotonic);
   3886                             mPaused = true;
   3887                             if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime);
   3888                             return mLastReportedTime;
   3889                         }
   3890                         // TODO get time when prepared
   3891                         throw e;
   3892                     }
   3893                     mLastNanoTime = nanoTime;
   3894                     if (monotonic && mLastTimeUs < mLastReportedTime) {
   3895                         /* have to adjust time */
   3896                         mTimeAdjustment = mLastReportedTime - mLastTimeUs;
   3897                         if (mTimeAdjustment > 1000000) {
   3898                             // schedule seeked event if time jumped significantly
   3899                             // TODO: do this properly by introducing an exception
   3900                             mStopped = false;
   3901                             mSeeking = true;
   3902                             scheduleNotification(NOTIFY_SEEK, 0 /* delay */);
   3903                         }
   3904                     } else {
   3905                         mTimeAdjustment = 0;
   3906                     }
   3907                 }
   3908 
   3909                 return getEstimatedTime(nanoTime, monotonic);
   3910             }
   3911         }
   3912 
   3913         private class EventHandler extends Handler {
   3914             public EventHandler(Looper looper) {
   3915                 super(looper);
   3916             }
   3917 
   3918             @Override
   3919             public void handleMessage(Message msg) {
   3920                 if (msg.what == NOTIFY) {
   3921                     switch (msg.arg1) {
   3922                     case NOTIFY_TIME:
   3923                         notifyTimedEvent(false /* refreshTime */);
   3924                         break;
   3925                     case REFRESH_AND_NOTIFY_TIME:
   3926                         notifyTimedEvent(true /* refreshTime */);
   3927                         break;
   3928                     case NOTIFY_STOP:
   3929                         notifyStop();
   3930                         break;
   3931                     case NOTIFY_SEEK:
   3932                         notifySeek();
   3933                         break;
   3934                     case NOTIFY_TRACK_DATA:
   3935                         notifyTrackData((Pair<SubtitleTrack, byte[]>)msg.obj);
   3936                         break;
   3937                     }
   3938                 }
   3939             }
   3940         }
   3941     }
   3942 }
   3943