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