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