android_GenericMediaPlayer.cpp revision 4b0e0b2860ffd5e246b42c8a434833cca2f068b3
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 27namespace android { 28 29// default delay in Us used when reposting an event when the player is not ready to accept 30// the command yet. This is for instance used when seeking on a MediaPlayer that's still preparing 31#define DEFAULT_COMMAND_DELAY_FOR_REPOST_US (100*1000) // 100ms 32 33static const char* const kDistantProtocolPrefix[] = { "http:", "https:", "ftp:", "rtp:", "rtsp:"}; 34#define NB_DISTANT_PROTOCOLS (sizeof(kDistantProtocolPrefix)/sizeof(kDistantProtocolPrefix[0])) 35 36//-------------------------------------------------------------------------------------------------- 37MediaPlayerNotificationClient::MediaPlayerNotificationClient(GenericMediaPlayer* gmp) : 38 mGenericMediaPlayer(gmp), 39 mPlayerPrepared(false) 40{ 41 42} 43 44MediaPlayerNotificationClient::~MediaPlayerNotificationClient() { 45 46} 47 48//-------------------------------------------------- 49// IMediaPlayerClient implementation 50void MediaPlayerNotificationClient::notify(int msg, int ext1, int ext2, const Parcel *obj) { 51 SL_LOGV("MediaPlayerNotificationClient::notify(msg=%d, ext1=%d, ext2=%d)", msg, ext1, ext2); 52 53 switch (msg) { 54 case MEDIA_PREPARED: 55 mPlayerPrepared = true; 56 mPlayerPreparedCondition.signal(); 57 break; 58 59 case MEDIA_SET_VIDEO_SIZE: 60 // only send video size updates if the player was flagged as having video, to avoid 61 // sending video size updates of (0,0) 62 if (mGenericMediaPlayer->mHasVideo) { 63 mGenericMediaPlayer->notify(PLAYEREVENT_VIDEO_SIZE_UPDATE, 64 (int32_t)ext1, (int32_t)ext2, true /*async*/); 65 } 66 break; 67 68 case MEDIA_SEEK_COMPLETE: 69 mGenericMediaPlayer->seekComplete(); 70 break; 71 72 case MEDIA_PLAYBACK_COMPLETE: 73 mGenericMediaPlayer->notify(PLAYEREVENT_ENDOFSTREAM, 1, true /*async*/); 74 break; 75 76 case MEDIA_BUFFERING_UPDATE: 77 // values received from Android framework for buffer fill level use percent, 78 // while SL/XA use permille, so does GenericPlayer 79 mGenericMediaPlayer->bufferingUpdate(ext1 * 10 /*fillLevelPerMille*/); 80 break; 81 82 default: { } 83 } 84} 85 86//-------------------------------------------------- 87void MediaPlayerNotificationClient::blockUntilPlayerPrepared() { 88 Mutex::Autolock _l(mLock); 89 while (!mPlayerPrepared) { 90 mPlayerPreparedCondition.wait(mLock); 91 } 92} 93 94//-------------------------------------------------------------------------------------------------- 95GenericMediaPlayer::GenericMediaPlayer(const AudioPlayback_Parameters* params, bool hasVideo) : 96 GenericPlayer(params), 97 mHasVideo(hasVideo), 98 mSeekTimeMsec(0), 99 mVideoSurface(0), 100 mVideoSurfaceTexture(0), 101 mPlayer(0), 102 mPlayerClient(0), 103 mGetMediaPlayerInfoGenCount(0) 104{ 105 SL_LOGD("GenericMediaPlayer::GenericMediaPlayer()"); 106 107 mServiceManager = defaultServiceManager(); 108 mBinder = mServiceManager->getService(String16("media.player")); 109 mMediaPlayerService = interface_cast<IMediaPlayerService>(mBinder); 110 111 CHECK(mMediaPlayerService.get() != NULL); 112 113 mPlayerClient = new MediaPlayerNotificationClient(this); 114} 115 116GenericMediaPlayer::~GenericMediaPlayer() { 117 SL_LOGD("GenericMediaPlayer::~GenericMediaPlayer()"); 118} 119 120void GenericMediaPlayer::preDestroy() { 121 // we might be in the middle of blocking for a getXXX call 122 { 123 android::Mutex::Autolock autoLock(mGetMediaPlayerInfoLock); 124 mGetMediaPlayerInfoGenCount++; 125 mGetMediaPlayerInfoCondition.broadcast(); 126 } 127 GenericPlayer::preDestroy(); 128} 129 130//-------------------------------------------------- 131// overridden from GenericPlayer 132// pre-condition: 133// msec != NULL 134// post-condition 135// *msec == mPositionMsec == 136// ANDROID_UNKNOWN_TIME if position is unknown at time of query, 137// or the current MediaPlayer position 138void GenericMediaPlayer::getPositionMsec(int* msec) { 139 SL_LOGD("GenericMediaPlayer::getPositionMsec()"); 140 uint32_t currentGen = 0; 141 { 142 android::Mutex::Autolock autoLock(mGetMediaPlayerInfoLock); 143 currentGen = mGetMediaPlayerInfoGenCount; 144 } 145 // send a message to update the MediaPlayer position in the event loop where it's safe to 146 // access the MediaPlayer. We block until the message kWhatMediaPlayerInfo has been processed 147 (new AMessage(kWhatMediaPlayerInfo, id()))->post(); 148 { 149 android::Mutex::Autolock autoLock(mGetMediaPlayerInfoLock); 150 // mGetMediaPlayerInfoGenCount will be incremented when the kWhatMediaPlayerInfo 151 // gets processed. 152 while (currentGen == mGetMediaPlayerInfoGenCount) { 153 mGetMediaPlayerInfoCondition.wait(mGetMediaPlayerInfoLock); 154 // if multiple GetPosition calls were issued before any got processed on the event queue 155 // then they will all return the same "recent-enough" position 156 } 157 // at this point mPositionMsec has been updated 158 // so now updates msec from mPositionMsec, while holding the lock protecting it 159 GenericPlayer::getPositionMsec(msec); 160 } 161} 162 163//-------------------------------------------------- 164void GenericMediaPlayer::setVideoSurface(const sp<Surface> &surface) { 165 mVideoSurface = surface; 166} 167 168void GenericMediaPlayer::setVideoSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) { 169 mVideoSurfaceTexture = surfaceTexture; 170} 171 172//-------------------------------------------------- 173void GenericMediaPlayer::onMessageReceived(const sp<AMessage> &msg) { 174 switch (msg->what()) { 175 case kWhatMediaPlayerInfo: 176 onGetMediaPlayerInfo(); 177 break; 178 179 default: 180 GenericPlayer::onMessageReceived(msg); 181 break; 182 } 183} 184 185//-------------------------------------------------- 186// Event handlers 187 188void GenericMediaPlayer::onPrepare() { 189 SL_LOGD("GenericMediaPlayer::onPrepare()"); 190 if (!(mStateFlags & kFlagPrepared) && (mPlayer != 0)) { 191 if (mHasVideo) { 192 if (mVideoSurface != 0) { 193 mPlayer->setVideoSurface(mVideoSurface); 194 } else if (mVideoSurfaceTexture != 0) { 195 mPlayer->setVideoSurfaceTexture(mVideoSurfaceTexture); 196 } 197 } 198 mPlayer->setAudioStreamType(mPlaybackParams.streamType); 199 mPlayer->prepareAsync(); 200 mPlayerClient->blockUntilPlayerPrepared(); 201 onAfterMediaPlayerPrepared(); 202 GenericPlayer::onPrepare(); 203 } 204 SL_LOGD("GenericMediaPlayer::onPrepare() done, mStateFlags=0x%x", mStateFlags); 205} 206 207 208void GenericMediaPlayer::onPlay() { 209 SL_LOGD("GenericMediaPlayer::onPlay()"); 210 if ((mStateFlags & kFlagPrepared) && (mPlayer != 0)) { 211 SL_LOGD("starting player"); 212 mPlayer->start(); 213 mStateFlags |= kFlagPlaying; 214 } else { 215 SL_LOGV("NOT starting player mStateFlags=0x%x", mStateFlags); 216 } 217} 218 219 220void GenericMediaPlayer::onPause() { 221 SL_LOGD("GenericMediaPlayer::onPause()"); 222 if ((mStateFlags & kFlagPrepared) && (mPlayer != 0)) { 223 mPlayer->pause(); 224 mStateFlags &= ~kFlagPlaying; 225 } 226} 227 228/** 229 * pre-condition: WHATPARAM_SEEK_SEEKTIME_MS parameter value >= 0 230 */ 231void GenericMediaPlayer::onSeek(const sp<AMessage> &msg) { 232 SL_LOGV("GenericMediaPlayer::onSeek"); 233 int64_t timeMsec = ANDROID_UNKNOWN_TIME; 234 if (!msg->findInt64(WHATPARAM_SEEK_SEEKTIME_MS, &timeMsec)) { 235 // invalid command, drop it 236 return; 237 } 238 if ((mStateFlags & kFlagSeeking) && (timeMsec == mSeekTimeMsec)) { 239 // already seeking to the same time, cancel this command 240 return; 241 } else if (!(mStateFlags & kFlagPrepared)) { 242 // we are not ready to accept a seek command at this time, retry later 243 msg->post(DEFAULT_COMMAND_DELAY_FOR_REPOST_US); 244 } else { 245 if (msg->findInt64(WHATPARAM_SEEK_SEEKTIME_MS, &timeMsec) && (mPlayer != 0)) { 246 mStateFlags |= kFlagSeeking; 247 mSeekTimeMsec = (int32_t)timeMsec; 248 if (OK != mPlayer->seekTo(timeMsec)) { 249 mStateFlags &= ~kFlagSeeking; 250 mSeekTimeMsec = ANDROID_UNKNOWN_TIME; 251 } else { 252 mPositionMsec = mSeekTimeMsec; 253 } 254 } 255 } 256} 257 258 259void GenericMediaPlayer::onLoop(const sp<AMessage> &msg) { 260 SL_LOGV("GenericMediaPlayer::onLoop"); 261 int32_t loop = 0; 262 if (msg->findInt32(WHATPARAM_LOOP_LOOPING, &loop)) { 263 if (mPlayer != 0 && OK == mPlayer->setLooping(loop)) { 264 if (loop) { 265 mStateFlags |= kFlagLooping; 266 } else { 267 mStateFlags &= ~kFlagLooping; 268 } 269 } 270 } 271} 272 273 274void GenericMediaPlayer::onVolumeUpdate() { 275 SL_LOGD("GenericMediaPlayer::onVolumeUpdate()"); 276 // use settings lock to read the volume settings 277 Mutex::Autolock _l(mSettingsLock); 278 if (mPlayer != 0) { 279 if (mAndroidAudioLevels.mMute) { 280 mPlayer->setVolume(0.0f, 0.0f); 281 } else { 282 mPlayer->setVolume(mAndroidAudioLevels.mFinalVolume[0], 283 mAndroidAudioLevels.mFinalVolume[1]); 284 } 285 } 286} 287 288 289void GenericMediaPlayer::onBufferingUpdate(const sp<AMessage> &msg) { 290 int32_t fillLevel = 0; 291 if (msg->findInt32(WHATPARAM_BUFFERING_UPDATE, &fillLevel)) { 292 SL_LOGD("GenericMediaPlayer::onBufferingUpdate(fillLevel=%d)", fillLevel); 293 294 Mutex::Autolock _l(mSettingsLock); 295 mCacheFill = fillLevel; 296 // handle cache fill update 297 if (mCacheFill - mLastNotifiedCacheFill >= mCacheFillNotifThreshold) { 298 notifyCacheFill(); 299 } 300 // handle prefetch status update 301 // compute how much time ahead of position is buffered 302 int durationMsec, positionMsec = -1; 303 if ((mStateFlags & kFlagPrepared) && (mPlayer != 0) 304 && (OK == mPlayer->getDuration(&durationMsec)) 305 && (OK == mPlayer->getCurrentPosition(&positionMsec))) { 306 if ((-1 != durationMsec) && (-1 != positionMsec)) { 307 // evaluate prefetch status based on buffer time thresholds 308 int64_t bufferedDurationMsec = (durationMsec * fillLevel / 100) - positionMsec; 309 CacheStatus_t newCacheStatus = mCacheStatus; 310 if (bufferedDurationMsec > DURATION_CACHED_HIGH_MS) { 311 newCacheStatus = kStatusHigh; 312 } else if (bufferedDurationMsec > DURATION_CACHED_MED_MS) { 313 newCacheStatus = kStatusEnough; 314 } else if (bufferedDurationMsec > DURATION_CACHED_LOW_MS) { 315 newCacheStatus = kStatusIntermediate; 316 } else if (bufferedDurationMsec == 0) { 317 newCacheStatus = kStatusEmpty; 318 } else { 319 newCacheStatus = kStatusLow; 320 } 321 322 if (newCacheStatus != mCacheStatus) { 323 mCacheStatus = newCacheStatus; 324 notifyStatus(); 325 } 326 } 327 } 328 } 329} 330 331 332void GenericMediaPlayer::onGetMediaPlayerInfo() { 333 SL_LOGD("GenericMediaPlayer::onGetMediaPlayerInfo()"); 334 { 335 android::Mutex::Autolock autoLock(mGetMediaPlayerInfoLock); 336 337 if ((!(mStateFlags & kFlagPrepared)) || (mPlayer == 0)) { 338 mPositionMsec = ANDROID_UNKNOWN_TIME; 339 } else { 340 mPlayer->getCurrentPosition(&mPositionMsec); 341 } 342 343 // the MediaPlayer info has been refreshed 344 mGetMediaPlayerInfoGenCount++; 345 // there might be multiple requests for MediaPlayer info, so use broadcast instead of signal 346 mGetMediaPlayerInfoCondition.broadcast(); 347 } 348} 349 350 351//-------------------------------------------------- 352/** 353 * called from the event handling loop 354 * pre-condition: mPlayer is prepared 355 */ 356void GenericMediaPlayer::onAfterMediaPlayerPrepared() { 357 // the MediaPlayer mPlayer is prepared, retrieve its duration 358 // FIXME retrieve channel count 359 { 360 Mutex::Autolock _l(mSettingsLock); 361 int msec = 0; 362 if (OK == mPlayer->getDuration(&msec)) { 363 mDurationMsec = msec; 364 } 365 } 366 // when the MediaPlayer mPlayer is prepared, there is "sufficient data" in the playback buffers 367 // if the data source was local, and the buffers are considered full so we need to notify that 368 bool isLocalSource = true; 369 if (kDataLocatorUri == mDataLocatorType) { 370 for (unsigned int i = 0 ; i < NB_DISTANT_PROTOCOLS ; i++) { 371 if (!strncasecmp(mDataLocator.uriRef, 372 kDistantProtocolPrefix[i], strlen(kDistantProtocolPrefix[i]))) { 373 isLocalSource = false; 374 break; 375 } 376 } 377 } 378 if (isLocalSource) { 379 SL_LOGD("media player prepared on local source"); 380 { 381 Mutex::Autolock _l(mSettingsLock); 382 mCacheStatus = kStatusHigh; 383 mCacheFill = 1000; 384 notifyStatus(); 385 notifyCacheFill(); 386 } 387 } else { 388 SL_LOGD("media player prepared on non-local source"); 389 } 390} 391 392} // namespace android 393