android_StreamPlayer.cpp revision 251f90a1a07a721e873a5bfbee96a11cfc33b200
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 if (mAndroidBufferQueue->mState.count != 0) { 138 // SL_LOGD("nbBuffers in ABQ = %u, buffSize=%u",abq->mState.count, buffSize); 139 assert(mAndroidBufferQueue->mFront != mAndroidBufferQueue->mRear); 140 141 oldFront = mAndroidBufferQueue->mFront; 142 AdvancedBufferHeader *newFront = &oldFront[1]; 143 144 // consume events when starting to read data from a buffer for the first time 145 if (oldFront->mDataSizeConsumed == 0) { 146 // note this code assumes at most one event per buffer; see IAndroidBufferQueue_Enqueue 147 if (oldFront->mItems.mTsCmdData.mTsCmdCode & ANDROID_MP2TSEVENT_EOS) { 148 receivedCmd_l(IStreamListener::EOS); 149 } else if (oldFront->mItems.mTsCmdData.mTsCmdCode & ANDROID_MP2TSEVENT_DISCONTINUITY) { 150 receivedCmd_l(IStreamListener::DISCONTINUITY); 151 } else if (oldFront->mItems.mTsCmdData.mTsCmdCode & ANDROID_MP2TSEVENT_DISCON_NEWPTS) { 152 sp<AMessage> msg = new AMessage(); 153 msg->setInt64(IStreamListener::kKeyResumeAtPTS, 154 (int64_t)oldFront->mItems.mTsCmdData.mPts); 155 receivedCmd_l(IStreamListener::DISCONTINUITY, msg /*msg*/); 156 } else if (oldFront->mItems.mTsCmdData.mTsCmdCode & ANDROID_MP2TSEVENT_FORMAT_CHANGE) { 157 sp<AMessage> msg = new AMessage(); 158 // positive value for format change key makes the discontinuity "hard", see key def 159 msg->setInt32(IStreamListener::kKeyFormatChange, (int32_t) 1); 160 receivedCmd_l(IStreamListener::DISCONTINUITY, msg /*msg*/); 161 } 162 oldFront->mItems.mTsCmdData.mTsCmdCode = ANDROID_MP2TSEVENT_NONE; 163 } 164 165 { 166 // we're going to change the shared mem buffer queue, so lock it 167 Mutex::Autolock _l(mLock); 168 if (!mAvailableBuffers.empty()) { 169 bufferId = *mAvailableBuffers.begin(); 170 CHECK_LT(bufferId, mBuffers.size()); 171 sp<IMemory> mem = mBuffers.itemAt(bufferId); 172 bufferLoc = mem->pointer(); 173 buffSize = mem->size(); 174 175 char *pSrc = ((char*)oldFront->mDataBuffer) + oldFront->mDataSizeConsumed; 176 if (oldFront->mDataSizeConsumed + buffSize < oldFront->mDataSize) { 177 // more available than requested, copy as much as requested 178 // consume data: 1/ copy to given destination 179 memcpy(bufferLoc, pSrc, buffSize); 180 // 2/ keep track of how much has been consumed 181 oldFront->mDataSizeConsumed += buffSize; 182 // 3/ notify shared mem listener that new data is available 183 receivedBuffer_l(bufferId, buffSize); 184 mAvailableBuffers.erase(mAvailableBuffers.begin()); 185 } else { 186 // requested as much available or more: consume the whole of the current 187 // buffer and move to the next 188 size_t consumed = oldFront->mDataSize - oldFront->mDataSizeConsumed; 189 //SL_LOGD("consuming rest of buffer: enqueueing=%u", consumed); 190 oldFront->mDataSizeConsumed = oldFront->mDataSize; 191 192 // move queue to next 193 if (newFront == &mAndroidBufferQueue-> 194 mBufferArray[mAndroidBufferQueue->mNumBuffers + 1]) { 195 // reached the end, circle back 196 newFront = mAndroidBufferQueue->mBufferArray; 197 } 198 mAndroidBufferQueue->mFront = newFront; 199 mAndroidBufferQueue->mState.count--; 200 mAndroidBufferQueue->mState.index++; 201 202 if (consumed > 0) { 203 // consume data: 1/ copy to given destination 204 memcpy(bufferLoc, pSrc, consumed); 205 // 2/ keep track of how much has been consumed 206 // here nothing to do because we are done with this buffer 207 // 3/ notify StreamPlayer that new data is available 208 receivedBuffer_l(bufferId, consumed); 209 mAvailableBuffers.erase(mAvailableBuffers.begin()); 210 } 211 212 // data has been consumed, and the buffer queue state has been updated 213 // we will notify the client if applicable 214 if (mAndroidBufferQueue->mCallbackEventsMask & 215 SL_ANDROIDBUFFERQUEUEEVENT_PROCESSED) { 216 callback = mAndroidBufferQueue->mCallback; 217 // save callback data while under lock 218 callbackPContext = mAndroidBufferQueue->mContext; 219 pBufferContext = (void *)oldFront->mBufferContext; 220 pBufferData = (void *)oldFront->mDataBuffer; 221 dataSize = oldFront->mDataSize; 222 // here a buffer is only dequeued when fully consumed 223 //dataUsed = oldFront->mDataSizeConsumed; 224 } 225 } 226 //SL_LOGD("%d buffers available after enqueue", mAvailableBuffers.size()); 227 if (!mAvailableBuffers.empty()) { 228 // there is still room in the shared memory, recheck later if we can pull 229 // data from the buffer queue and write it to shared memory 230 mPlayer->queueRefilled(); 231 } 232 } 233 } 234 235 236 } else { // empty queue 237 SL_LOGD("ABQ empty, starving!"); 238 // signal we're at the end of the content, but don't pause (see note in function) 239 if (mUserIsAudioPlayer) { 240 // FIXME declare this external 241 //audioPlayer_dispatch_headAtEnd_lockPlay((CAudioPlayer*)user, 242 // false /*set state to paused?*/, false); 243 } else { 244 // FIXME implement headAtEnd dispatch for CMediaPlayer 245 } 246 } 247 248 interface_unlock_exclusive(mAndroidBufferQueue); 249 250 // notify client 251 if (NULL != callback) { 252 SLresult result = (*callback)(&mAndroidBufferQueue->mItf, callbackPContext, 253 pBufferContext, pBufferData, dataSize, 254 dataSize, /* dataUsed */ 255 // no messages during playback other than marking the buffer as processed 256 (const SLAndroidBufferItem*)(&kItemProcessed) /* pItems */, 257 NB_BUFFEREVENT_ITEM_FIELDS *sizeof(SLuint32) /* itemsLength */ ); 258 if (SL_RESULT_SUCCESS != result) { 259 // Reserved for future use 260 SL_LOGW("Unsuccessful result %d returned from AndroidBufferQueueCallback", result); 261 } 262 } 263 264 mCallbackProtector->exitCb(); 265 } // enterCbIfOk 266} 267 268 269//-------------------------------------------------------------------------------------------------- 270StreamPlayer::StreamPlayer(AudioPlayback_Parameters* params, bool hasVideo) : 271 GenericMediaPlayer(params, hasVideo), 272 mAppProxy(0) 273{ 274 SL_LOGD("StreamPlayer::StreamPlayer()"); 275 276 mPlaybackParams = *params; 277 278} 279 280StreamPlayer::~StreamPlayer() { 281 SL_LOGD("StreamPlayer::~StreamPlayer()"); 282 283 mAppProxy.clear(); 284} 285 286 287void StreamPlayer::onMessageReceived(const sp<AMessage> &msg) { 288 switch (msg->what()) { 289 case kWhatPullFromAbq: 290 onPullFromAndroidBufferQueue(); 291 break; 292 293 default: 294 GenericMediaPlayer::onMessageReceived(msg); 295 break; 296 } 297} 298 299 300void StreamPlayer::registerQueueCallback( 301 const void* user, bool userIsAudioPlayer, 302 void *context, 303 const void *caller) { 304 SL_LOGD("StreamPlayer::registerQueueCallback"); 305 Mutex::Autolock _l(mAppProxyLock); 306 307 mAppProxy = new StreamSourceAppProxy( 308 user, userIsAudioPlayer, 309 context, caller, mCallbackProtector, this); 310 311 CHECK(mAppProxy != 0); 312 SL_LOGD("StreamPlayer::registerQueueCallback end"); 313} 314 315 316/** 317 * Asynchronously notify the player that the queue is ready to be pulled from. 318 */ 319void StreamPlayer::queueRefilled() { 320 // async notification that the ABQ was refilled: the player should pull from the ABQ, and 321 // and push to shared memory (to the media server) 322 (new AMessage(kWhatPullFromAbq, id()))->post(); 323} 324 325 326void StreamPlayer::appClear_l() { 327 // the user of StreamPlayer has cleared its AndroidBufferQueue: 328 // there's no clear() for the shared memory queue, so this is a no-op 329} 330 331 332//-------------------------------------------------- 333// Event handlers 334void StreamPlayer::onPrepare() { 335 SL_LOGD("StreamPlayer::onPrepare()"); 336 Mutex::Autolock _l(mAppProxyLock); 337 if (mAppProxy != 0) { 338 sp<IMediaPlayerService> mediaPlayerService(getMediaPlayerService()); 339 if (mediaPlayerService != NULL) { 340 mPlayer = mediaPlayerService->create(getpid(), mPlayerClient /*IMediaPlayerClient*/, 341 mPlaybackParams.sessionId); 342 if (mPlayer == NULL) { 343 SL_LOGE("media player service failed to create player by app proxy"); 344 } else if (mPlayer->setDataSource(mAppProxy /*IStreamSource*/) != NO_ERROR) { 345 SL_LOGE("setDataSource failed"); 346 mPlayer.clear(); 347 } 348 } 349 } else { 350 SL_LOGE("Nothing to do here because there is no registered callback"); 351 } 352 if (mPlayer == NULL) { 353 mStateFlags |= kFlagPreparedUnsuccessfully; 354 } 355 GenericMediaPlayer::onPrepare(); 356 SL_LOGD("StreamPlayer::onPrepare() done"); 357} 358 359 360void StreamPlayer::onPlay() { 361 SL_LOGD("StreamPlayer::onPlay()"); 362 // enqueue a message that will cause StreamAppProxy to consume from the queue (again if the 363 // player had starved the shared memory) 364 queueRefilled(); 365 366 GenericMediaPlayer::onPlay(); 367} 368 369 370void StreamPlayer::onPullFromAndroidBufferQueue() { 371 //SL_LOGD("StreamPlayer::onQueueRefilled()"); 372 Mutex::Autolock _l(mAppProxyLock); 373 if (mAppProxy != 0) { 374 mAppProxy->pullFromBuffQueue(); 375 } 376} 377 378} // namespace android 379