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