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