MediaPlayer.java revision 48db7834830215a3ee00f31a442a62acf33cabfa
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.media; 18 19import android.app.ActivityThread; 20import android.app.AppOpsManager; 21import android.app.Application; 22import android.content.BroadcastReceiver; 23import android.content.ContentResolver; 24import android.content.Context; 25import android.content.Intent; 26import android.content.IntentFilter; 27import android.content.res.AssetFileDescriptor; 28import android.net.Uri; 29import android.os.Handler; 30import android.os.HandlerThread; 31import android.os.IBinder; 32import android.os.Looper; 33import android.os.Message; 34import android.os.Parcel; 35import android.os.Parcelable; 36import android.os.Process; 37import android.os.PowerManager; 38import android.os.RemoteException; 39import android.os.ServiceManager; 40import android.system.ErrnoException; 41import android.system.OsConstants; 42import android.util.Log; 43import android.view.Surface; 44import android.view.SurfaceHolder; 45import android.graphics.SurfaceTexture; 46import android.media.AudioManager; 47import android.media.MediaFormat; 48import android.media.MediaTimeProvider; 49import android.media.SubtitleController; 50import android.media.SubtitleController.Anchor; 51import android.media.SubtitleData; 52import android.media.SubtitleTrack.RenderingWidget; 53 54import com.android.internal.app.IAppOpsService; 55 56import libcore.io.IoBridge; 57import libcore.io.Libcore; 58 59import java.io.ByteArrayOutputStream; 60import java.io.File; 61import java.io.FileDescriptor; 62import java.io.FileInputStream; 63import java.io.IOException; 64import java.io.InputStream; 65import java.io.OutputStream; 66import java.lang.Runnable; 67import java.net.InetSocketAddress; 68import java.util.Map; 69import java.util.Scanner; 70import java.util.Set; 71import java.util.Vector; 72import java.lang.ref.WeakReference; 73 74/** 75 * MediaPlayer class can be used to control playback 76 * of audio/video files and streams. An example on how to use the methods in 77 * this class can be found in {@link android.widget.VideoView}. 78 * 79 * <p>Topics covered here are: 80 * <ol> 81 * <li><a href="#StateDiagram">State Diagram</a> 82 * <li><a href="#Valid_and_Invalid_States">Valid and Invalid States</a> 83 * <li><a href="#Permissions">Permissions</a> 84 * <li><a href="#Callbacks">Register informational and error callbacks</a> 85 * </ol> 86 * 87 * <div class="special reference"> 88 * <h3>Developer Guides</h3> 89 * <p>For more information about how to use MediaPlayer, read the 90 * <a href="{@docRoot}guide/topics/media/mediaplayer.html">Media Playback</a> developer guide.</p> 91 * </div> 92 * 93 * <a name="StateDiagram"></a> 94 * <h3>State Diagram</h3> 95 * 96 * <p>Playback control of audio/video files and streams is managed as a state 97 * machine. The following diagram shows the life cycle and the states of a 98 * MediaPlayer object driven by the supported playback control operations. 99 * The ovals represent the states a MediaPlayer object may reside 100 * in. The arcs represent the playback control operations that drive the object 101 * state transition. There are two types of arcs. The arcs with a single arrow 102 * head represent synchronous method calls, while those with 103 * a double arrow head represent asynchronous method calls.</p> 104 * 105 * <p><img src="../../../images/mediaplayer_state_diagram.gif" 106 * alt="MediaPlayer State diagram" 107 * border="0" /></p> 108 * 109 * <p>From this state diagram, one can see that a MediaPlayer object has the 110 * following states:</p> 111 * <ul> 112 * <li>When a MediaPlayer object is just created using <code>new</code> or 113 * after {@link #reset()} is called, it is in the <em>Idle</em> state; and after 114 * {@link #release()} is called, it is in the <em>End</em> state. Between these 115 * two states is the life cycle of the MediaPlayer object. 116 * <ul> 117 * <li>There is a subtle but important difference between a newly constructed 118 * MediaPlayer object and the MediaPlayer object after {@link #reset()} 119 * is called. It is a programming error to invoke methods such 120 * as {@link #getCurrentPosition()}, 121 * {@link #getDuration()}, {@link #getVideoHeight()}, 122 * {@link #getVideoWidth()}, {@link #setAudioStreamType(int)}, 123 * {@link #setLooping(boolean)}, 124 * {@link #setVolume(float, float)}, {@link #pause()}, {@link #start()}, 125 * {@link #stop()}, {@link #seekTo(int)}, {@link #prepare()} or 126 * {@link #prepareAsync()} in the <em>Idle</em> state for both cases. If any of these 127 * methods is called right after a MediaPlayer object is constructed, 128 * the user supplied callback method OnErrorListener.onError() won't be 129 * called by the internal player engine and the object state remains 130 * unchanged; but if these methods are called right after {@link #reset()}, 131 * the user supplied callback method OnErrorListener.onError() will be 132 * invoked by the internal player engine and the object will be 133 * transfered to the <em>Error</em> state. </li> 134 * <li>It is also recommended that once 135 * a MediaPlayer object is no longer being used, call {@link #release()} immediately 136 * so that resources used by the internal player engine associated with the 137 * MediaPlayer object can be released immediately. Resource may include 138 * singleton resources such as hardware acceleration components and 139 * failure to call {@link #release()} may cause subsequent instances of 140 * MediaPlayer objects to fallback to software implementations or fail 141 * altogether. Once the MediaPlayer 142 * object is in the <em>End</em> state, it can no longer be used and 143 * there is no way to bring it back to any other state. </li> 144 * <li>Furthermore, 145 * the MediaPlayer objects created using <code>new</code> is in the 146 * <em>Idle</em> state, while those created with one 147 * of the overloaded convenient <code>create</code> methods are <em>NOT</em> 148 * in the <em>Idle</em> state. In fact, the objects are in the <em>Prepared</em> 149 * state if the creation using <code>create</code> method is successful. 150 * </li> 151 * </ul> 152 * </li> 153 * <li>In general, some playback control operation may fail due to various 154 * reasons, such as unsupported audio/video format, poorly interleaved 155 * audio/video, resolution too high, streaming timeout, and the like. 156 * Thus, error reporting and recovery is an important concern under 157 * these circumstances. Sometimes, due to programming errors, invoking a playback 158 * control operation in an invalid state may also occur. Under all these 159 * error conditions, the internal player engine invokes a user supplied 160 * OnErrorListener.onError() method if an OnErrorListener has been 161 * registered beforehand via 162 * {@link #setOnErrorListener(android.media.MediaPlayer.OnErrorListener)}. 163 * <ul> 164 * <li>It is important to note that once an error occurs, the 165 * MediaPlayer object enters the <em>Error</em> state (except as noted 166 * above), even if an error listener has not been registered by the application.</li> 167 * <li>In order to reuse a MediaPlayer object that is in the <em> 168 * Error</em> state and recover from the error, 169 * {@link #reset()} can be called to restore the object to its <em>Idle</em> 170 * state.</li> 171 * <li>It is good programming practice to have your application 172 * register a OnErrorListener to look out for error notifications from 173 * the internal player engine.</li> 174 * <li>IllegalStateException is 175 * thrown to prevent programming errors such as calling {@link #prepare()}, 176 * {@link #prepareAsync()}, or one of the overloaded <code>setDataSource 177 * </code> methods in an invalid state. </li> 178 * </ul> 179 * </li> 180 * <li>Calling 181 * {@link #setDataSource(FileDescriptor)}, or 182 * {@link #setDataSource(String)}, or 183 * {@link #setDataSource(Context, Uri)}, or 184 * {@link #setDataSource(FileDescriptor, long, long)} transfers a 185 * MediaPlayer object in the <em>Idle</em> state to the 186 * <em>Initialized</em> state. 187 * <ul> 188 * <li>An IllegalStateException is thrown if 189 * setDataSource() is called in any other state.</li> 190 * <li>It is good programming 191 * practice to always look out for <code>IllegalArgumentException</code> 192 * and <code>IOException</code> that may be thrown from the overloaded 193 * <code>setDataSource</code> methods.</li> 194 * </ul> 195 * </li> 196 * <li>A MediaPlayer object must first enter the <em>Prepared</em> state 197 * before playback can be started. 198 * <ul> 199 * <li>There are two ways (synchronous vs. 200 * asynchronous) that the <em>Prepared</em> state can be reached: 201 * either a call to {@link #prepare()} (synchronous) which 202 * transfers the object to the <em>Prepared</em> state once the method call 203 * returns, or a call to {@link #prepareAsync()} (asynchronous) which 204 * first transfers the object to the <em>Preparing</em> state after the 205 * call returns (which occurs almost right way) while the internal 206 * player engine continues working on the rest of preparation work 207 * until the preparation work completes. When the preparation completes or when {@link #prepare()} call returns, 208 * the internal player engine then calls a user supplied callback method, 209 * onPrepared() of the OnPreparedListener interface, if an 210 * OnPreparedListener is registered beforehand via {@link 211 * #setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener)}.</li> 212 * <li>It is important to note that 213 * the <em>Preparing</em> state is a transient state, and the behavior 214 * of calling any method with side effect while a MediaPlayer object is 215 * in the <em>Preparing</em> state is undefined.</li> 216 * <li>An IllegalStateException is 217 * thrown if {@link #prepare()} or {@link #prepareAsync()} is called in 218 * any other state.</li> 219 * <li>While in the <em>Prepared</em> state, properties 220 * such as audio/sound volume, screenOnWhilePlaying, looping can be 221 * adjusted by invoking the corresponding set methods.</li> 222 * </ul> 223 * </li> 224 * <li>To start the playback, {@link #start()} must be called. After 225 * {@link #start()} returns successfully, the MediaPlayer object is in the 226 * <em>Started</em> state. {@link #isPlaying()} can be called to test 227 * whether the MediaPlayer object is in the <em>Started</em> state. 228 * <ul> 229 * <li>While in the <em>Started</em> state, the internal player engine calls 230 * a user supplied OnBufferingUpdateListener.onBufferingUpdate() callback 231 * method if a OnBufferingUpdateListener has been registered beforehand 232 * via {@link #setOnBufferingUpdateListener(OnBufferingUpdateListener)}. 233 * This callback allows applications to keep track of the buffering status 234 * while streaming audio/video.</li> 235 * <li>Calling {@link #start()} has not effect 236 * on a MediaPlayer object that is already in the <em>Started</em> state.</li> 237 * </ul> 238 * </li> 239 * <li>Playback can be paused and stopped, and the current playback position 240 * can be adjusted. Playback can be paused via {@link #pause()}. When the call to 241 * {@link #pause()} returns, the MediaPlayer object enters the 242 * <em>Paused</em> state. Note that the transition from the <em>Started</em> 243 * state to the <em>Paused</em> state and vice versa happens 244 * asynchronously in the player engine. It may take some time before 245 * the state is updated in calls to {@link #isPlaying()}, and it can be 246 * a number of seconds in the case of streamed content. 247 * <ul> 248 * <li>Calling {@link #start()} to resume playback for a paused 249 * MediaPlayer object, and the resumed playback 250 * position is the same as where it was paused. When the call to 251 * {@link #start()} returns, the paused MediaPlayer object goes back to 252 * the <em>Started</em> state.</li> 253 * <li>Calling {@link #pause()} has no effect on 254 * a MediaPlayer object that is already in the <em>Paused</em> state.</li> 255 * </ul> 256 * </li> 257 * <li>Calling {@link #stop()} stops playback and causes a 258 * MediaPlayer in the <em>Started</em>, <em>Paused</em>, <em>Prepared 259 * </em> or <em>PlaybackCompleted</em> state to enter the 260 * <em>Stopped</em> state. 261 * <ul> 262 * <li>Once in the <em>Stopped</em> state, playback cannot be started 263 * until {@link #prepare()} or {@link #prepareAsync()} are called to set 264 * the MediaPlayer object to the <em>Prepared</em> state again.</li> 265 * <li>Calling {@link #stop()} has no effect on a MediaPlayer 266 * object that is already in the <em>Stopped</em> state.</li> 267 * </ul> 268 * </li> 269 * <li>The playback position can be adjusted with a call to 270 * {@link #seekTo(int)}. 271 * <ul> 272 * <li>Although the asynchronuous {@link #seekTo(int)} 273 * call returns right way, the actual seek operation may take a while to 274 * finish, especially for audio/video being streamed. When the actual 275 * seek operation completes, the internal player engine calls a user 276 * supplied OnSeekComplete.onSeekComplete() if an OnSeekCompleteListener 277 * has been registered beforehand via 278 * {@link #setOnSeekCompleteListener(OnSeekCompleteListener)}.</li> 279 * <li>Please 280 * note that {@link #seekTo(int)} can also be called in the other states, 281 * such as <em>Prepared</em>, <em>Paused</em> and <em>PlaybackCompleted 282 * </em> state.</li> 283 * <li>Furthermore, the actual current playback position 284 * can be retrieved with a call to {@link #getCurrentPosition()}, which 285 * is helpful for applications such as a Music player that need to keep 286 * track of the playback progress.</li> 287 * </ul> 288 * </li> 289 * <li>When the playback reaches the end of stream, the playback completes. 290 * <ul> 291 * <li>If the looping mode was being set to <var>true</var>with 292 * {@link #setLooping(boolean)}, the MediaPlayer object shall remain in 293 * the <em>Started</em> state.</li> 294 * <li>If the looping mode was set to <var>false 295 * </var>, the player engine calls a user supplied callback method, 296 * OnCompletion.onCompletion(), if a OnCompletionListener is registered 297 * beforehand via {@link #setOnCompletionListener(OnCompletionListener)}. 298 * The invoke of the callback signals that the object is now in the <em> 299 * PlaybackCompleted</em> state.</li> 300 * <li>While in the <em>PlaybackCompleted</em> 301 * state, calling {@link #start()} can restart the playback from the 302 * beginning of the audio/video source.</li> 303 * </ul> 304 * 305 * 306 * <a name="Valid_and_Invalid_States"></a> 307 * <h3>Valid and invalid states</h3> 308 * 309 * <table border="0" cellspacing="0" cellpadding="0"> 310 * <tr><td>Method Name </p></td> 311 * <td>Valid Sates </p></td> 312 * <td>Invalid States </p></td> 313 * <td>Comments </p></td></tr> 314 * <tr><td>attachAuxEffect </p></td> 315 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td> 316 * <td>{Idle, Error} </p></td> 317 * <td>This method must be called after setDataSource. 318 * Calling it does not change the object state. </p></td></tr> 319 * <tr><td>getAudioSessionId </p></td> 320 * <td>any </p></td> 321 * <td>{} </p></td> 322 * <td>This method can be called in any state and calling it does not change 323 * the object state. </p></td></tr> 324 * <tr><td>getCurrentPosition </p></td> 325 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 326 * PlaybackCompleted} </p></td> 327 * <td>{Error}</p></td> 328 * <td>Successful invoke of this method in a valid state does not change the 329 * state. Calling this method in an invalid state transfers the object 330 * to the <em>Error</em> state. </p></td></tr> 331 * <tr><td>getDuration </p></td> 332 * <td>{Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td> 333 * <td>{Idle, Initialized, Error} </p></td> 334 * <td>Successful invoke of this method in a valid state does not change the 335 * state. Calling this method in an invalid state transfers the object 336 * to the <em>Error</em> state. </p></td></tr> 337 * <tr><td>getVideoHeight </p></td> 338 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 339 * PlaybackCompleted}</p></td> 340 * <td>{Error}</p></td> 341 * <td>Successful invoke of this method in a valid state does not change the 342 * state. Calling this method in an invalid state transfers the object 343 * to the <em>Error</em> state. </p></td></tr> 344 * <tr><td>getVideoWidth </p></td> 345 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 346 * PlaybackCompleted}</p></td> 347 * <td>{Error}</p></td> 348 * <td>Successful invoke of this method in a valid state does not change 349 * the state. Calling this method in an invalid state transfers the 350 * object to the <em>Error</em> state. </p></td></tr> 351 * <tr><td>isPlaying </p></td> 352 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 353 * PlaybackCompleted}</p></td> 354 * <td>{Error}</p></td> 355 * <td>Successful invoke of this method in a valid state does not change 356 * the state. Calling this method in an invalid state transfers the 357 * object to the <em>Error</em> state. </p></td></tr> 358 * <tr><td>pause </p></td> 359 * <td>{Started, Paused, PlaybackCompleted}</p></td> 360 * <td>{Idle, Initialized, Prepared, Stopped, Error}</p></td> 361 * <td>Successful invoke of this method in a valid state transfers the 362 * object to the <em>Paused</em> state. Calling this method in an 363 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr> 364 * <tr><td>prepare </p></td> 365 * <td>{Initialized, Stopped} </p></td> 366 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td> 367 * <td>Successful invoke of this method in a valid state transfers the 368 * object to the <em>Prepared</em> state. Calling this method in an 369 * invalid state throws an IllegalStateException.</p></td></tr> 370 * <tr><td>prepareAsync </p></td> 371 * <td>{Initialized, Stopped} </p></td> 372 * <td>{Idle, Prepared, Started, Paused, PlaybackCompleted, Error} </p></td> 373 * <td>Successful invoke of this method in a valid state transfers the 374 * object to the <em>Preparing</em> state. Calling this method in an 375 * invalid state throws an IllegalStateException.</p></td></tr> 376 * <tr><td>release </p></td> 377 * <td>any </p></td> 378 * <td>{} </p></td> 379 * <td>After {@link #release()}, the object is no longer available. </p></td></tr> 380 * <tr><td>reset </p></td> 381 * <td>{Idle, Initialized, Prepared, Started, Paused, Stopped, 382 * PlaybackCompleted, Error}</p></td> 383 * <td>{}</p></td> 384 * <td>After {@link #reset()}, the object is like being just created.</p></td></tr> 385 * <tr><td>seekTo </p></td> 386 * <td>{Prepared, Started, Paused, PlaybackCompleted} </p></td> 387 * <td>{Idle, Initialized, Stopped, Error}</p></td> 388 * <td>Successful invoke of this method in a valid state does not change 389 * the state. Calling this method in an invalid state transfers the 390 * object to the <em>Error</em> state. </p></td></tr> 391 * <tr><td>setAudioAttributes </p></td> 392 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused, 393 * PlaybackCompleted}</p></td> 394 * <td>{Error}</p></td> 395 * <td>Successful invoke of this method does not change the state. In order for the 396 * target audio attributes type to become effective, this method must be called before 397 * prepare() or prepareAsync().</p></td></tr> 398 * <tr><td>setAudioSessionId </p></td> 399 * <td>{Idle} </p></td> 400 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, 401 * Error} </p></td> 402 * <td>This method must be called in idle state as the audio session ID must be known before 403 * calling setDataSource. Calling it does not change the object state. </p></td></tr> 404 * <tr><td>setAudioStreamType </p></td> 405 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused, 406 * PlaybackCompleted}</p></td> 407 * <td>{Error}</p></td> 408 * <td>Successful invoke of this method does not change the state. In order for the 409 * target audio stream type to become effective, this method must be called before 410 * prepare() or prepareAsync().</p></td></tr> 411 * <tr><td>setAuxEffectSendLevel </p></td> 412 * <td>any</p></td> 413 * <td>{} </p></td> 414 * <td>Calling this method does not change the object state. </p></td></tr> 415 * <tr><td>setDataSource </p></td> 416 * <td>{Idle} </p></td> 417 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted, 418 * Error} </p></td> 419 * <td>Successful invoke of this method in a valid state transfers the 420 * object to the <em>Initialized</em> state. Calling this method in an 421 * invalid state throws an IllegalStateException.</p></td></tr> 422 * <tr><td>setDisplay </p></td> 423 * <td>any </p></td> 424 * <td>{} </p></td> 425 * <td>This method can be called in any state and calling it does not change 426 * the object state. </p></td></tr> 427 * <tr><td>setSurface </p></td> 428 * <td>any </p></td> 429 * <td>{} </p></td> 430 * <td>This method can be called in any state and calling it does not change 431 * the object state. </p></td></tr> 432 * <tr><td>setVideoScalingMode </p></td> 433 * <td>{Initialized, Prepared, Started, Paused, Stopped, PlaybackCompleted} </p></td> 434 * <td>{Idle, Error}</p></td> 435 * <td>Successful invoke of this method does not change the state.</p></td></tr> 436 * <tr><td>setLooping </p></td> 437 * <td>{Idle, Initialized, Stopped, Prepared, Started, Paused, 438 * PlaybackCompleted}</p></td> 439 * <td>{Error}</p></td> 440 * <td>Successful invoke of this method in a valid state does not change 441 * the state. Calling this method in an 442 * invalid state transfers the object to the <em>Error</em> state.</p></td></tr> 443 * <tr><td>isLooping </p></td> 444 * <td>any </p></td> 445 * <td>{} </p></td> 446 * <td>This method can be called in any state and calling it does not change 447 * the object state. </p></td></tr> 448 * <tr><td>setOnBufferingUpdateListener </p></td> 449 * <td>any </p></td> 450 * <td>{} </p></td> 451 * <td>This method can be called in any state and calling it does not change 452 * the object state. </p></td></tr> 453 * <tr><td>setOnCompletionListener </p></td> 454 * <td>any </p></td> 455 * <td>{} </p></td> 456 * <td>This method can be called in any state and calling it does not change 457 * the object state. </p></td></tr> 458 * <tr><td>setOnErrorListener </p></td> 459 * <td>any </p></td> 460 * <td>{} </p></td> 461 * <td>This method can be called in any state and calling it does not change 462 * the object state. </p></td></tr> 463 * <tr><td>setOnPreparedListener </p></td> 464 * <td>any </p></td> 465 * <td>{} </p></td> 466 * <td>This method can be called in any state and calling it does not change 467 * the object state. </p></td></tr> 468 * <tr><td>setOnSeekCompleteListener </p></td> 469 * <td>any </p></td> 470 * <td>{} </p></td> 471 * <td>This method can be called in any state and calling it does not change 472 * the object state. </p></td></tr> 473 * <tr><td>setScreenOnWhilePlaying</></td> 474 * <td>any </p></td> 475 * <td>{} </p></td> 476 * <td>This method can be called in any state and calling it does not change 477 * the object state. </p></td></tr> 478 * <tr><td>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 */ 548public 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"); 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 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 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 */ 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 */ 1107 public void setDataSource(FileDescriptor fd, long offset, long length) 1108 throws IOException, IllegalArgumentException, IllegalStateException { 1109 _setDataSource(fd, offset, length); 1110 } 1111 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 */ 1124 public void prepare() throws IOException, IllegalStateException { 1125 _prepare(); 1126 scanInternalSubtitleTracks(); 1127 } 1128 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 */ 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 */ 1151 public void start() throws IllegalStateException { 1152 if (isRestricted()) { 1153 _setVolume(0, 0); 1154 } 1155 stayAwake(true); 1156 _start(); 1157 } 1158 1159 private native void _start() throws IllegalStateException; 1160 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 1173 private int getAudioStreamType() { 1174 if (mStreamType == AudioManager.USE_DEFAULT_STREAM_TYPE) { 1175 mStreamType = _getAudioStreamType(); 1176 } 1177 return mStreamType; 1178 } 1179 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 */ 1188 public void stop() throws IllegalStateException { 1189 stayAwake(false); 1190 _stop(); 1191 } 1192 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 */ 1201 public void pause() throws IllegalStateException { 1202 stayAwake(false); 1203 _pause(); 1204 } 1205 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 */ 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 */ 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 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 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 */ 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 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 */ 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 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 */ 1522 public void setAudioStreamType(int streamtype) { 1523 _setAudioStreamType(streamtype); 1524 mStreamType = streamtype; 1525 } 1526 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 */ 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 */ 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 */ 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 */ 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 */ 1590 public void setVolume(float leftVolume, float rightVolume) { 1591 if (isRestricted()) { 1592 return; 1593 } 1594 _setVolume(leftVolume, rightVolume); 1595 } 1596 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 */ 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 */ 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 */ 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 */ 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 */ 1662 public void setAuxEffectSendLevel(float level) { 1663 if (isRestricted()) { 1664 return; 1665 } 1666 _setAuxEffectSendLevel(level); 1667 } 1668 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 */ 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 */ 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 */ 1705 private native final int native_setMetadataFilter(Parcel request); 1706 1707 private static native final void native_init(); 1708 private native final void native_setup(Object mediaplayer_this); 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 */ 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 */ 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 */ 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 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 */ 1778 TrackInfo(int type, MediaFormat format) { 1779 mTrackType = type; 1780 mFormat = format; 1781 } 1782 1783 /** 1784 * {@inheritDoc} 1785 */ 1786 @Override 1787 public int describeContents() { 1788 return 0; 1789 } 1790 1791 /** 1792 * {@inheritDoc} 1793 */ 1794 @Override 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 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 */ 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 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 */ 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 */ 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 SubtitleTrack[] mInbandSubtitleTracks; 1933 private int mSelectedSubtitleTrackIndex = -1; 1934 private Vector<SubtitleTrack> mOutOfBandSubtitleTracks; 1935 private Vector<InputStream> mOpenSubtitleSources; 1936 1937 private OnSubtitleDataListener mSubtitleDataListener = new OnSubtitleDataListener() { 1938 @Override 1939 public void onSubtitleData(MediaPlayer mp, SubtitleData data) { 1940 int index = data.getTrackIndex(); 1941 if (index >= mInbandSubtitleTracks.length) { 1942 return; 1943 } 1944 SubtitleTrack track = mInbandSubtitleTracks[index]; 1945 if (track != null) { 1946 track.onData(data); 1947 } 1948 } 1949 }; 1950 1951 /** @hide */ 1952 @Override 1953 public void onSubtitleTrackSelected(SubtitleTrack track) { 1954 if (mSelectedSubtitleTrackIndex >= 0) { 1955 try { 1956 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, false); 1957 } catch (IllegalStateException e) { 1958 } 1959 mSelectedSubtitleTrackIndex = -1; 1960 } 1961 setOnSubtitleDataListener(null); 1962 if (track == null) { 1963 return; 1964 } 1965 for (int i = 0; i < mInbandSubtitleTracks.length; i++) { 1966 if (mInbandSubtitleTracks[i] == track) { 1967 Log.v(TAG, "Selecting subtitle track " + i); 1968 mSelectedSubtitleTrackIndex = i; 1969 try { 1970 selectOrDeselectInbandTrack(mSelectedSubtitleTrackIndex, true); 1971 } catch (IllegalStateException e) { 1972 } 1973 setOnSubtitleDataListener(mSubtitleDataListener); 1974 break; 1975 } 1976 } 1977 // no need to select out-of-band tracks 1978 } 1979 1980 /** @hide */ 1981 public void addSubtitleSource(InputStream is, MediaFormat format) 1982 throws IllegalStateException 1983 { 1984 final InputStream fIs = is; 1985 final MediaFormat fFormat = format; 1986 1987 // Ensure all input streams are closed. It is also a handy 1988 // way to implement timeouts in the future. 1989 synchronized(mOpenSubtitleSources) { 1990 mOpenSubtitleSources.add(is); 1991 } 1992 1993 // process each subtitle in its own thread 1994 final HandlerThread thread = new HandlerThread("SubtitleReadThread", 1995 Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE); 1996 thread.start(); 1997 Handler handler = new Handler(thread.getLooper()); 1998 handler.post(new Runnable() { 1999 private int addTrack() { 2000 if (fIs == null || mSubtitleController == null) { 2001 return MEDIA_INFO_UNSUPPORTED_SUBTITLE; 2002 } 2003 2004 SubtitleTrack track = mSubtitleController.addTrack(fFormat); 2005 if (track == null) { 2006 return MEDIA_INFO_UNSUPPORTED_SUBTITLE; 2007 } 2008 2009 // TODO: do the conversion in the subtitle track 2010 Scanner scanner = new Scanner(fIs, "UTF-8"); 2011 String contents = scanner.useDelimiter("\\A").next(); 2012 synchronized(mOpenSubtitleSources) { 2013 mOpenSubtitleSources.remove(fIs); 2014 } 2015 scanner.close(); 2016 mOutOfBandSubtitleTracks.add(track); 2017 track.onData(contents.getBytes(), true /* eos */, ~0 /* runID: keep forever */); 2018 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE; 2019 } 2020 2021 public void run() { 2022 int res = addTrack(); 2023 if (mEventHandler != null) { 2024 Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null); 2025 mEventHandler.sendMessage(m); 2026 } 2027 thread.getLooper().quitSafely(); 2028 } 2029 }); 2030 } 2031 2032 private void scanInternalSubtitleTracks() { 2033 if (mSubtitleController == null) { 2034 Log.e(TAG, "Should have subtitle controller already set"); 2035 return; 2036 } 2037 2038 TrackInfo[] tracks = getInbandTrackInfo(); 2039 SubtitleTrack[] inbandTracks = new SubtitleTrack[tracks.length]; 2040 for (int i=0; i < tracks.length; i++) { 2041 if (tracks[i].getTrackType() == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE) { 2042 if (i < mInbandSubtitleTracks.length) { 2043 inbandTracks[i] = mInbandSubtitleTracks[i]; 2044 } else { 2045 SubtitleTrack track = mSubtitleController.addTrack( 2046 tracks[i].getFormat()); 2047 inbandTracks[i] = track; 2048 } 2049 } 2050 } 2051 mInbandSubtitleTracks = inbandTracks; 2052 mSubtitleController.selectDefaultTrack(); 2053 } 2054 2055 /* TODO: Limit the total number of external timed text source to a reasonable number. 2056 */ 2057 /** 2058 * Adds an external timed text source file. 2059 * 2060 * Currently supported format is SubRip with the file extension .srt, case insensitive. 2061 * Note that a single external timed text source may contain multiple tracks in it. 2062 * One can find the total number of available tracks using {@link #getTrackInfo()} to see what 2063 * additional tracks become available after this method call. 2064 * 2065 * @param path The file path of external timed text source file. 2066 * @param mimeType The mime type of the file. Must be one of the mime types listed above. 2067 * @throws IOException if the file cannot be accessed or is corrupted. 2068 * @throws IllegalArgumentException if the mimeType is not supported. 2069 * @throws IllegalStateException if called in an invalid state. 2070 */ 2071 public void addTimedTextSource(String path, String mimeType) 2072 throws IOException, IllegalArgumentException, IllegalStateException { 2073 if (!availableMimeTypeForExternalSource(mimeType)) { 2074 final String msg = "Illegal mimeType for timed text source: " + mimeType; 2075 throw new IllegalArgumentException(msg); 2076 } 2077 2078 File file = new File(path); 2079 if (file.exists()) { 2080 FileInputStream is = new FileInputStream(file); 2081 FileDescriptor fd = is.getFD(); 2082 addTimedTextSource(fd, mimeType); 2083 is.close(); 2084 } else { 2085 // We do not support the case where the path is not a file. 2086 throw new IOException(path); 2087 } 2088 } 2089 2090 /** 2091 * Adds an external timed text source file (Uri). 2092 * 2093 * Currently supported format is SubRip with the file extension .srt, case insensitive. 2094 * Note that a single external timed text source may contain multiple tracks in it. 2095 * One can find the total number of available tracks using {@link #getTrackInfo()} to see what 2096 * additional tracks become available after this method call. 2097 * 2098 * @param context the Context to use when resolving the Uri 2099 * @param uri the Content URI of the data you want to play 2100 * @param mimeType The mime type of the file. Must be one of the mime types listed above. 2101 * @throws IOException if the file cannot be accessed or is corrupted. 2102 * @throws IllegalArgumentException if the mimeType is not supported. 2103 * @throws IllegalStateException if called in an invalid state. 2104 */ 2105 public void addTimedTextSource(Context context, Uri uri, String mimeType) 2106 throws IOException, IllegalArgumentException, IllegalStateException { 2107 String scheme = uri.getScheme(); 2108 if(scheme == null || scheme.equals("file")) { 2109 addTimedTextSource(uri.getPath(), mimeType); 2110 return; 2111 } 2112 2113 AssetFileDescriptor fd = null; 2114 try { 2115 ContentResolver resolver = context.getContentResolver(); 2116 fd = resolver.openAssetFileDescriptor(uri, "r"); 2117 if (fd == null) { 2118 return; 2119 } 2120 addTimedTextSource(fd.getFileDescriptor(), mimeType); 2121 return; 2122 } catch (SecurityException ex) { 2123 } catch (IOException ex) { 2124 } finally { 2125 if (fd != null) { 2126 fd.close(); 2127 } 2128 } 2129 } 2130 2131 /** 2132 * Adds an external timed text source file (FileDescriptor). 2133 * 2134 * It is the caller's responsibility to close the file descriptor. 2135 * It is safe to do so as soon as this call returns. 2136 * 2137 * Currently supported format is SubRip. Note that a single external timed text source may 2138 * contain multiple tracks in it. One can find the total number of available tracks 2139 * using {@link #getTrackInfo()} to see what additional tracks become available 2140 * after this method call. 2141 * 2142 * @param fd the FileDescriptor for the file you want to play 2143 * @param mimeType The mime type of the file. Must be one of the mime types listed above. 2144 * @throws IllegalArgumentException if the mimeType is not supported. 2145 * @throws IllegalStateException if called in an invalid state. 2146 */ 2147 public void addTimedTextSource(FileDescriptor fd, String mimeType) 2148 throws IllegalArgumentException, IllegalStateException { 2149 // intentionally less than LONG_MAX 2150 addTimedTextSource(fd, 0, 0x7ffffffffffffffL, mimeType); 2151 } 2152 2153 /** 2154 * Adds an external timed text file (FileDescriptor). 2155 * 2156 * It is the caller's responsibility to close the file descriptor. 2157 * It is safe to do so as soon as this call returns. 2158 * 2159 * Currently supported format is SubRip. Note that a single external timed text source may 2160 * contain multiple tracks in it. One can find the total number of available tracks 2161 * using {@link #getTrackInfo()} to see what additional tracks become available 2162 * after this method call. 2163 * 2164 * @param fd the FileDescriptor for the file you want to play 2165 * @param offset the offset into the file where the data to be played starts, in bytes 2166 * @param length the length in bytes of the data to be played 2167 * @param mime The mime type of the file. Must be one of the mime types listed above. 2168 * @throws IllegalArgumentException if the mimeType is not supported. 2169 * @throws IllegalStateException if called in an invalid state. 2170 */ 2171 public void addTimedTextSource(FileDescriptor fd, long offset, long length, String mime) 2172 throws IllegalArgumentException, IllegalStateException { 2173 if (!availableMimeTypeForExternalSource(mime)) { 2174 throw new IllegalArgumentException("Illegal mimeType for timed text source: " + mime); 2175 } 2176 2177 FileDescriptor fd2; 2178 try { 2179 fd2 = Libcore.os.dup(fd); 2180 } catch (ErrnoException ex) { 2181 Log.e(TAG, ex.getMessage(), ex); 2182 throw new RuntimeException(ex); 2183 } 2184 2185 final MediaFormat fFormat = new MediaFormat(); 2186 fFormat.setString(MediaFormat.KEY_MIME, mime); 2187 fFormat.setInteger(MediaFormat.KEY_IS_TIMED_TEXT, 1); 2188 2189 Context context = ActivityThread.currentApplication(); 2190 // A MediaPlayer created by a VideoView should already have its mSubtitleController set. 2191 if (mSubtitleController == null) { 2192 mSubtitleController = new SubtitleController(context, mTimeProvider, this); 2193 mSubtitleController.setAnchor(new Anchor() { 2194 @Override 2195 public void setSubtitleWidget(RenderingWidget subtitleWidget) { 2196 } 2197 2198 @Override 2199 public Looper getSubtitleLooper() { 2200 return Looper.getMainLooper(); 2201 } 2202 }); 2203 } 2204 2205 if (!mSubtitleController.hasRendererFor(fFormat)) { 2206 // test and add not atomic 2207 mSubtitleController.registerRenderer(new SRTRenderer(context, mEventHandler)); 2208 } 2209 final SubtitleTrack track = mSubtitleController.addTrack(fFormat); 2210 mOutOfBandSubtitleTracks.add(track); 2211 2212 final FileDescriptor fd3 = fd2; 2213 final long offset2 = offset; 2214 final long length2 = length; 2215 final HandlerThread thread = new HandlerThread( 2216 "TimedTextReadThread", 2217 Process.THREAD_PRIORITY_BACKGROUND + Process.THREAD_PRIORITY_MORE_FAVORABLE); 2218 thread.start(); 2219 Handler handler = new Handler(thread.getLooper()); 2220 handler.post(new Runnable() { 2221 private int addTrack() { 2222 InputStream is = null; 2223 final ByteArrayOutputStream bos = new ByteArrayOutputStream(); 2224 try { 2225 Libcore.os.lseek(fd3, offset2, OsConstants.SEEK_SET); 2226 byte[] buffer = new byte[4096]; 2227 for (int total = 0; total < length2;) { 2228 int remain = (int)length2 - total; 2229 int bytes = IoBridge.read(fd3, buffer, 0, Math.min(buffer.length, remain)); 2230 if (bytes < 0) { 2231 break; 2232 } else { 2233 bos.write(buffer, 0, bytes); 2234 total += bytes; 2235 } 2236 } 2237 track.onData(bos.toByteArray(), true /* eos */, ~0 /* runID: keep forever */); 2238 return MEDIA_INFO_EXTERNAL_METADATA_UPDATE; 2239 } catch (Exception e) { 2240 Log.e(TAG, e.getMessage(), e); 2241 return MEDIA_INFO_TIMED_TEXT_ERROR; 2242 } finally { 2243 if (is != null) { 2244 try { 2245 is.close(); 2246 } catch (IOException e) { 2247 Log.e(TAG, e.getMessage(), e); 2248 } 2249 } 2250 } 2251 } 2252 2253 public void run() { 2254 int res = addTrack(); 2255 if (mEventHandler != null) { 2256 Message m = mEventHandler.obtainMessage(MEDIA_INFO, res, 0, null); 2257 mEventHandler.sendMessage(m); 2258 } 2259 thread.getLooper().quitSafely(); 2260 } 2261 }); 2262 } 2263 2264 /** 2265 * Returns the index of the audio, video, or subtitle track currently selected for playback, 2266 * The return value is an index into the array returned by {@link #getTrackInfo()}, and can 2267 * be used in calls to {@link #selectTrack(int)} or {@link #deselectTrack(int)}. 2268 * 2269 * @param trackType should be one of {@link TrackInfo#MEDIA_TRACK_TYPE_VIDEO}, 2270 * {@link TrackInfo#MEDIA_TRACK_TYPE_AUDIO}, or 2271 * {@link TrackInfo#MEDIA_TRACK_TYPE_SUBTITLE} 2272 * @return index of the audio, video, or subtitle track currently selected for playback; 2273 * a negative integer is returned when there is no selected track for {@code trackType} or 2274 * when {@code trackType} is not one of audio, video, or subtitle. 2275 * @throws IllegalStateException if called after {@link #release()} 2276 * 2277 * @see {@link #getTrackInfo()} 2278 * @see {@link #selectTrack(int)} 2279 * @see {@link #deselectTrack(int)} 2280 */ 2281 public int getSelectedTrack(int trackType) throws IllegalStateException { 2282 if (trackType == TrackInfo.MEDIA_TRACK_TYPE_SUBTITLE && mSubtitleController != null) { 2283 SubtitleTrack subtitleTrack = mSubtitleController.getSelectedTrack(); 2284 if (subtitleTrack != null) { 2285 int index = mOutOfBandSubtitleTracks.indexOf(subtitleTrack); 2286 if (index >= 0) { 2287 return mInbandSubtitleTracks.length + index; 2288 } 2289 } 2290 } 2291 2292 Parcel request = Parcel.obtain(); 2293 Parcel reply = Parcel.obtain(); 2294 try { 2295 request.writeInterfaceToken(IMEDIA_PLAYER); 2296 request.writeInt(INVOKE_ID_GET_SELECTED_TRACK); 2297 request.writeInt(trackType); 2298 invoke(request, reply); 2299 int selectedTrack = reply.readInt(); 2300 return selectedTrack; 2301 } finally { 2302 request.recycle(); 2303 reply.recycle(); 2304 } 2305 } 2306 2307 /** 2308 * Selects a track. 2309 * <p> 2310 * If a MediaPlayer is in invalid state, it throws an IllegalStateException exception. 2311 * If a MediaPlayer is in <em>Started</em> state, the selected track is presented immediately. 2312 * If a MediaPlayer is not in Started state, it just marks the track to be played. 2313 * </p> 2314 * <p> 2315 * In any valid state, if it is called multiple times on the same type of track (ie. Video, 2316 * Audio, Timed Text), the most recent one will be chosen. 2317 * </p> 2318 * <p> 2319 * The first audio and video tracks are selected by default if available, even though 2320 * this method is not called. However, no timed text track will be selected until 2321 * this function is called. 2322 * </p> 2323 * <p> 2324 * Currently, only timed text tracks or audio tracks can be selected via this method. 2325 * In addition, the support for selecting an audio track at runtime is pretty limited 2326 * in that an audio track can only be selected in the <em>Prepared</em> state. 2327 * </p> 2328 * @param index the index of the track to be selected. The valid range of the index 2329 * is 0..total number of track - 1. The total number of tracks as well as the type of 2330 * each individual track can be found by calling {@link #getTrackInfo()} method. 2331 * @throws IllegalStateException if called in an invalid state. 2332 * 2333 * @see android.media.MediaPlayer#getTrackInfo 2334 */ 2335 public void selectTrack(int index) throws IllegalStateException { 2336 selectOrDeselectTrack(index, true /* select */); 2337 } 2338 2339 /** 2340 * Deselect a track. 2341 * <p> 2342 * Currently, the track must be a timed text track and no audio or video tracks can be 2343 * deselected. If the timed text track identified by index has not been 2344 * selected before, it throws an exception. 2345 * </p> 2346 * @param index the index of the track to be deselected. The valid range of the index 2347 * is 0..total number of tracks - 1. The total number of tracks as well as the type of 2348 * each individual track can be found by calling {@link #getTrackInfo()} method. 2349 * @throws IllegalStateException if called in an invalid state. 2350 * 2351 * @see android.media.MediaPlayer#getTrackInfo 2352 */ 2353 public void deselectTrack(int index) throws IllegalStateException { 2354 selectOrDeselectTrack(index, false /* select */); 2355 } 2356 2357 private void selectOrDeselectTrack(int index, boolean select) 2358 throws IllegalStateException { 2359 // handle subtitle track through subtitle controller 2360 SubtitleTrack track = null; 2361 if (index < mInbandSubtitleTracks.length) { 2362 track = mInbandSubtitleTracks[index]; 2363 } else if (index < mInbandSubtitleTracks.length + mOutOfBandSubtitleTracks.size()) { 2364 track = mOutOfBandSubtitleTracks.get(index - mInbandSubtitleTracks.length); 2365 } 2366 2367 if (mSubtitleController != null && track != null) { 2368 if (select) { 2369 if (track.isTimedText()) { 2370 int ttIndex = getSelectedTrack(TrackInfo.MEDIA_TRACK_TYPE_TIMEDTEXT); 2371 if (ttIndex >= 0 && ttIndex < mInbandSubtitleTracks.length) { 2372 // deselect inband counterpart 2373 selectOrDeselectInbandTrack(ttIndex, false); 2374 } 2375 } 2376 mSubtitleController.selectTrack(track); 2377 } else if (mSubtitleController.getSelectedTrack() == track) { 2378 mSubtitleController.selectTrack(null); 2379 } else { 2380 Log.w(TAG, "trying to deselect track that was not selected"); 2381 } 2382 return; 2383 } 2384 2385 selectOrDeselectInbandTrack(index, select); 2386 } 2387 2388 private void selectOrDeselectInbandTrack(int index, boolean select) 2389 throws IllegalStateException { 2390 Parcel request = Parcel.obtain(); 2391 Parcel reply = Parcel.obtain(); 2392 try { 2393 request.writeInterfaceToken(IMEDIA_PLAYER); 2394 request.writeInt(select? INVOKE_ID_SELECT_TRACK: INVOKE_ID_DESELECT_TRACK); 2395 request.writeInt(index); 2396 invoke(request, reply); 2397 } finally { 2398 request.recycle(); 2399 reply.recycle(); 2400 } 2401 } 2402 2403 2404 /** 2405 * @param reply Parcel with audio/video duration info for battery 2406 tracking usage 2407 * @return The status code. 2408 * {@hide} 2409 */ 2410 public native static int native_pullBatteryData(Parcel reply); 2411 2412 /** 2413 * Sets the target UDP re-transmit endpoint for the low level player. 2414 * Generally, the address portion of the endpoint is an IP multicast 2415 * address, although a unicast address would be equally valid. When a valid 2416 * retransmit endpoint has been set, the media player will not decode and 2417 * render the media presentation locally. Instead, the player will attempt 2418 * to re-multiplex its media data using the Android@Home RTP profile and 2419 * re-transmit to the target endpoint. Receiver devices (which may be 2420 * either the same as the transmitting device or different devices) may 2421 * instantiate, prepare, and start a receiver player using a setDataSource 2422 * URL of the form... 2423 * 2424 * aahRX://<multicastIP>:<port> 2425 * 2426 * to receive, decode and render the re-transmitted content. 2427 * 2428 * setRetransmitEndpoint may only be called before setDataSource has been 2429 * called; while the player is in the Idle state. 2430 * 2431 * @param endpoint the address and UDP port of the re-transmission target or 2432 * null if no re-transmission is to be performed. 2433 * @throws IllegalStateException if it is called in an invalid state 2434 * @throws IllegalArgumentException if the retransmit endpoint is supplied, 2435 * but invalid. 2436 * 2437 * {@hide} pending API council 2438 */ 2439 public void setRetransmitEndpoint(InetSocketAddress endpoint) 2440 throws IllegalStateException, IllegalArgumentException 2441 { 2442 String addrString = null; 2443 int port = 0; 2444 2445 if (null != endpoint) { 2446 addrString = endpoint.getAddress().getHostAddress(); 2447 port = endpoint.getPort(); 2448 } 2449 2450 int ret = native_setRetransmitEndpoint(addrString, port); 2451 if (ret != 0) { 2452 throw new IllegalArgumentException("Illegal re-transmit endpoint; native ret " + ret); 2453 } 2454 } 2455 2456 private native final int native_setRetransmitEndpoint(String addrString, int port); 2457 2458 @Override 2459 protected void finalize() { native_finalize(); } 2460 2461 /* Do not change these values without updating their counterparts 2462 * in include/media/mediaplayer.h! 2463 */ 2464 private static final int MEDIA_NOP = 0; // interface test message 2465 private static final int MEDIA_PREPARED = 1; 2466 private static final int MEDIA_PLAYBACK_COMPLETE = 2; 2467 private static final int MEDIA_BUFFERING_UPDATE = 3; 2468 private static final int MEDIA_SEEK_COMPLETE = 4; 2469 private static final int MEDIA_SET_VIDEO_SIZE = 5; 2470 private static final int MEDIA_STARTED = 6; 2471 private static final int MEDIA_PAUSED = 7; 2472 private static final int MEDIA_STOPPED = 8; 2473 private static final int MEDIA_SKIPPED = 9; 2474 private static final int MEDIA_TIMED_TEXT = 99; 2475 private static final int MEDIA_ERROR = 100; 2476 private static final int MEDIA_INFO = 200; 2477 private static final int MEDIA_SUBTITLE_DATA = 201; 2478 2479 private TimeProvider mTimeProvider; 2480 2481 /** @hide */ 2482 public MediaTimeProvider getMediaTimeProvider() { 2483 if (mTimeProvider == null) { 2484 mTimeProvider = new TimeProvider(this); 2485 } 2486 return mTimeProvider; 2487 } 2488 2489 private class EventHandler extends Handler 2490 { 2491 private MediaPlayer mMediaPlayer; 2492 2493 public EventHandler(MediaPlayer mp, Looper looper) { 2494 super(looper); 2495 mMediaPlayer = mp; 2496 } 2497 2498 @Override 2499 public void handleMessage(Message msg) { 2500 if (mMediaPlayer.mNativeContext == 0) { 2501 Log.w(TAG, "mediaplayer went away with unhandled events"); 2502 return; 2503 } 2504 switch(msg.what) { 2505 case MEDIA_PREPARED: 2506 scanInternalSubtitleTracks(); 2507 if (mOnPreparedListener != null) 2508 mOnPreparedListener.onPrepared(mMediaPlayer); 2509 return; 2510 2511 case MEDIA_PLAYBACK_COMPLETE: 2512 if (mOnCompletionListener != null) 2513 mOnCompletionListener.onCompletion(mMediaPlayer); 2514 stayAwake(false); 2515 return; 2516 2517 case MEDIA_STOPPED: 2518 if (mTimeProvider != null) { 2519 mTimeProvider.onStopped(); 2520 } 2521 break; 2522 2523 case MEDIA_STARTED: 2524 case MEDIA_PAUSED: 2525 if (mTimeProvider != null) { 2526 mTimeProvider.onPaused(msg.what == MEDIA_PAUSED); 2527 } 2528 break; 2529 2530 case MEDIA_BUFFERING_UPDATE: 2531 if (mOnBufferingUpdateListener != null) 2532 mOnBufferingUpdateListener.onBufferingUpdate(mMediaPlayer, msg.arg1); 2533 return; 2534 2535 case MEDIA_SEEK_COMPLETE: 2536 if (mOnSeekCompleteListener != null) { 2537 mOnSeekCompleteListener.onSeekComplete(mMediaPlayer); 2538 } 2539 // fall through 2540 2541 case MEDIA_SKIPPED: 2542 if (mTimeProvider != null) { 2543 mTimeProvider.onSeekComplete(mMediaPlayer); 2544 } 2545 return; 2546 2547 case MEDIA_SET_VIDEO_SIZE: 2548 if (mOnVideoSizeChangedListener != null) 2549 mOnVideoSizeChangedListener.onVideoSizeChanged(mMediaPlayer, msg.arg1, msg.arg2); 2550 return; 2551 2552 case MEDIA_ERROR: 2553 Log.e(TAG, "Error (" + msg.arg1 + "," + msg.arg2 + ")"); 2554 boolean error_was_handled = false; 2555 if (mOnErrorListener != null) { 2556 error_was_handled = mOnErrorListener.onError(mMediaPlayer, msg.arg1, msg.arg2); 2557 } 2558 if (mOnCompletionListener != null && ! error_was_handled) { 2559 mOnCompletionListener.onCompletion(mMediaPlayer); 2560 } 2561 stayAwake(false); 2562 return; 2563 2564 case MEDIA_INFO: 2565 switch (msg.arg1) { 2566 case MEDIA_INFO_VIDEO_TRACK_LAGGING: 2567 Log.i(TAG, "Info (" + msg.arg1 + "," + msg.arg2 + ")"); 2568 break; 2569 case MEDIA_INFO_METADATA_UPDATE: 2570 scanInternalSubtitleTracks(); 2571 // fall through 2572 2573 case MEDIA_INFO_EXTERNAL_METADATA_UPDATE: 2574 msg.arg1 = MEDIA_INFO_METADATA_UPDATE; 2575 // update default track selection 2576 if (mSubtitleController != null) { 2577 mSubtitleController.selectDefaultTrack(); 2578 } 2579 break; 2580 } 2581 2582 if (mOnInfoListener != null) { 2583 mOnInfoListener.onInfo(mMediaPlayer, msg.arg1, msg.arg2); 2584 } 2585 // No real default action so far. 2586 return; 2587 case MEDIA_TIMED_TEXT: 2588 if (mOnTimedTextListener == null) 2589 return; 2590 if (msg.obj == null) { 2591 mOnTimedTextListener.onTimedText(mMediaPlayer, null); 2592 } else { 2593 if (msg.obj instanceof Parcel) { 2594 Parcel parcel = (Parcel)msg.obj; 2595 TimedText text = new TimedText(parcel); 2596 parcel.recycle(); 2597 mOnTimedTextListener.onTimedText(mMediaPlayer, text); 2598 } 2599 } 2600 return; 2601 2602 case MEDIA_SUBTITLE_DATA: 2603 if (mOnSubtitleDataListener == null) { 2604 return; 2605 } 2606 if (msg.obj instanceof Parcel) { 2607 Parcel parcel = (Parcel) msg.obj; 2608 SubtitleData data = new SubtitleData(parcel); 2609 parcel.recycle(); 2610 mOnSubtitleDataListener.onSubtitleData(mMediaPlayer, data); 2611 } 2612 return; 2613 2614 case MEDIA_NOP: // interface test message - ignore 2615 break; 2616 2617 default: 2618 Log.e(TAG, "Unknown message type " + msg.what); 2619 return; 2620 } 2621 } 2622 } 2623 2624 /* 2625 * Called from native code when an interesting event happens. This method 2626 * just uses the EventHandler system to post the event back to the main app thread. 2627 * We use a weak reference to the original MediaPlayer object so that the native 2628 * code is safe from the object disappearing from underneath it. (This is 2629 * the cookie passed to native_setup().) 2630 */ 2631 private static void postEventFromNative(Object mediaplayer_ref, 2632 int what, int arg1, int arg2, Object obj) 2633 { 2634 MediaPlayer mp = (MediaPlayer)((WeakReference)mediaplayer_ref).get(); 2635 if (mp == null) { 2636 return; 2637 } 2638 2639 if (what == MEDIA_INFO && arg1 == MEDIA_INFO_STARTED_AS_NEXT) { 2640 // this acquires the wakelock if needed, and sets the client side state 2641 mp.start(); 2642 } 2643 if (mp.mEventHandler != null) { 2644 Message m = mp.mEventHandler.obtainMessage(what, arg1, arg2, obj); 2645 mp.mEventHandler.sendMessage(m); 2646 } 2647 } 2648 2649 /** 2650 * Interface definition for a callback to be invoked when the media 2651 * source is ready for playback. 2652 */ 2653 public interface OnPreparedListener 2654 { 2655 /** 2656 * Called when the media file is ready for playback. 2657 * 2658 * @param mp the MediaPlayer that is ready for playback 2659 */ 2660 void onPrepared(MediaPlayer mp); 2661 } 2662 2663 /** 2664 * Register a callback to be invoked when the media source is ready 2665 * for playback. 2666 * 2667 * @param listener the callback that will be run 2668 */ 2669 public void setOnPreparedListener(OnPreparedListener listener) 2670 { 2671 mOnPreparedListener = listener; 2672 } 2673 2674 private OnPreparedListener mOnPreparedListener; 2675 2676 /** 2677 * Interface definition for a callback to be invoked when playback of 2678 * a media source has completed. 2679 */ 2680 public interface OnCompletionListener 2681 { 2682 /** 2683 * Called when the end of a media source is reached during playback. 2684 * 2685 * @param mp the MediaPlayer that reached the end of the file 2686 */ 2687 void onCompletion(MediaPlayer mp); 2688 } 2689 2690 /** 2691 * Register a callback to be invoked when the end of a media source 2692 * has been reached during playback. 2693 * 2694 * @param listener the callback that will be run 2695 */ 2696 public void setOnCompletionListener(OnCompletionListener listener) 2697 { 2698 mOnCompletionListener = listener; 2699 } 2700 2701 private OnCompletionListener mOnCompletionListener; 2702 2703 /** 2704 * Interface definition of a callback to be invoked indicating buffering 2705 * status of a media resource being streamed over the network. 2706 */ 2707 public interface OnBufferingUpdateListener 2708 { 2709 /** 2710 * Called to update status in buffering a media stream received through 2711 * progressive HTTP download. The received buffering percentage 2712 * indicates how much of the content has been buffered or played. 2713 * For example a buffering update of 80 percent when half the content 2714 * has already been played indicates that the next 30 percent of the 2715 * content to play has been buffered. 2716 * 2717 * @param mp the MediaPlayer the update pertains to 2718 * @param percent the percentage (0-100) of the content 2719 * that has been buffered or played thus far 2720 */ 2721 void onBufferingUpdate(MediaPlayer mp, int percent); 2722 } 2723 2724 /** 2725 * Register a callback to be invoked when the status of a network 2726 * stream's buffer has changed. 2727 * 2728 * @param listener the callback that will be run. 2729 */ 2730 public void setOnBufferingUpdateListener(OnBufferingUpdateListener listener) 2731 { 2732 mOnBufferingUpdateListener = listener; 2733 } 2734 2735 private OnBufferingUpdateListener mOnBufferingUpdateListener; 2736 2737 /** 2738 * Interface definition of a callback to be invoked indicating 2739 * the completion of a seek operation. 2740 */ 2741 public interface OnSeekCompleteListener 2742 { 2743 /** 2744 * Called to indicate the completion of a seek operation. 2745 * 2746 * @param mp the MediaPlayer that issued the seek operation 2747 */ 2748 public void onSeekComplete(MediaPlayer mp); 2749 } 2750 2751 /** 2752 * Register a callback to be invoked when a seek operation has been 2753 * completed. 2754 * 2755 * @param listener the callback that will be run 2756 */ 2757 public void setOnSeekCompleteListener(OnSeekCompleteListener listener) 2758 { 2759 mOnSeekCompleteListener = listener; 2760 } 2761 2762 private OnSeekCompleteListener mOnSeekCompleteListener; 2763 2764 /** 2765 * Interface definition of a callback to be invoked when the 2766 * video size is first known or updated 2767 */ 2768 public interface OnVideoSizeChangedListener 2769 { 2770 /** 2771 * Called to indicate the video size 2772 * 2773 * The video size (width and height) could be 0 if there was no video, 2774 * no display surface was set, or the value was not determined yet. 2775 * 2776 * @param mp the MediaPlayer associated with this callback 2777 * @param width the width of the video 2778 * @param height the height of the video 2779 */ 2780 public void onVideoSizeChanged(MediaPlayer mp, int width, int height); 2781 } 2782 2783 /** 2784 * Register a callback to be invoked when the video size is 2785 * known or updated. 2786 * 2787 * @param listener the callback that will be run 2788 */ 2789 public void setOnVideoSizeChangedListener(OnVideoSizeChangedListener listener) 2790 { 2791 mOnVideoSizeChangedListener = listener; 2792 } 2793 2794 private OnVideoSizeChangedListener mOnVideoSizeChangedListener; 2795 2796 /** 2797 * Interface definition of a callback to be invoked when a 2798 * timed text is available for display. 2799 */ 2800 public interface OnTimedTextListener 2801 { 2802 /** 2803 * Called to indicate an avaliable timed text 2804 * 2805 * @param mp the MediaPlayer associated with this callback 2806 * @param text the timed text sample which contains the text 2807 * needed to be displayed and the display format. 2808 */ 2809 public void onTimedText(MediaPlayer mp, TimedText text); 2810 } 2811 2812 /** 2813 * Register a callback to be invoked when a timed text is available 2814 * for display. 2815 * 2816 * @param listener the callback that will be run 2817 */ 2818 public void setOnTimedTextListener(OnTimedTextListener listener) 2819 { 2820 mOnTimedTextListener = listener; 2821 } 2822 2823 private OnTimedTextListener mOnTimedTextListener; 2824 2825 /** 2826 * Interface definition of a callback to be invoked when a 2827 * track has data available. 2828 * 2829 * @hide 2830 */ 2831 public interface OnSubtitleDataListener 2832 { 2833 public void onSubtitleData(MediaPlayer mp, SubtitleData data); 2834 } 2835 2836 /** 2837 * Register a callback to be invoked when a track has data available. 2838 * 2839 * @param listener the callback that will be run 2840 * 2841 * @hide 2842 */ 2843 public void setOnSubtitleDataListener(OnSubtitleDataListener listener) 2844 { 2845 mOnSubtitleDataListener = listener; 2846 } 2847 2848 private OnSubtitleDataListener mOnSubtitleDataListener; 2849 2850 /* Do not change these values without updating their counterparts 2851 * in include/media/mediaplayer.h! 2852 */ 2853 /** Unspecified media player error. 2854 * @see android.media.MediaPlayer.OnErrorListener 2855 */ 2856 public static final int MEDIA_ERROR_UNKNOWN = 1; 2857 2858 /** Media server died. In this case, the application must release the 2859 * MediaPlayer object and instantiate a new one. 2860 * @see android.media.MediaPlayer.OnErrorListener 2861 */ 2862 public static final int MEDIA_ERROR_SERVER_DIED = 100; 2863 2864 /** The video is streamed and its container is not valid for progressive 2865 * playback i.e the video's index (e.g moov atom) is not at the start of the 2866 * file. 2867 * @see android.media.MediaPlayer.OnErrorListener 2868 */ 2869 public static final int MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK = 200; 2870 2871 /** File or network related operation errors. */ 2872 public static final int MEDIA_ERROR_IO = -1004; 2873 /** Bitstream is not conforming to the related coding standard or file spec. */ 2874 public static final int MEDIA_ERROR_MALFORMED = -1007; 2875 /** Bitstream is conforming to the related coding standard or file spec, but 2876 * the media framework does not support the feature. */ 2877 public static final int MEDIA_ERROR_UNSUPPORTED = -1010; 2878 /** Some operation takes too long to complete, usually more than 3-5 seconds. */ 2879 public static final int MEDIA_ERROR_TIMED_OUT = -110; 2880 2881 /** 2882 * Interface definition of a callback to be invoked when there 2883 * has been an error during an asynchronous operation (other errors 2884 * will throw exceptions at method call time). 2885 */ 2886 public interface OnErrorListener 2887 { 2888 /** 2889 * Called to indicate an error. 2890 * 2891 * @param mp the MediaPlayer the error pertains to 2892 * @param what the type of error that has occurred: 2893 * <ul> 2894 * <li>{@link #MEDIA_ERROR_UNKNOWN} 2895 * <li>{@link #MEDIA_ERROR_SERVER_DIED} 2896 * </ul> 2897 * @param extra an extra code, specific to the error. Typically 2898 * implementation dependent. 2899 * <ul> 2900 * <li>{@link #MEDIA_ERROR_IO} 2901 * <li>{@link #MEDIA_ERROR_MALFORMED} 2902 * <li>{@link #MEDIA_ERROR_UNSUPPORTED} 2903 * <li>{@link #MEDIA_ERROR_TIMED_OUT} 2904 * </ul> 2905 * @return True if the method handled the error, false if it didn't. 2906 * Returning false, or not having an OnErrorListener at all, will 2907 * cause the OnCompletionListener to be called. 2908 */ 2909 boolean onError(MediaPlayer mp, int what, int extra); 2910 } 2911 2912 /** 2913 * Register a callback to be invoked when an error has happened 2914 * during an asynchronous operation. 2915 * 2916 * @param listener the callback that will be run 2917 */ 2918 public void setOnErrorListener(OnErrorListener listener) 2919 { 2920 mOnErrorListener = listener; 2921 } 2922 2923 private OnErrorListener mOnErrorListener; 2924 2925 2926 /* Do not change these values without updating their counterparts 2927 * in include/media/mediaplayer.h! 2928 */ 2929 /** Unspecified media player info. 2930 * @see android.media.MediaPlayer.OnInfoListener 2931 */ 2932 public static final int MEDIA_INFO_UNKNOWN = 1; 2933 2934 /** The player was started because it was used as the next player for another 2935 * player, which just completed playback. 2936 * @see android.media.MediaPlayer.OnInfoListener 2937 * @hide 2938 */ 2939 public static final int MEDIA_INFO_STARTED_AS_NEXT = 2; 2940 2941 /** The player just pushed the very first video frame for rendering. 2942 * @see android.media.MediaPlayer.OnInfoListener 2943 */ 2944 public static final int MEDIA_INFO_VIDEO_RENDERING_START = 3; 2945 2946 /** The video is too complex for the decoder: it can't decode frames fast 2947 * enough. Possibly only the audio plays fine at this stage. 2948 * @see android.media.MediaPlayer.OnInfoListener 2949 */ 2950 public static final int MEDIA_INFO_VIDEO_TRACK_LAGGING = 700; 2951 2952 /** MediaPlayer is temporarily pausing playback internally in order to 2953 * buffer more data. 2954 * @see android.media.MediaPlayer.OnInfoListener 2955 */ 2956 public static final int MEDIA_INFO_BUFFERING_START = 701; 2957 2958 /** MediaPlayer is resuming playback after filling buffers. 2959 * @see android.media.MediaPlayer.OnInfoListener 2960 */ 2961 public static final int MEDIA_INFO_BUFFERING_END = 702; 2962 2963 /** Bad interleaving means that a media has been improperly interleaved or 2964 * not interleaved at all, e.g has all the video samples first then all the 2965 * audio ones. Video is playing but a lot of disk seeks may be happening. 2966 * @see android.media.MediaPlayer.OnInfoListener 2967 */ 2968 public static final int MEDIA_INFO_BAD_INTERLEAVING = 800; 2969 2970 /** The media cannot be seeked (e.g live stream) 2971 * @see android.media.MediaPlayer.OnInfoListener 2972 */ 2973 public static final int MEDIA_INFO_NOT_SEEKABLE = 801; 2974 2975 /** A new set of metadata is available. 2976 * @see android.media.MediaPlayer.OnInfoListener 2977 */ 2978 public static final int MEDIA_INFO_METADATA_UPDATE = 802; 2979 2980 /** A new set of external-only metadata is available. Used by 2981 * JAVA framework to avoid triggering track scanning. 2982 * @hide 2983 */ 2984 public static final int MEDIA_INFO_EXTERNAL_METADATA_UPDATE = 803; 2985 2986 /** Failed to handle timed text track properly. 2987 * @see android.media.MediaPlayer.OnInfoListener 2988 * 2989 * {@hide} 2990 */ 2991 public static final int MEDIA_INFO_TIMED_TEXT_ERROR = 900; 2992 2993 /** Subtitle track was not supported by the media framework. 2994 * @see android.media.MediaPlayer.OnInfoListener 2995 */ 2996 public static final int MEDIA_INFO_UNSUPPORTED_SUBTITLE = 901; 2997 2998 /** Reading the subtitle track takes too long. 2999 * @see android.media.MediaPlayer.OnInfoListener 3000 */ 3001 public static final int MEDIA_INFO_SUBTITLE_TIMED_OUT = 902; 3002 3003 /** 3004 * Interface definition of a callback to be invoked to communicate some 3005 * info and/or warning about the media or its playback. 3006 */ 3007 public interface OnInfoListener 3008 { 3009 /** 3010 * Called to indicate an info or a warning. 3011 * 3012 * @param mp the MediaPlayer the info pertains to. 3013 * @param what the type of info or warning. 3014 * <ul> 3015 * <li>{@link #MEDIA_INFO_UNKNOWN} 3016 * <li>{@link #MEDIA_INFO_VIDEO_TRACK_LAGGING} 3017 * <li>{@link #MEDIA_INFO_VIDEO_RENDERING_START} 3018 * <li>{@link #MEDIA_INFO_BUFFERING_START} 3019 * <li>{@link #MEDIA_INFO_BUFFERING_END} 3020 * <li>{@link #MEDIA_INFO_BAD_INTERLEAVING} 3021 * <li>{@link #MEDIA_INFO_NOT_SEEKABLE} 3022 * <li>{@link #MEDIA_INFO_METADATA_UPDATE} 3023 * <li>{@link #MEDIA_INFO_UNSUPPORTED_SUBTITLE} 3024 * <li>{@link #MEDIA_INFO_SUBTITLE_TIMED_OUT} 3025 * </ul> 3026 * @param extra an extra code, specific to the info. Typically 3027 * implementation dependent. 3028 * @return True if the method handled the info, false if it didn't. 3029 * Returning false, or not having an OnErrorListener at all, will 3030 * cause the info to be discarded. 3031 */ 3032 boolean onInfo(MediaPlayer mp, int what, int extra); 3033 } 3034 3035 /** 3036 * Register a callback to be invoked when an info/warning is available. 3037 * 3038 * @param listener the callback that will be run 3039 */ 3040 public void setOnInfoListener(OnInfoListener listener) 3041 { 3042 mOnInfoListener = listener; 3043 } 3044 3045 private OnInfoListener mOnInfoListener; 3046 3047 /* 3048 * Test whether a given video scaling mode is supported. 3049 */ 3050 private boolean isVideoScalingModeSupported(int mode) { 3051 return (mode == VIDEO_SCALING_MODE_SCALE_TO_FIT || 3052 mode == VIDEO_SCALING_MODE_SCALE_TO_FIT_WITH_CROPPING); 3053 } 3054 3055 /** @hide */ 3056 static class TimeProvider implements MediaPlayer.OnSeekCompleteListener, 3057 MediaTimeProvider { 3058 private static final String TAG = "MTP"; 3059 private static final long MAX_NS_WITHOUT_POSITION_CHECK = 5000000000L; 3060 private static final long MAX_EARLY_CALLBACK_US = 1000; 3061 private static final long TIME_ADJUSTMENT_RATE = 2; /* meaning 1/2 */ 3062 private long mLastTimeUs = 0; 3063 private MediaPlayer mPlayer; 3064 private boolean mPaused = true; 3065 private boolean mStopped = true; 3066 private long mLastReportedTime; 3067 private long mTimeAdjustment; 3068 // since we are expecting only a handful listeners per stream, there is 3069 // no need for log(N) search performance 3070 private MediaTimeProvider.OnMediaTimeListener mListeners[]; 3071 private long mTimes[]; 3072 private long mLastNanoTime; 3073 private Handler mEventHandler; 3074 private boolean mRefresh = false; 3075 private boolean mPausing = false; 3076 private boolean mSeeking = false; 3077 private static final int NOTIFY = 1; 3078 private static final int NOTIFY_TIME = 0; 3079 private static final int REFRESH_AND_NOTIFY_TIME = 1; 3080 private static final int NOTIFY_STOP = 2; 3081 private static final int NOTIFY_SEEK = 3; 3082 private HandlerThread mHandlerThread; 3083 3084 /** @hide */ 3085 public boolean DEBUG = false; 3086 3087 public TimeProvider(MediaPlayer mp) { 3088 mPlayer = mp; 3089 try { 3090 getCurrentTimeUs(true, false); 3091 } catch (IllegalStateException e) { 3092 // we assume starting position 3093 mRefresh = true; 3094 } 3095 3096 Looper looper; 3097 if ((looper = Looper.myLooper()) == null && 3098 (looper = Looper.getMainLooper()) == null) { 3099 // Create our own looper here in case MP was created without one 3100 mHandlerThread = new HandlerThread("MediaPlayerMTPEventThread", 3101 Process.THREAD_PRIORITY_FOREGROUND); 3102 mHandlerThread.start(); 3103 looper = mHandlerThread.getLooper(); 3104 } 3105 mEventHandler = new EventHandler(looper); 3106 3107 mListeners = new MediaTimeProvider.OnMediaTimeListener[0]; 3108 mTimes = new long[0]; 3109 mLastTimeUs = 0; 3110 mTimeAdjustment = 0; 3111 } 3112 3113 private void scheduleNotification(int type, long delayUs) { 3114 // ignore time notifications until seek is handled 3115 if (mSeeking && 3116 (type == NOTIFY_TIME || type == REFRESH_AND_NOTIFY_TIME)) { 3117 return; 3118 } 3119 3120 if (DEBUG) Log.v(TAG, "scheduleNotification " + type + " in " + delayUs); 3121 mEventHandler.removeMessages(NOTIFY); 3122 Message msg = mEventHandler.obtainMessage(NOTIFY, type, 0); 3123 mEventHandler.sendMessageDelayed(msg, (int) (delayUs / 1000)); 3124 } 3125 3126 /** @hide */ 3127 public void close() { 3128 mEventHandler.removeMessages(NOTIFY); 3129 if (mHandlerThread != null) { 3130 mHandlerThread.quitSafely(); 3131 mHandlerThread = null; 3132 } 3133 } 3134 3135 /** @hide */ 3136 protected void finalize() { 3137 if (mHandlerThread != null) { 3138 mHandlerThread.quitSafely(); 3139 } 3140 } 3141 3142 /** @hide */ 3143 public void onPaused(boolean paused) { 3144 synchronized(this) { 3145 if (DEBUG) Log.d(TAG, "onPaused: " + paused); 3146 if (mStopped) { // handle as seek if we were stopped 3147 mStopped = false; 3148 mSeeking = true; 3149 scheduleNotification(NOTIFY_SEEK, 0 /* delay */); 3150 } else { 3151 mPausing = paused; // special handling if player disappeared 3152 mSeeking = false; 3153 scheduleNotification(REFRESH_AND_NOTIFY_TIME, 0 /* delay */); 3154 } 3155 } 3156 } 3157 3158 /** @hide */ 3159 public void onStopped() { 3160 synchronized(this) { 3161 if (DEBUG) Log.d(TAG, "onStopped"); 3162 mPaused = true; 3163 mStopped = true; 3164 mSeeking = false; 3165 scheduleNotification(NOTIFY_STOP, 0 /* delay */); 3166 } 3167 } 3168 3169 /** @hide */ 3170 @Override 3171 public void onSeekComplete(MediaPlayer mp) { 3172 synchronized(this) { 3173 mStopped = false; 3174 mSeeking = true; 3175 scheduleNotification(NOTIFY_SEEK, 0 /* delay */); 3176 } 3177 } 3178 3179 /** @hide */ 3180 public void onNewPlayer() { 3181 if (mRefresh) { 3182 synchronized(this) { 3183 mStopped = false; 3184 mSeeking = true; 3185 scheduleNotification(NOTIFY_SEEK, 0 /* delay */); 3186 } 3187 } 3188 } 3189 3190 private synchronized void notifySeek() { 3191 mSeeking = false; 3192 try { 3193 long timeUs = getCurrentTimeUs(true, false); 3194 if (DEBUG) Log.d(TAG, "onSeekComplete at " + timeUs); 3195 3196 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) { 3197 if (listener == null) { 3198 break; 3199 } 3200 listener.onSeek(timeUs); 3201 } 3202 } catch (IllegalStateException e) { 3203 // we should not be there, but at least signal pause 3204 if (DEBUG) Log.d(TAG, "onSeekComplete but no player"); 3205 mPausing = true; // special handling if player disappeared 3206 notifyTimedEvent(false /* refreshTime */); 3207 } 3208 } 3209 3210 private synchronized void notifyStop() { 3211 for (MediaTimeProvider.OnMediaTimeListener listener: mListeners) { 3212 if (listener == null) { 3213 break; 3214 } 3215 listener.onStop(); 3216 } 3217 } 3218 3219 private int registerListener(MediaTimeProvider.OnMediaTimeListener listener) { 3220 int i = 0; 3221 for (; i < mListeners.length; i++) { 3222 if (mListeners[i] == listener || mListeners[i] == null) { 3223 break; 3224 } 3225 } 3226 3227 // new listener 3228 if (i >= mListeners.length) { 3229 MediaTimeProvider.OnMediaTimeListener[] newListeners = 3230 new MediaTimeProvider.OnMediaTimeListener[i + 1]; 3231 long[] newTimes = new long[i + 1]; 3232 System.arraycopy(mListeners, 0, newListeners, 0, mListeners.length); 3233 System.arraycopy(mTimes, 0, newTimes, 0, mTimes.length); 3234 mListeners = newListeners; 3235 mTimes = newTimes; 3236 } 3237 3238 if (mListeners[i] == null) { 3239 mListeners[i] = listener; 3240 mTimes[i] = MediaTimeProvider.NO_TIME; 3241 } 3242 return i; 3243 } 3244 3245 public void notifyAt( 3246 long timeUs, MediaTimeProvider.OnMediaTimeListener listener) { 3247 synchronized(this) { 3248 if (DEBUG) Log.d(TAG, "notifyAt " + timeUs); 3249 mTimes[registerListener(listener)] = timeUs; 3250 scheduleNotification(NOTIFY_TIME, 0 /* delay */); 3251 } 3252 } 3253 3254 public void scheduleUpdate(MediaTimeProvider.OnMediaTimeListener listener) { 3255 synchronized(this) { 3256 if (DEBUG) Log.d(TAG, "scheduleUpdate"); 3257 int i = registerListener(listener); 3258 3259 if (mStopped) { 3260 scheduleNotification(NOTIFY_STOP, 0 /* delay */); 3261 } else { 3262 mTimes[i] = 0; 3263 scheduleNotification(NOTIFY_TIME, 0 /* delay */); 3264 } 3265 } 3266 } 3267 3268 public void cancelNotifications( 3269 MediaTimeProvider.OnMediaTimeListener listener) { 3270 synchronized(this) { 3271 int i = 0; 3272 for (; i < mListeners.length; i++) { 3273 if (mListeners[i] == listener) { 3274 System.arraycopy(mListeners, i + 1, 3275 mListeners, i, mListeners.length - i - 1); 3276 System.arraycopy(mTimes, i + 1, 3277 mTimes, i, mTimes.length - i - 1); 3278 mListeners[mListeners.length - 1] = null; 3279 mTimes[mTimes.length - 1] = NO_TIME; 3280 break; 3281 } else if (mListeners[i] == null) { 3282 break; 3283 } 3284 } 3285 3286 scheduleNotification(NOTIFY_TIME, 0 /* delay */); 3287 } 3288 } 3289 3290 private synchronized void notifyTimedEvent(boolean refreshTime) { 3291 // figure out next callback 3292 long nowUs; 3293 try { 3294 nowUs = getCurrentTimeUs(refreshTime, true); 3295 } catch (IllegalStateException e) { 3296 // assume we paused until new player arrives 3297 mRefresh = true; 3298 mPausing = true; // this ensures that call succeeds 3299 nowUs = getCurrentTimeUs(refreshTime, true); 3300 } 3301 long nextTimeUs = nowUs; 3302 3303 if (mSeeking) { 3304 // skip timed-event notifications until seek is complete 3305 return; 3306 } 3307 3308 if (DEBUG) { 3309 StringBuilder sb = new StringBuilder(); 3310 sb.append("notifyTimedEvent(").append(mLastTimeUs).append(" -> ") 3311 .append(nowUs).append(") from {"); 3312 boolean first = true; 3313 for (long time: mTimes) { 3314 if (time == NO_TIME) { 3315 continue; 3316 } 3317 if (!first) sb.append(", "); 3318 sb.append(time); 3319 first = false; 3320 } 3321 sb.append("}"); 3322 Log.d(TAG, sb.toString()); 3323 } 3324 3325 Vector<MediaTimeProvider.OnMediaTimeListener> activatedListeners = 3326 new Vector<MediaTimeProvider.OnMediaTimeListener>(); 3327 for (int ix = 0; ix < mTimes.length; ix++) { 3328 if (mListeners[ix] == null) { 3329 break; 3330 } 3331 if (mTimes[ix] <= NO_TIME) { 3332 // ignore, unless we were stopped 3333 } else if (mTimes[ix] <= nowUs + MAX_EARLY_CALLBACK_US) { 3334 activatedListeners.add(mListeners[ix]); 3335 if (DEBUG) Log.d(TAG, "removed"); 3336 mTimes[ix] = NO_TIME; 3337 } else if (nextTimeUs == nowUs || mTimes[ix] < nextTimeUs) { 3338 nextTimeUs = mTimes[ix]; 3339 } 3340 } 3341 3342 if (nextTimeUs > nowUs && !mPaused) { 3343 // schedule callback at nextTimeUs 3344 if (DEBUG) Log.d(TAG, "scheduling for " + nextTimeUs + " and " + nowUs); 3345 scheduleNotification(NOTIFY_TIME, nextTimeUs - nowUs); 3346 } else { 3347 mEventHandler.removeMessages(NOTIFY); 3348 // no more callbacks 3349 } 3350 3351 for (MediaTimeProvider.OnMediaTimeListener listener: activatedListeners) { 3352 listener.onTimedEvent(nowUs); 3353 } 3354 } 3355 3356 private long getEstimatedTime(long nanoTime, boolean monotonic) { 3357 if (mPaused) { 3358 mLastReportedTime = mLastTimeUs + mTimeAdjustment; 3359 } else { 3360 long timeSinceRead = (nanoTime - mLastNanoTime) / 1000; 3361 mLastReportedTime = mLastTimeUs + timeSinceRead; 3362 if (mTimeAdjustment > 0) { 3363 long adjustment = 3364 mTimeAdjustment - timeSinceRead / TIME_ADJUSTMENT_RATE; 3365 if (adjustment <= 0) { 3366 mTimeAdjustment = 0; 3367 } else { 3368 mLastReportedTime += adjustment; 3369 } 3370 } 3371 } 3372 return mLastReportedTime; 3373 } 3374 3375 public long getCurrentTimeUs(boolean refreshTime, boolean monotonic) 3376 throws IllegalStateException { 3377 synchronized (this) { 3378 // we always refresh the time when the paused-state changes, because 3379 // we expect to have received the pause-change event delayed. 3380 if (mPaused && !refreshTime) { 3381 return mLastReportedTime; 3382 } 3383 3384 long nanoTime = System.nanoTime(); 3385 if (refreshTime || 3386 nanoTime >= mLastNanoTime + MAX_NS_WITHOUT_POSITION_CHECK) { 3387 try { 3388 mLastTimeUs = mPlayer.getCurrentPosition() * 1000L; 3389 mPaused = !mPlayer.isPlaying(); 3390 if (DEBUG) Log.v(TAG, (mPaused ? "paused" : "playing") + " at " + mLastTimeUs); 3391 } catch (IllegalStateException e) { 3392 if (mPausing) { 3393 // if we were pausing, get last estimated timestamp 3394 mPausing = false; 3395 getEstimatedTime(nanoTime, monotonic); 3396 mPaused = true; 3397 if (DEBUG) Log.d(TAG, "illegal state, but pausing: estimating at " + mLastReportedTime); 3398 return mLastReportedTime; 3399 } 3400 // TODO get time when prepared 3401 throw e; 3402 } 3403 mLastNanoTime = nanoTime; 3404 if (monotonic && mLastTimeUs < mLastReportedTime) { 3405 /* have to adjust time */ 3406 mTimeAdjustment = mLastReportedTime - mLastTimeUs; 3407 if (mTimeAdjustment > 1000000) { 3408 // schedule seeked event if time jumped significantly 3409 // TODO: do this properly by introducing an exception 3410 mStopped = false; 3411 mSeeking = true; 3412 scheduleNotification(NOTIFY_SEEK, 0 /* delay */); 3413 } 3414 } else { 3415 mTimeAdjustment = 0; 3416 } 3417 } 3418 3419 return getEstimatedTime(nanoTime, monotonic); 3420 } 3421 } 3422 3423 private class EventHandler extends Handler { 3424 public EventHandler(Looper looper) { 3425 super(looper); 3426 } 3427 3428 @Override 3429 public void handleMessage(Message msg) { 3430 if (msg.what == NOTIFY) { 3431 switch (msg.arg1) { 3432 case NOTIFY_TIME: 3433 notifyTimedEvent(false /* refreshTime */); 3434 break; 3435 case REFRESH_AND_NOTIFY_TIME: 3436 notifyTimedEvent(true /* refreshTime */); 3437 break; 3438 case NOTIFY_STOP: 3439 notifyStop(); 3440 break; 3441 case NOTIFY_SEEK: 3442 notifySeek(); 3443 break; 3444 } 3445 } 3446 } 3447 } 3448 } 3449} 3450