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