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