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