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