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