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