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