android_GenericMediaPlayer.cpp revision 833251ab9e5e59a6ea5ac325122cf3abdf7cd944
1/* 2 * Copyright (C) 2011 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 17//#define USE_LOG SLAndroidLogLevel_Verbose 18 19#include "sles_allinclusive.h" 20#include "android_GenericMediaPlayer.h" 21 22#include <media/IMediaPlayerService.h> 23#include <surfaceflinger/ISurfaceComposer.h> 24#include <surfaceflinger/SurfaceComposerClient.h> 25#include <media/stagefright/foundation/ADebug.h> 26 27// default delay in Us used when reposting an event when the player is not ready to accept 28// the command yet. This is for instance used when seeking on a MediaPlayer that's still preparing 29#define DEFAULT_COMMAND_DELAY_FOR_REPOST_US (100*1000) // 100ms 30 31// table of prefixes for known distant protocols; these are immediately dispatched to mediaserver 32static const char* const kDistantProtocolPrefix[] = { "http://", "https://", "rtsp://"}; 33#define NB_DISTANT_PROTOCOLS (sizeof(kDistantProtocolPrefix)/sizeof(kDistantProtocolPrefix[0])) 34 35// is the specified URI a known distant protocol? 36bool isDistantProtocol(const char *uri) 37{ 38 for (unsigned int i = 0; i < NB_DISTANT_PROTOCOLS; i++) { 39 if (!strncasecmp(uri, kDistantProtocolPrefix[i], strlen(kDistantProtocolPrefix[i]))) { 40 return true; 41 } 42 } 43 return false; 44} 45 46namespace android { 47 48//-------------------------------------------------------------------------------------------------- 49MediaPlayerNotificationClient::MediaPlayerNotificationClient(GenericMediaPlayer* gmp) : 50 mGenericMediaPlayer(gmp), 51 mPlayerPrepared(PREPARE_NOT_STARTED) 52{ 53 SL_LOGV("MediaPlayerNotificationClient::MediaPlayerNotificationClient()"); 54} 55 56MediaPlayerNotificationClient::~MediaPlayerNotificationClient() { 57 SL_LOGV("MediaPlayerNotificationClient::~MediaPlayerNotificationClient()"); 58} 59 60// Map a MEDIA_* enum to a string 61static const char *media_to_string(int msg) 62{ 63 switch (msg) { 64#define _(x) case MEDIA_##x: return "MEDIA_" #x; 65 _(PREPARED) 66 _(SET_VIDEO_SIZE) 67 _(SEEK_COMPLETE) 68 _(PLAYBACK_COMPLETE) 69 _(BUFFERING_UPDATE) 70 _(ERROR) 71 _(NOP) 72 _(TIMED_TEXT) 73 _(INFO) 74#undef _ 75 default: 76 return NULL; 77 } 78} 79 80//-------------------------------------------------- 81// IMediaPlayerClient implementation 82void MediaPlayerNotificationClient::notify(int msg, int ext1, int ext2, const Parcel *obj) { 83 SL_LOGV("MediaPlayerNotificationClient::notify(msg=%s (%d), ext1=%d, ext2=%d)", 84 media_to_string(msg), msg, ext1, ext2); 85 86 switch (msg) { 87 case MEDIA_PREPARED: 88 mPlayerPrepared = PREPARE_COMPLETED_SUCCESSFULLY; 89 mPlayerPreparedCondition.signal(); 90 break; 91 92 case MEDIA_SET_VIDEO_SIZE: 93 // only send video size updates if the player was flagged as having video, to avoid 94 // sending video size updates of (0,0) 95 if (mGenericMediaPlayer->mHasVideo) { 96 mGenericMediaPlayer->notify(PLAYEREVENT_VIDEO_SIZE_UPDATE, 97 (int32_t)ext1, (int32_t)ext2, true /*async*/); 98 } 99 break; 100 101 case MEDIA_SEEK_COMPLETE: 102 mGenericMediaPlayer->seekComplete(); 103 break; 104 105 case MEDIA_PLAYBACK_COMPLETE: 106 mGenericMediaPlayer->notify(PLAYEREVENT_ENDOFSTREAM, 1, true /*async*/); 107 break; 108 109 case MEDIA_BUFFERING_UPDATE: 110 // values received from Android framework for buffer fill level use percent, 111 // while SL/XA use permille, so does GenericPlayer 112 mGenericMediaPlayer->bufferingUpdate(ext1 * 10 /*fillLevelPerMille*/); 113 break; 114 115 case MEDIA_ERROR: 116 mPlayerPrepared = PREPARE_COMPLETED_UNSUCCESSFULLY; 117 mPlayerPreparedCondition.signal(); 118 break; 119 120 case MEDIA_NOP: 121 case MEDIA_TIMED_TEXT: 122 case MEDIA_INFO: 123 break; 124 125 default: { } 126 } 127 128} 129 130//-------------------------------------------------- 131void MediaPlayerNotificationClient::beforePrepare() 132{ 133 Mutex::Autolock _l(mLock); 134 assert(mPlayerPrepared == PREPARE_NOT_STARTED); 135 mPlayerPrepared = PREPARE_IN_PROGRESS; 136} 137 138//-------------------------------------------------- 139bool MediaPlayerNotificationClient::blockUntilPlayerPrepared() { 140 Mutex::Autolock _l(mLock); 141 assert(mPlayerPrepared != PREPARE_NOT_STARTED); 142 while (mPlayerPrepared == PREPARE_IN_PROGRESS) { 143 mPlayerPreparedCondition.wait(mLock); 144 } 145 assert(mPlayerPrepared == PREPARE_COMPLETED_SUCCESSFULLY || 146 mPlayerPrepared == PREPARE_COMPLETED_UNSUCCESSFULLY); 147 return mPlayerPrepared == PREPARE_COMPLETED_SUCCESSFULLY; 148} 149 150//-------------------------------------------------------------------------------------------------- 151GenericMediaPlayer::GenericMediaPlayer(const AudioPlayback_Parameters* params, bool hasVideo) : 152 GenericPlayer(params), 153 mHasVideo(hasVideo), 154 mSeekTimeMsec(0), 155 mVideoSurface(0), 156 mVideoSurfaceTexture(0), 157 mPlayer(0), 158 mPlayerClient(0) 159{ 160 SL_LOGD("GenericMediaPlayer::GenericMediaPlayer()"); 161 162 mPlayerClient = new MediaPlayerNotificationClient(this); 163} 164 165GenericMediaPlayer::~GenericMediaPlayer() { 166 SL_LOGD("GenericMediaPlayer::~GenericMediaPlayer()"); 167} 168 169void GenericMediaPlayer::preDestroy() { 170 SL_LOGD("GenericMediaPlayer::preDestroy()"); 171 GenericPlayer::preDestroy(); 172} 173 174//-------------------------------------------------- 175// overridden from GenericPlayer 176// pre-condition: 177// msec != NULL 178// post-condition 179// *msec == 180// ANDROID_UNKNOWN_TIME if position is unknown at time of query, 181// or the current MediaPlayer position 182void GenericMediaPlayer::getPositionMsec(int* msec) { 183 SL_LOGD("GenericMediaPlayer::getPositionMsec()"); 184 sp<IMediaPlayer> player; 185 getPlayerPrepared(player); 186 // To avoid deadlock, directly call the MediaPlayer object 187 if (player == 0 || player->getCurrentPosition(msec) != NO_ERROR) { 188 *msec = ANDROID_UNKNOWN_TIME; 189 } 190} 191 192//-------------------------------------------------- 193void GenericMediaPlayer::setVideoSurface(const sp<Surface> &surface) { 194 SL_LOGV("GenericMediaPlayer::setVideoSurface()"); 195 // FIXME bug - race condition, should do in looper 196 if (mVideoSurface.get() == surface.get()) { 197 return; 198 } 199 if ((mStateFlags & kFlagPrepared) && (mPlayer != 0)) { 200 mPlayer->setVideoSurface(surface); 201 } 202 mVideoSurface = surface; 203 mVideoSurfaceTexture = NULL; 204} 205 206void GenericMediaPlayer::setVideoSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) { 207 SL_LOGV("GenericMediaPlayer::setVideoSurfaceTexture()"); 208 // FIXME bug - race condition, should do in looper 209 if (mVideoSurfaceTexture.get() == surfaceTexture.get()) { 210 return; 211 } 212 if ((mStateFlags & kFlagPrepared) && (mPlayer != 0)) { 213 mPlayer->setVideoSurfaceTexture(surfaceTexture); 214 } 215 mVideoSurfaceTexture = surfaceTexture; 216 mVideoSurface = NULL; 217} 218 219 220//-------------------------------------------------- 221// Event handlers 222 223// blocks until mPlayer is prepared 224void GenericMediaPlayer::onPrepare() { 225 SL_LOGD("GenericMediaPlayer::onPrepare()"); 226 // Attempt to prepare at most once, and only if there is a MediaPlayer 227 if (!(mStateFlags & (kFlagPrepared | kFlagPreparedUnsuccessfully)) && (mPlayer != 0)) { 228 if (mHasVideo) { 229 if (mVideoSurface != 0) { 230 mPlayer->setVideoSurface(mVideoSurface); 231 } else if (mVideoSurfaceTexture != 0) { 232 mPlayer->setVideoSurfaceTexture(mVideoSurfaceTexture); 233 } 234 } 235 mPlayer->setAudioStreamType(mPlaybackParams.streamType); 236 mPlayerClient->beforePrepare(); 237 mPlayer->prepareAsync(); 238 if (mPlayerClient->blockUntilPlayerPrepared()) { 239 mStateFlags |= kFlagPrepared; 240 afterMediaPlayerPreparedSuccessfully(); 241 } else { 242 mStateFlags |= kFlagPreparedUnsuccessfully; 243 } 244 } 245 GenericPlayer::onPrepare(); 246 SL_LOGD("GenericMediaPlayer::onPrepare() done, mStateFlags=0x%x", mStateFlags); 247} 248 249 250void GenericMediaPlayer::onPlay() { 251 SL_LOGD("GenericMediaPlayer::onPlay()"); 252 if (((mStateFlags & (kFlagPrepared | kFlagPlaying)) == kFlagPrepared) && (mPlayer != 0)) { 253 mPlayer->start(); 254 } 255 GenericPlayer::onPlay(); 256} 257 258 259void GenericMediaPlayer::onPause() { 260 SL_LOGD("GenericMediaPlayer::onPause()"); 261 if (!(~mStateFlags & (kFlagPrepared | kFlagPlaying)) && (mPlayer != 0)) { 262 mPlayer->pause(); 263 } 264 GenericPlayer::onPause(); 265} 266 267 268void GenericMediaPlayer::onSeekComplete() { 269 SL_LOGV("GenericMediaPlayer::onSeekComplete()"); 270 // did we initiate the seek? 271 if (!(mStateFlags & kFlagSeeking)) { 272 // no, are we looping? 273 if (mStateFlags & kFlagLooping) { 274 // yes, per OpenSL ES 1.0.1 and 1.1 do NOT report it to client 275 // notify(PLAYEREVENT_ENDOFSTREAM, 1, true /*async*/); 276 // no, well that's surprising, but it's probably just a benign race condition 277 } else { 278 SL_LOGW("Unexpected seek complete event ignored"); 279 } 280 } 281 GenericPlayer::onSeekComplete(); 282} 283 284 285/** 286 * pre-condition: WHATPARAM_SEEK_SEEKTIME_MS parameter value >= 0 287 */ 288void GenericMediaPlayer::onSeek(const sp<AMessage> &msg) { 289 SL_LOGV("GenericMediaPlayer::onSeek"); 290 int64_t timeMsec = ANDROID_UNKNOWN_TIME; 291 if (!msg->findInt64(WHATPARAM_SEEK_SEEKTIME_MS, &timeMsec)) { 292 // invalid command, drop it 293 return; 294 } 295 if ((mStateFlags & kFlagSeeking) && (timeMsec == mSeekTimeMsec)) { 296 // already seeking to the same time, cancel this command 297 return; 298 } else if (mStateFlags & kFlagPreparedUnsuccessfully) { 299 // discard seeks after unsuccessful prepare 300 } else if (!(mStateFlags & kFlagPrepared)) { 301 // we are not ready to accept a seek command at this time, retry later 302 msg->post(DEFAULT_COMMAND_DELAY_FOR_REPOST_US); 303 } else { 304 if (msg->findInt64(WHATPARAM_SEEK_SEEKTIME_MS, &timeMsec) && (mPlayer != 0)) { 305 mStateFlags |= kFlagSeeking; 306 mSeekTimeMsec = (int32_t)timeMsec; 307 if (OK != mPlayer->seekTo(timeMsec)) { 308 mStateFlags &= ~kFlagSeeking; 309 mSeekTimeMsec = ANDROID_UNKNOWN_TIME; 310 } 311 } 312 } 313} 314 315 316void GenericMediaPlayer::onLoop(const sp<AMessage> &msg) { 317 SL_LOGV("GenericMediaPlayer::onLoop"); 318 int32_t loop = 0; 319 if (msg->findInt32(WHATPARAM_LOOP_LOOPING, &loop)) { 320 if (loop) { 321 mStateFlags |= kFlagLooping; 322 } else { 323 mStateFlags &= ~kFlagLooping; 324 } 325 // if we have a MediaPlayer then tell it now, otherwise we'll tell it after it's created 326 if (mPlayer != 0) { 327 (void) mPlayer->setLooping(loop); 328 } 329 } 330} 331 332 333void GenericMediaPlayer::onVolumeUpdate() { 334 SL_LOGD("GenericMediaPlayer::onVolumeUpdate()"); 335 // use settings lock to read the volume settings 336 Mutex::Autolock _l(mSettingsLock); 337 if (mPlayer != 0) { 338 mPlayer->setVolume(mAndroidAudioLevels.mFinalVolume[0], 339 mAndroidAudioLevels.mFinalVolume[1]); 340 } 341} 342 343 344void GenericMediaPlayer::onAttachAuxEffect(const sp<AMessage> &msg) { 345 SL_LOGD("GenericMediaPlayer::onAttachAuxEffect()"); 346 int32_t effectId = 0; 347 if (msg->findInt32(WHATPARAM_ATTACHAUXEFFECT, &effectId)) { 348 if (mPlayer != 0) { 349 status_t status; 350 status = mPlayer->attachAuxEffect(effectId); 351 // attachAuxEffect returns a status but we have no way to report it back to app 352 (void) status; 353 } 354 } 355} 356 357 358void GenericMediaPlayer::onSetAuxEffectSendLevel(const sp<AMessage> &msg) { 359 SL_LOGD("GenericMediaPlayer::onSetAuxEffectSendLevel()"); 360 float level = 0.0f; 361 if (msg->findFloat(WHATPARAM_SETAUXEFFECTSENDLEVEL, &level)) { 362 if (mPlayer != 0) { 363 status_t status; 364 status = mPlayer->setAuxEffectSendLevel(level); 365 // setAuxEffectSendLevel returns a status but we have no way to report it back to app 366 (void) status; 367 } 368 } 369} 370 371 372void GenericMediaPlayer::onBufferingUpdate(const sp<AMessage> &msg) { 373 int32_t fillLevel = 0; 374 if (msg->findInt32(WHATPARAM_BUFFERING_UPDATE, &fillLevel)) { 375 SL_LOGD("GenericMediaPlayer::onBufferingUpdate(fillLevel=%d)", fillLevel); 376 377 Mutex::Autolock _l(mSettingsLock); 378 mCacheFill = fillLevel; 379 // handle cache fill update 380 if (mCacheFill - mLastNotifiedCacheFill >= mCacheFillNotifThreshold) { 381 notifyCacheFill(); 382 } 383 // handle prefetch status update 384 // compute how much time ahead of position is buffered 385 int durationMsec, positionMsec = -1; 386 if ((mStateFlags & kFlagPrepared) && (mPlayer != 0) 387 && (OK == mPlayer->getDuration(&durationMsec)) 388 && (OK == mPlayer->getCurrentPosition(&positionMsec))) { 389 if ((-1 != durationMsec) && (-1 != positionMsec)) { 390 // evaluate prefetch status based on buffer time thresholds 391 int64_t bufferedDurationMsec = (durationMsec * fillLevel / 100) - positionMsec; 392 CacheStatus_t newCacheStatus = mCacheStatus; 393 if (bufferedDurationMsec > DURATION_CACHED_HIGH_MS) { 394 newCacheStatus = kStatusHigh; 395 } else if (bufferedDurationMsec > DURATION_CACHED_MED_MS) { 396 newCacheStatus = kStatusEnough; 397 } else if (bufferedDurationMsec > DURATION_CACHED_LOW_MS) { 398 newCacheStatus = kStatusIntermediate; 399 } else if (bufferedDurationMsec == 0) { 400 newCacheStatus = kStatusEmpty; 401 } else { 402 newCacheStatus = kStatusLow; 403 } 404 405 if (newCacheStatus != mCacheStatus) { 406 mCacheStatus = newCacheStatus; 407 notifyStatus(); 408 } 409 } 410 } 411 } else { 412 SL_LOGV("GenericMediaPlayer::onBufferingUpdate(fillLevel=unknown)"); 413 } 414} 415 416 417//-------------------------------------------------- 418/** 419 * called from GenericMediaPlayer::onPrepare after the MediaPlayer mPlayer is prepared successfully 420 * pre-conditions: 421 * mPlayer != 0 422 * mPlayer is prepared successfully 423 */ 424void GenericMediaPlayer::afterMediaPlayerPreparedSuccessfully() { 425 SL_LOGV("GenericMediaPlayer::afterMediaPlayerPrepared()"); 426 assert(mPlayer != 0); 427 assert(mStateFlags & kFlagPrepared); 428 // Mark this player as prepared successfully, so safe to directly call getCurrentPosition 429 { 430 Mutex::Autolock _l(mPlayerPreparedLock); 431 assert(mPlayerPrepared == 0); 432 mPlayerPrepared = mPlayer; 433 } 434 // retrieve channel count 435 assert(UNKNOWN_NUMCHANNELS == mChannelCount); 436 Parcel *reply = new Parcel(); 437 status_t status = mPlayer->getParameter(KEY_PARAMETER_AUDIO_CHANNEL_COUNT, reply); 438 if (status == NO_ERROR) { 439 mChannelCount = reply->readInt32(); 440 } else { 441 // FIXME MPEG-2 TS doesn't yet implement this key, so default to stereo 442 mChannelCount = 2; 443 } 444 if (UNKNOWN_NUMCHANNELS != mChannelCount) { 445 // now that we know the channel count, re-calculate the volumes 446 notify(PLAYEREVENT_CHANNEL_COUNT, mChannelCount, true /*async*/); 447 } else { 448 LOGW("channel count is still unknown after prepare"); 449 } 450 delete reply; 451 // retrieve duration 452 { 453 Mutex::Autolock _l(mSettingsLock); 454 int msec = 0; 455 if (OK == mPlayer->getDuration(&msec)) { 456 mDurationMsec = msec; 457 } 458 } 459 // now that we have a MediaPlayer, set the looping flag 460 if (mStateFlags & kFlagLooping) { 461 (void) mPlayer->setLooping(1); 462 } 463 // when the MediaPlayer mPlayer is prepared, there is "sufficient data" in the playback buffers 464 // if the data source was local, and the buffers are considered full so we need to notify that 465 bool isLocalSource = true; 466 if (kDataLocatorUri == mDataLocatorType) { 467 isLocalSource = !isDistantProtocol(mDataLocator.uriRef); 468 } 469 if (isLocalSource) { 470 SL_LOGD("media player prepared on local source"); 471 { 472 Mutex::Autolock _l(mSettingsLock); 473 mCacheStatus = kStatusHigh; 474 mCacheFill = 1000; 475 notifyStatus(); 476 notifyCacheFill(); 477 } 478 } else { 479 SL_LOGD("media player prepared on non-local source"); 480 } 481} 482 483 484//-------------------------------------------------- 485// If player is prepared successfully, set output parameter to that reference, otherwise NULL 486void GenericMediaPlayer::getPlayerPrepared(sp<IMediaPlayer> &playerPrepared) 487{ 488 Mutex::Autolock _l(mPlayerPreparedLock); 489 playerPrepared = mPlayerPrepared; 490} 491 492} // namespace android 493