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