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