android_StreamPlayer.cpp revision 4d919aa2a89c65869058a98efcaf9066eab8c125
1/* 2 * Copyright (C) 2010 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_StreamPlayer.h" 21 22#include <media/IStreamSource.h> 23#include <media/IMediaPlayerService.h> 24#include <media/stagefright/foundation/ADebug.h> 25#include <binder/IPCThreadState.h> 26 27#include "mpeg2ts/ATSParser.h" 28 29//-------------------------------------------------------------------------------------------------- 30namespace android { 31 32StreamSourceAppProxy::StreamSourceAppProxy( 33 IAndroidBufferQueue *androidBufferQueue, 34 const sp<CallbackProtector> &callbackProtector, 35 // sp<StreamPlayer> would cause StreamPlayer's destructor to run during it's own 36 // construction. If you pass in a sp<> to 'this' inside a constructor, then first the 37 // refcount is increased from 0 to 1, then decreased from 1 to 0, which causes the object's 38 // destructor to run from inside it's own constructor. 39 StreamPlayer * /* const sp<StreamPlayer> & */ player) : 40 mBuffersHasBeenSet(false), 41 mAndroidBufferQueue(androidBufferQueue), 42 mCallbackProtector(callbackProtector), 43 mPlayer(player) 44{ 45 SL_LOGV("StreamSourceAppProxy::StreamSourceAppProxy()"); 46} 47 48StreamSourceAppProxy::~StreamSourceAppProxy() { 49 SL_LOGV("StreamSourceAppProxy::~StreamSourceAppProxy()"); 50 disconnect(); 51} 52 53const SLuint32 StreamSourceAppProxy::kItemProcessed[NB_BUFFEREVENT_ITEM_FIELDS] = { 54 SL_ANDROID_ITEMKEY_BUFFERQUEUEEVENT, // item key 55 sizeof(SLuint32), // item size 56 SL_ANDROIDBUFFERQUEUEEVENT_PROCESSED // item data 57}; 58 59//-------------------------------------------------- 60// IStreamSource implementation 61void StreamSourceAppProxy::setListener(const sp<IStreamListener> &listener) { 62 assert(listener != NULL); 63 Mutex::Autolock _l(mLock); 64 assert(mListener == NULL); 65 mListener = listener; 66} 67 68void StreamSourceAppProxy::setBuffers(const Vector<sp<IMemory> > &buffers) { 69 Mutex::Autolock _l(mLock); 70 assert(!mBuffersHasBeenSet); 71 mBuffers = buffers; 72 mBuffersHasBeenSet = true; 73} 74 75void StreamSourceAppProxy::onBufferAvailable(size_t index) { 76 //SL_LOGD("StreamSourceAppProxy::onBufferAvailable(%d)", index); 77 78 { 79 Mutex::Autolock _l(mLock); 80 // assert not needed because if not set, size() will be zero and the CHECK_LT will also fail 81 // assert(mBuffersHasBeenSet); 82 CHECK_LT(index, mBuffers.size()); 83#if 0 // enable if needed for debugging 84 sp<IMemory> mem = mBuffers.itemAt(index); 85 SLAint64 length = (SLAint64) mem->size(); 86#endif 87 mAvailableBuffers.push_back(index); 88 //SL_LOGD("onBufferAvailable() now %d buffers available in queue", 89 // mAvailableBuffers.size()); 90 } 91 92 // a new shared mem buffer is available: let's try to fill immediately 93 pullFromBuffQueue(); 94} 95 96void StreamSourceAppProxy::receivedCmd_l(IStreamListener::Command cmd, const sp<AMessage> &msg) { 97 if (mListener != 0) { 98 mListener->issueCommand(cmd, false /* synchronous */, msg); 99 } 100} 101 102void StreamSourceAppProxy::receivedBuffer_l(size_t buffIndex, size_t buffLength) { 103 if (mListener != 0) { 104 mListener->queueBuffer(buffIndex, buffLength); 105 } 106} 107 108void StreamSourceAppProxy::disconnect() { 109 Mutex::Autolock _l(mLock); 110 mListener.clear(); 111 // Force binder to push the decremented reference count for sp<IStreamListener>. 112 // mediaserver and client both have sp<> to the other. When you decrement an sp<> 113 // reference count, binder doesn't push that to the other process immediately. 114 IPCThreadState::self()->flushCommands(); 115 mBuffers.clear(); 116 mBuffersHasBeenSet = false; 117 mAvailableBuffers.clear(); 118} 119 120//-------------------------------------------------- 121// consumption from ABQ: pull from the ABQ, and push to shared memory (media server) 122void StreamSourceAppProxy::pullFromBuffQueue() { 123 124 if (android::CallbackProtector::enterCbIfOk(mCallbackProtector)) { 125 126 size_t bufferId; 127 void* bufferLoc; 128 size_t buffSize; 129 130 slAndroidBufferQueueCallback callback = NULL; 131 void* pBufferContext, *pBufferData, *callbackPContext = NULL; 132 AdvancedBufferHeader *oldFront = NULL; 133 uint32_t dataSize /* , dataUsed */; 134 135 // retrieve data from the buffer queue 136 interface_lock_exclusive(mAndroidBufferQueue); 137 138 // can this read operation cause us to call the buffer queue callback 139 // (either because there was a command with no data, or all the data has been consumed) 140 bool queueCallbackCandidate = false; 141 142 if (mAndroidBufferQueue->mState.count != 0) { 143 // SL_LOGD("nbBuffers in ABQ = %u, buffSize=%u",abq->mState.count, buffSize); 144 assert(mAndroidBufferQueue->mFront != mAndroidBufferQueue->mRear); 145 146 oldFront = mAndroidBufferQueue->mFront; 147 AdvancedBufferHeader *newFront = &oldFront[1]; 148 149 // consume events when starting to read data from a buffer for the first time 150 if (oldFront->mDataSizeConsumed == 0) { 151 // note this code assumes at most one event per buffer; see IAndroidBufferQueue_Enqueue 152 if (oldFront->mItems.mTsCmdData.mTsCmdCode & ANDROID_MP2TSEVENT_EOS) { 153 receivedCmd_l(IStreamListener::EOS); 154 // EOS has no associated data 155 queueCallbackCandidate = true; 156 } else if (oldFront->mItems.mTsCmdData.mTsCmdCode & ANDROID_MP2TSEVENT_DISCONTINUITY) { 157 receivedCmd_l(IStreamListener::DISCONTINUITY); 158 } else if (oldFront->mItems.mTsCmdData.mTsCmdCode & ANDROID_MP2TSEVENT_DISCON_NEWPTS) { 159 sp<AMessage> msg = new AMessage(); 160 msg->setInt64(IStreamListener::kKeyResumeAtPTS, 161 (int64_t)oldFront->mItems.mTsCmdData.mPts); 162 receivedCmd_l(IStreamListener::DISCONTINUITY, msg /*msg*/); 163 } else if (oldFront->mItems.mTsCmdData.mTsCmdCode & ANDROID_MP2TSEVENT_FORMAT_CHANGE) { 164 sp<AMessage> msg = new AMessage(); 165 // positive value for format change key makes the discontinuity "hard", see key def 166 msg->setInt32( 167 IStreamListener::kKeyDiscontinuityMask, 168 ATSParser::DISCONTINUITY_FORMATCHANGE); 169 170 receivedCmd_l(IStreamListener::DISCONTINUITY, msg /*msg*/); 171 } 172 if (oldFront->mItems.mTsCmdData.mTsCmdCode & (ANDROID_MP2TSEVENT_DISCONTINUITY | 173 ANDROID_MP2TSEVENT_DISCON_NEWPTS | ANDROID_MP2TSEVENT_FORMAT_CHANGE)) { 174 const sp<StreamPlayer> player(mPlayer.promote()); 175 if (player != NULL) { 176 // FIXME see note at onSeek 177 player->seek(ANDROID_UNKNOWN_TIME); 178 } 179 } 180 oldFront->mItems.mTsCmdData.mTsCmdCode = ANDROID_MP2TSEVENT_NONE; 181 } 182 183 { 184 // we're going to change the shared mem buffer queue, so lock it 185 Mutex::Autolock _l(mLock); 186 if (!mAvailableBuffers.empty()) { 187 bufferId = *mAvailableBuffers.begin(); 188 CHECK_LT(bufferId, mBuffers.size()); 189 sp<IMemory> mem = mBuffers.itemAt(bufferId); 190 bufferLoc = mem->pointer(); 191 buffSize = mem->size(); 192 193 char *pSrc = ((char*)oldFront->mDataBuffer) + oldFront->mDataSizeConsumed; 194 if (oldFront->mDataSizeConsumed + buffSize < oldFront->mDataSize) { 195 // more available than requested, copy as much as requested 196 // consume data: 1/ copy to given destination 197 memcpy(bufferLoc, pSrc, buffSize); 198 // 2/ keep track of how much has been consumed 199 oldFront->mDataSizeConsumed += buffSize; 200 // 3/ notify shared mem listener that new data is available 201 receivedBuffer_l(bufferId, buffSize); 202 mAvailableBuffers.erase(mAvailableBuffers.begin()); 203 } else { 204 // requested as much available or more: consume the whole of the current 205 // buffer and move to the next 206 size_t consumed = oldFront->mDataSize - oldFront->mDataSizeConsumed; 207 //SL_LOGD("consuming rest of buffer: enqueueing=%u", consumed); 208 oldFront->mDataSizeConsumed = oldFront->mDataSize; 209 210 // move queue to next 211 if (newFront == &mAndroidBufferQueue-> 212 mBufferArray[mAndroidBufferQueue->mNumBuffers + 1]) { 213 // reached the end, circle back 214 newFront = mAndroidBufferQueue->mBufferArray; 215 } 216 mAndroidBufferQueue->mFront = newFront; 217 mAndroidBufferQueue->mState.count--; 218 mAndroidBufferQueue->mState.index++; 219 220 if (consumed > 0) { 221 // consume data: 1/ copy to given destination 222 memcpy(bufferLoc, pSrc, consumed); 223 // 2/ keep track of how much has been consumed 224 // here nothing to do because we are done with this buffer 225 // 3/ notify StreamPlayer that new data is available 226 receivedBuffer_l(bufferId, consumed); 227 mAvailableBuffers.erase(mAvailableBuffers.begin()); 228 } 229 230 // data has been consumed, and the buffer queue state has been updated 231 // we will notify the client if applicable 232 queueCallbackCandidate = true; 233 } 234 } 235 236 if (queueCallbackCandidate) { 237 if (mAndroidBufferQueue->mCallbackEventsMask & 238 SL_ANDROIDBUFFERQUEUEEVENT_PROCESSED) { 239 callback = mAndroidBufferQueue->mCallback; 240 // save callback data while under lock 241 callbackPContext = mAndroidBufferQueue->mContext; 242 pBufferContext = (void *)oldFront->mBufferContext; 243 pBufferData = (void *)oldFront->mDataBuffer; 244 dataSize = oldFront->mDataSize; 245 // here a buffer is only dequeued when fully consumed 246 //dataUsed = oldFront->mDataSizeConsumed; 247 } 248 } 249 //SL_LOGD("%d buffers available after reading from queue", mAvailableBuffers.size()); 250 if (!mAvailableBuffers.empty()) { 251 // there is still room in the shared memory, recheck later if we can pull 252 // data from the buffer queue and write it to shared memory 253 const sp<StreamPlayer> player(mPlayer.promote()); 254 if (player != NULL) { 255 player->queueRefilled(); 256 } 257 } 258 } 259 260 } else { // empty queue 261 SL_LOGD("ABQ empty, starving!"); 262 } 263 264 interface_unlock_exclusive(mAndroidBufferQueue); 265 266 // notify client of buffer processed 267 if (NULL != callback) { 268 SLresult result = (*callback)(&mAndroidBufferQueue->mItf, callbackPContext, 269 pBufferContext, pBufferData, dataSize, 270 dataSize, /* dataUsed */ 271 // no messages during playback other than marking the buffer as processed 272 (const SLAndroidBufferItem*)(&kItemProcessed) /* pItems */, 273 NB_BUFFEREVENT_ITEM_FIELDS *sizeof(SLuint32) /* itemsLength */ ); 274 if (SL_RESULT_SUCCESS != result) { 275 // Reserved for future use 276 SL_LOGW("Unsuccessful result %d returned from AndroidBufferQueueCallback", result); 277 } 278 } 279 280 mCallbackProtector->exitCb(); 281 } // enterCbIfOk 282} 283 284 285//-------------------------------------------------------------------------------------------------- 286StreamPlayer::StreamPlayer(const AudioPlayback_Parameters* params, bool hasVideo, 287 IAndroidBufferQueue *androidBufferQueue, const sp<CallbackProtector> &callbackProtector) : 288 GenericMediaPlayer(params, hasVideo), 289 mAppProxy(new StreamSourceAppProxy(androidBufferQueue, callbackProtector, this)), 290 mStopForDestroyCompleted(false) 291{ 292 SL_LOGD("StreamPlayer::StreamPlayer()"); 293} 294 295StreamPlayer::~StreamPlayer() { 296 SL_LOGD("StreamPlayer::~StreamPlayer()"); 297 mAppProxy->disconnect(); 298} 299 300 301void StreamPlayer::onMessageReceived(const sp<AMessage> &msg) { 302 switch (msg->what()) { 303 case kWhatPullFromAbq: 304 onPullFromAndroidBufferQueue(); 305 break; 306 307 case kWhatStopForDestroy: 308 onStopForDestroy(); 309 break; 310 311 default: 312 GenericMediaPlayer::onMessageReceived(msg); 313 break; 314 } 315} 316 317 318void StreamPlayer::preDestroy() { 319 // FIXME NuPlayerDriver is currently not thread-safe, so stop() must be called by looper 320 (new AMessage(kWhatStopForDestroy, id()))->post(); 321 { 322 Mutex::Autolock _l(mStopForDestroyLock); 323 while (!mStopForDestroyCompleted) { 324 mStopForDestroyCondition.wait(mStopForDestroyLock); 325 } 326 } 327 // GenericMediaPlayer::preDestroy will repeat some of what we've done, but that's benign 328 GenericMediaPlayer::preDestroy(); 329} 330 331 332void StreamPlayer::onStopForDestroy() { 333 if (mPlayer != 0) { 334 mPlayer->stop(); 335 // causes CHECK failure in Nuplayer 336 //mPlayer->setDataSource(NULL); 337 mPlayer->setVideoSurfaceTexture(NULL); 338 mPlayer->disconnect(); 339 mPlayer.clear(); 340 { 341 // FIXME ugh make this a method 342 Mutex::Autolock _l(mPreparedPlayerLock); 343 mPreparedPlayer.clear(); 344 } 345 } 346 { 347 Mutex::Autolock _l(mStopForDestroyLock); 348 mStopForDestroyCompleted = true; 349 } 350 mStopForDestroyCondition.signal(); 351} 352 353 354/** 355 * Asynchronously notify the player that the queue is ready to be pulled from. 356 */ 357void StreamPlayer::queueRefilled() { 358 // async notification that the ABQ was refilled: the player should pull from the ABQ, and 359 // and push to shared memory (to the media server) 360 (new AMessage(kWhatPullFromAbq, id()))->post(); 361} 362 363 364void StreamPlayer::appClear_l() { 365 // the user of StreamPlayer has cleared its AndroidBufferQueue: 366 // there's no clear() for the shared memory queue, so this is a no-op 367} 368 369 370//-------------------------------------------------- 371// Event handlers 372void StreamPlayer::onPrepare() { 373 SL_LOGD("StreamPlayer::onPrepare()"); 374 sp<IMediaPlayerService> mediaPlayerService(getMediaPlayerService()); 375 if (mediaPlayerService != NULL) { 376 mPlayer = mediaPlayerService->create(getpid(), mPlayerClient /*IMediaPlayerClient*/, 377 mPlaybackParams.sessionId); 378 if (mPlayer == NULL) { 379 SL_LOGE("media player service failed to create player by app proxy"); 380 } else if (mPlayer->setDataSource(mAppProxy /*IStreamSource*/) != NO_ERROR) { 381 SL_LOGE("setDataSource failed"); 382 mPlayer.clear(); 383 } 384 } 385 if (mPlayer == NULL) { 386 mStateFlags |= kFlagPreparedUnsuccessfully; 387 } 388 GenericMediaPlayer::onPrepare(); 389 SL_LOGD("StreamPlayer::onPrepare() done"); 390} 391 392 393void StreamPlayer::onPlay() { 394 SL_LOGD("StreamPlayer::onPlay()"); 395 // enqueue a message that will cause StreamAppProxy to consume from the queue (again if the 396 // player had starved the shared memory) 397 queueRefilled(); 398 399 GenericMediaPlayer::onPlay(); 400} 401 402 403void StreamPlayer::onPullFromAndroidBufferQueue() { 404 SL_LOGD("StreamPlayer::onPullFromAndroidBufferQueue()"); 405 mAppProxy->pullFromBuffQueue(); 406} 407 408} // namespace android 409