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