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