Tracks.cpp revision d054c32443a493513ab63529b0c8b1aca290278c
1/* 2** 3** Copyright 2012, The Android Open Source Project 4** 5** Licensed under the Apache License, Version 2.0 (the "License"); 6** you may not use this file except in compliance with the License. 7** You may obtain a copy of the License at 8** 9** http://www.apache.org/licenses/LICENSE-2.0 10** 11** Unless required by applicable law or agreed to in writing, software 12** distributed under the License is distributed on an "AS IS" BASIS, 13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14** See the License for the specific language governing permissions and 15** limitations under the License. 16*/ 17 18 19#define LOG_TAG "AudioFlinger" 20//#define LOG_NDEBUG 0 21 22#include "Configuration.h" 23#include <math.h> 24#include <utils/Log.h> 25 26#include <private/media/AudioTrackShared.h> 27 28#include <common_time/cc_helper.h> 29#include <common_time/local_clock.h> 30 31#include "AudioMixer.h" 32#include "AudioFlinger.h" 33#include "ServiceUtilities.h" 34 35#include <media/nbaio/Pipe.h> 36#include <media/nbaio/PipeReader.h> 37 38// ---------------------------------------------------------------------------- 39 40// Note: the following macro is used for extremely verbose logging message. In 41// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to 42// 0; but one side effect of this is to turn all LOGV's as well. Some messages 43// are so verbose that we want to suppress them even when we have ALOG_ASSERT 44// turned on. Do not uncomment the #def below unless you really know what you 45// are doing and want to see all of the extremely verbose messages. 46//#define VERY_VERY_VERBOSE_LOGGING 47#ifdef VERY_VERY_VERBOSE_LOGGING 48#define ALOGVV ALOGV 49#else 50#define ALOGVV(a...) do { } while(0) 51#endif 52 53namespace android { 54 55// ---------------------------------------------------------------------------- 56// TrackBase 57// ---------------------------------------------------------------------------- 58 59static volatile int32_t nextTrackId = 55; 60 61// TrackBase constructor must be called with AudioFlinger::mLock held 62AudioFlinger::ThreadBase::TrackBase::TrackBase( 63 ThreadBase *thread, 64 const sp<Client>& client, 65 uint32_t sampleRate, 66 audio_format_t format, 67 audio_channel_mask_t channelMask, 68 size_t frameCount, 69 const sp<IMemory>& sharedBuffer, 70 int sessionId, 71 bool isOut) 72 : RefBase(), 73 mThread(thread), 74 mClient(client), 75 mCblk(NULL), 76 // mBuffer 77 mState(IDLE), 78 mSampleRate(sampleRate), 79 mFormat(format), 80 mChannelMask(channelMask), 81 mChannelCount(popcount(channelMask)), 82 mFrameSize(audio_is_linear_pcm(format) ? 83 mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)), 84 mFrameCount(frameCount), 85 mSessionId(sessionId), 86 mIsOut(isOut), 87 mServerProxy(NULL), 88 mId(android_atomic_inc(&nextTrackId)), 89 mTerminated(false) 90{ 91 // client == 0 implies sharedBuffer == 0 92 ALOG_ASSERT(!(client == 0 && sharedBuffer != 0)); 93 94 ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(), 95 sharedBuffer->size()); 96 97 // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize); 98 size_t size = sizeof(audio_track_cblk_t); 99 size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize; 100 if (sharedBuffer == 0) { 101 size += bufferSize; 102 } 103 104 if (client != 0) { 105 mCblkMemory = client->heap()->allocate(size); 106 if (mCblkMemory != 0) { 107 mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer()); 108 // can't assume mCblk != NULL 109 } else { 110 ALOGE("not enough memory for AudioTrack size=%u", size); 111 client->heap()->dump("AudioTrack"); 112 return; 113 } 114 } else { 115 // this syntax avoids calling the audio_track_cblk_t constructor twice 116 mCblk = (audio_track_cblk_t *) new uint8_t[size]; 117 // assume mCblk != NULL 118 } 119 120 // construct the shared structure in-place. 121 if (mCblk != NULL) { 122 new(mCblk) audio_track_cblk_t(); 123 // clear all buffers 124 mCblk->frameCount_ = frameCount; 125 if (sharedBuffer == 0) { 126 mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t); 127 memset(mBuffer, 0, bufferSize); 128 } else { 129 mBuffer = sharedBuffer->pointer(); 130#if 0 131 mCblk->mFlags = CBLK_FORCEREADY; // FIXME hack, need to fix the track ready logic 132#endif 133 } 134 135#ifdef TEE_SINK 136 if (mTeeSinkTrackEnabled) { 137 NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount); 138 if (pipeFormat != Format_Invalid) { 139 Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat); 140 size_t numCounterOffers = 0; 141 const NBAIO_Format offers[1] = {pipeFormat}; 142 ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers); 143 ALOG_ASSERT(index == 0); 144 PipeReader *pipeReader = new PipeReader(*pipe); 145 numCounterOffers = 0; 146 index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers); 147 ALOG_ASSERT(index == 0); 148 mTeeSink = pipe; 149 mTeeSource = pipeReader; 150 } 151 } 152#endif 153 154 } 155} 156 157AudioFlinger::ThreadBase::TrackBase::~TrackBase() 158{ 159#ifdef TEE_SINK 160 dumpTee(-1, mTeeSource, mId); 161#endif 162 // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference 163 delete mServerProxy; 164 if (mCblk != NULL) { 165 if (mClient == 0) { 166 delete mCblk; 167 } else { 168 mCblk->~audio_track_cblk_t(); // destroy our shared-structure. 169 } 170 } 171 mCblkMemory.clear(); // free the shared memory before releasing the heap it belongs to 172 if (mClient != 0) { 173 // Client destructor must run with AudioFlinger mutex locked 174 Mutex::Autolock _l(mClient->audioFlinger()->mLock); 175 // If the client's reference count drops to zero, the associated destructor 176 // must run with AudioFlinger lock held. Thus the explicit clear() rather than 177 // relying on the automatic clear() at end of scope. 178 mClient.clear(); 179 } 180} 181 182// AudioBufferProvider interface 183// getNextBuffer() = 0; 184// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack 185void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer) 186{ 187#ifdef TEE_SINK 188 if (mTeeSink != 0) { 189 (void) mTeeSink->write(buffer->raw, buffer->frameCount); 190 } 191#endif 192 193 ServerProxy::Buffer buf; 194 buf.mFrameCount = buffer->frameCount; 195 buf.mRaw = buffer->raw; 196 buffer->frameCount = 0; 197 buffer->raw = NULL; 198 mServerProxy->releaseBuffer(&buf); 199} 200 201status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event) 202{ 203 mSyncEvents.add(event); 204 return NO_ERROR; 205} 206 207// ---------------------------------------------------------------------------- 208// Playback 209// ---------------------------------------------------------------------------- 210 211AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track) 212 : BnAudioTrack(), 213 mTrack(track) 214{ 215} 216 217AudioFlinger::TrackHandle::~TrackHandle() { 218 // just stop the track on deletion, associated resources 219 // will be freed from the main thread once all pending buffers have 220 // been played. Unless it's not in the active track list, in which 221 // case we free everything now... 222 mTrack->destroy(); 223} 224 225sp<IMemory> AudioFlinger::TrackHandle::getCblk() const { 226 return mTrack->getCblk(); 227} 228 229status_t AudioFlinger::TrackHandle::start() { 230 return mTrack->start(); 231} 232 233void AudioFlinger::TrackHandle::stop() { 234 mTrack->stop(); 235} 236 237void AudioFlinger::TrackHandle::flush() { 238 mTrack->flush(); 239} 240 241void AudioFlinger::TrackHandle::pause() { 242 mTrack->pause(); 243} 244 245status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId) 246{ 247 return mTrack->attachAuxEffect(EffectId); 248} 249 250status_t AudioFlinger::TrackHandle::allocateTimedBuffer(size_t size, 251 sp<IMemory>* buffer) { 252 if (!mTrack->isTimedTrack()) 253 return INVALID_OPERATION; 254 255 PlaybackThread::TimedTrack* tt = 256 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 257 return tt->allocateTimedBuffer(size, buffer); 258} 259 260status_t AudioFlinger::TrackHandle::queueTimedBuffer(const sp<IMemory>& buffer, 261 int64_t pts) { 262 if (!mTrack->isTimedTrack()) 263 return INVALID_OPERATION; 264 265 PlaybackThread::TimedTrack* tt = 266 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 267 return tt->queueTimedBuffer(buffer, pts); 268} 269 270status_t AudioFlinger::TrackHandle::setMediaTimeTransform( 271 const LinearTransform& xform, int target) { 272 273 if (!mTrack->isTimedTrack()) 274 return INVALID_OPERATION; 275 276 PlaybackThread::TimedTrack* tt = 277 reinterpret_cast<PlaybackThread::TimedTrack*>(mTrack.get()); 278 return tt->setMediaTimeTransform( 279 xform, static_cast<TimedAudioTrack::TargetTimeline>(target)); 280} 281 282status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) { 283 return mTrack->setParameters(keyValuePairs); 284} 285 286status_t AudioFlinger::TrackHandle::onTransact( 287 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 288{ 289 return BnAudioTrack::onTransact(code, data, reply, flags); 290} 291 292// ---------------------------------------------------------------------------- 293 294// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held 295AudioFlinger::PlaybackThread::Track::Track( 296 PlaybackThread *thread, 297 const sp<Client>& client, 298 audio_stream_type_t streamType, 299 uint32_t sampleRate, 300 audio_format_t format, 301 audio_channel_mask_t channelMask, 302 size_t frameCount, 303 const sp<IMemory>& sharedBuffer, 304 int sessionId, 305 IAudioFlinger::track_flags_t flags) 306 : TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer, 307 sessionId, true /*isOut*/), 308 mFillingUpStatus(FS_INVALID), 309 // mRetryCount initialized later when needed 310 mSharedBuffer(sharedBuffer), 311 mStreamType(streamType), 312 mName(-1), // see note below 313 mMainBuffer(thread->mixBuffer()), 314 mAuxBuffer(NULL), 315 mAuxEffectId(0), mHasVolumeController(false), 316 mPresentationCompleteFrames(0), 317 mFlags(flags), 318 mFastIndex(-1), 319 mUnderrunCount(0), 320 mCachedVolume(1.0), 321 mIsInvalid(false), 322 mAudioTrackServerProxy(NULL), 323 mResumeToStopping(false) 324{ 325 if (mCblk != NULL) { 326 if (sharedBuffer == 0) { 327 mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount, 328 mFrameSize); 329 } else { 330 mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount, 331 mFrameSize); 332 } 333 mServerProxy = mAudioTrackServerProxy; 334 // to avoid leaking a track name, do not allocate one unless there is an mCblk 335 mName = thread->getTrackName_l(channelMask, sessionId); 336 if (mName < 0) { 337 ALOGE("no more track names available"); 338 return; 339 } 340 // only allocate a fast track index if we were able to allocate a normal track name 341 if (flags & IAudioFlinger::TRACK_FAST) { 342 mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads(); 343 ALOG_ASSERT(thread->mFastTrackAvailMask != 0); 344 int i = __builtin_ctz(thread->mFastTrackAvailMask); 345 ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks); 346 // FIXME This is too eager. We allocate a fast track index before the 347 // fast track becomes active. Since fast tracks are a scarce resource, 348 // this means we are potentially denying other more important fast tracks from 349 // being created. It would be better to allocate the index dynamically. 350 mFastIndex = i; 351 // Read the initial underruns because this field is never cleared by the fast mixer 352 mObservedUnderruns = thread->getFastTrackUnderruns(i); 353 thread->mFastTrackAvailMask &= ~(1 << i); 354 } 355 } 356 ALOGV("Track constructor name %d, calling pid %d", mName, 357 IPCThreadState::self()->getCallingPid()); 358} 359 360AudioFlinger::PlaybackThread::Track::~Track() 361{ 362 ALOGV("PlaybackThread::Track destructor"); 363} 364 365void AudioFlinger::PlaybackThread::Track::destroy() 366{ 367 // NOTE: destroyTrack_l() can remove a strong reference to this Track 368 // by removing it from mTracks vector, so there is a risk that this Tracks's 369 // destructor is called. As the destructor needs to lock mLock, 370 // we must acquire a strong reference on this Track before locking mLock 371 // here so that the destructor is called only when exiting this function. 372 // On the other hand, as long as Track::destroy() is only called by 373 // TrackHandle destructor, the TrackHandle still holds a strong ref on 374 // this Track with its member mTrack. 375 sp<Track> keep(this); 376 { // scope for mLock 377 sp<ThreadBase> thread = mThread.promote(); 378 if (thread != 0) { 379 Mutex::Autolock _l(thread->mLock); 380 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 381 bool wasActive = playbackThread->destroyTrack_l(this); 382 if (!isOutputTrack() && !wasActive) { 383 AudioSystem::releaseOutput(thread->id()); 384 } 385 } 386 } 387} 388 389/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result) 390{ 391 result.append(" Name Client Type Fmt Chn mask Session fCount S F SRate " 392 "L dB R dB Server Main buf Aux Buf Flags Underruns\n"); 393} 394 395void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size) 396{ 397 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR(); 398 if (isFastTrack()) { 399 sprintf(buffer, " F %2d", mFastIndex); 400 } else { 401 sprintf(buffer, " %4d", mName - AudioMixer::TRACK0); 402 } 403 track_state state = mState; 404 char stateChar; 405 if (isTerminated()) { 406 stateChar = 'T'; 407 } else { 408 switch (state) { 409 case IDLE: 410 stateChar = 'I'; 411 break; 412 case STOPPING_1: 413 stateChar = 's'; 414 break; 415 case STOPPING_2: 416 stateChar = '5'; 417 break; 418 case STOPPED: 419 stateChar = 'S'; 420 break; 421 case RESUMING: 422 stateChar = 'R'; 423 break; 424 case ACTIVE: 425 stateChar = 'A'; 426 break; 427 case PAUSING: 428 stateChar = 'p'; 429 break; 430 case PAUSED: 431 stateChar = 'P'; 432 break; 433 case FLUSHED: 434 stateChar = 'F'; 435 break; 436 default: 437 stateChar = '?'; 438 break; 439 } 440 } 441 char nowInUnderrun; 442 switch (mObservedUnderruns.mBitFields.mMostRecent) { 443 case UNDERRUN_FULL: 444 nowInUnderrun = ' '; 445 break; 446 case UNDERRUN_PARTIAL: 447 nowInUnderrun = '<'; 448 break; 449 case UNDERRUN_EMPTY: 450 nowInUnderrun = '*'; 451 break; 452 default: 453 nowInUnderrun = '?'; 454 break; 455 } 456 snprintf(&buffer[7], size-7, " %6u %4u %3u %08X %7u %6u %1c %1d %5u %5.2g %5.2g " 457 "%08X %08X %08X 0x%03X %9u%c\n", 458 (mClient == 0) ? getpid_cached : mClient->pid(), 459 mStreamType, 460 mFormat, 461 mChannelMask, 462 mSessionId, 463 mFrameCount, 464 stateChar, 465 mFillingUpStatus, 466 mAudioTrackServerProxy->getSampleRate(), 467 20.0 * log10((vlr & 0xFFFF) / 4096.0), 468 20.0 * log10((vlr >> 16) / 4096.0), 469 mCblk->mServer, 470 (int)mMainBuffer, 471 (int)mAuxBuffer, 472 mCblk->mFlags, 473 mUnderrunCount, 474 nowInUnderrun); 475} 476 477uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const { 478 return mAudioTrackServerProxy->getSampleRate(); 479} 480 481// AudioBufferProvider interface 482status_t AudioFlinger::PlaybackThread::Track::getNextBuffer( 483 AudioBufferProvider::Buffer* buffer, int64_t pts) 484{ 485 ServerProxy::Buffer buf; 486 size_t desiredFrames = buffer->frameCount; 487 buf.mFrameCount = desiredFrames; 488 status_t status = mServerProxy->obtainBuffer(&buf); 489 buffer->frameCount = buf.mFrameCount; 490 buffer->raw = buf.mRaw; 491 if (buf.mFrameCount == 0) { 492 // only implemented so far for normal tracks, not fast tracks 493 mCblk->u.mStreaming.mUnderrunFrames += desiredFrames; 494 // FIXME also wake futex so that underrun is noticed more quickly 495 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags); 496 } 497 return status; 498} 499 500// Note that framesReady() takes a mutex on the control block using tryLock(). 501// This could result in priority inversion if framesReady() is called by the normal mixer, 502// as the normal mixer thread runs at lower 503// priority than the client's callback thread: there is a short window within framesReady() 504// during which the normal mixer could be preempted, and the client callback would block. 505// Another problem can occur if framesReady() is called by the fast mixer: 506// the tryLock() could block for up to 1 ms, and a sequence of these could delay fast mixer. 507// FIXME Replace AudioTrackShared control block implementation by a non-blocking FIFO queue. 508size_t AudioFlinger::PlaybackThread::Track::framesReady() const { 509 return mAudioTrackServerProxy->framesReady(); 510} 511 512// Don't call for fast tracks; the framesReady() could result in priority inversion 513bool AudioFlinger::PlaybackThread::Track::isReady() const { 514 if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) { 515 return true; 516 } 517 518 if (framesReady() >= mFrameCount || 519 (mCblk->mFlags & CBLK_FORCEREADY)) { 520 mFillingUpStatus = FS_FILLED; 521 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags); 522 return true; 523 } 524 return false; 525} 526 527status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event, 528 int triggerSession) 529{ 530 status_t status = NO_ERROR; 531 ALOGV("start(%d), calling pid %d session %d", 532 mName, IPCThreadState::self()->getCallingPid(), mSessionId); 533 534 sp<ThreadBase> thread = mThread.promote(); 535 if (thread != 0) { 536 Mutex::Autolock _l(thread->mLock); 537 track_state state = mState; 538 // here the track could be either new, or restarted 539 // in both cases "unstop" the track 540 541 if (state == PAUSED) { 542 if (mResumeToStopping) { 543 // happened we need to resume to STOPPING_1 544 mState = TrackBase::STOPPING_1; 545 ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this); 546 } else { 547 mState = TrackBase::RESUMING; 548 ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this); 549 } 550 } else { 551 mState = TrackBase::ACTIVE; 552 ALOGV("? => ACTIVE (%d) on thread %p", mName, this); 553 } 554 555 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 556 status = playbackThread->addTrack_l(this); 557 if (status == INVALID_OPERATION || status == PERMISSION_DENIED) { 558 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 559 // restore previous state if start was rejected by policy manager 560 if (status == PERMISSION_DENIED) { 561 mState = state; 562 } 563 } 564 // track was already in the active list, not a problem 565 if (status == ALREADY_EXISTS) { 566 status = NO_ERROR; 567 } 568 } else { 569 status = BAD_VALUE; 570 } 571 return status; 572} 573 574void AudioFlinger::PlaybackThread::Track::stop() 575{ 576 ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 577 sp<ThreadBase> thread = mThread.promote(); 578 if (thread != 0) { 579 Mutex::Autolock _l(thread->mLock); 580 track_state state = mState; 581 if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) { 582 // If the track is not active (PAUSED and buffers full), flush buffers 583 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 584 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 585 reset(); 586 mState = STOPPED; 587 } else if (!isFastTrack() && !isOffloaded()) { 588 mState = STOPPED; 589 } else { 590 // For fast tracks prepareTracks_l() will set state to STOPPING_2 591 // presentation is complete 592 // For an offloaded track this starts a drain and state will 593 // move to STOPPING_2 when drain completes and then STOPPED 594 mState = STOPPING_1; 595 } 596 ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName, 597 playbackThread); 598 } 599 } 600} 601 602void AudioFlinger::PlaybackThread::Track::pause() 603{ 604 ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid()); 605 sp<ThreadBase> thread = mThread.promote(); 606 if (thread != 0) { 607 Mutex::Autolock _l(thread->mLock); 608 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 609 switch (mState) { 610 case STOPPING_1: 611 case STOPPING_2: 612 if (!isOffloaded()) { 613 /* nothing to do if track is not offloaded */ 614 break; 615 } 616 617 // Offloaded track was draining, we need to carry on draining when resumed 618 mResumeToStopping = true; 619 // fall through... 620 case ACTIVE: 621 case RESUMING: 622 mState = PAUSING; 623 ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get()); 624 playbackThread->signal_l(); 625 break; 626 627 default: 628 break; 629 } 630 } 631} 632 633void AudioFlinger::PlaybackThread::Track::flush() 634{ 635 ALOGV("flush(%d)", mName); 636 sp<ThreadBase> thread = mThread.promote(); 637 if (thread != 0) { 638 Mutex::Autolock _l(thread->mLock); 639 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 640 641 if (isOffloaded()) { 642 // If offloaded we allow flush during any state except terminated 643 // and keep the track active to avoid problems if user is seeking 644 // rapidly and underlying hardware has a significant delay handling 645 // a pause 646 if (isTerminated()) { 647 return; 648 } 649 650 ALOGV("flush: offload flush"); 651 reset(); 652 653 if (mState == STOPPING_1 || mState == STOPPING_2) { 654 ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE"); 655 mState = ACTIVE; 656 } 657 658 if (mState == ACTIVE) { 659 ALOGV("flush called in active state, resetting buffer time out retry count"); 660 mRetryCount = PlaybackThread::kMaxTrackRetriesOffload; 661 } 662 663 mResumeToStopping = false; 664 } else { 665 if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED && 666 mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) { 667 return; 668 } 669 // No point remaining in PAUSED state after a flush => go to 670 // FLUSHED state 671 mState = FLUSHED; 672 // do not reset the track if it is still in the process of being stopped or paused. 673 // this will be done by prepareTracks_l() when the track is stopped. 674 // prepareTracks_l() will see mState == FLUSHED, then 675 // remove from active track list, reset(), and trigger presentation complete 676 if (playbackThread->mActiveTracks.indexOf(this) < 0) { 677 reset(); 678 } 679 } 680 // Prevent flush being lost if the track is flushed and then resumed 681 // before mixer thread can run. This is important when offloading 682 // because the hardware buffer could hold a large amount of audio 683 playbackThread->flushOutput_l(); 684 playbackThread->signal_l(); 685 } 686} 687 688void AudioFlinger::PlaybackThread::Track::reset() 689{ 690 // Do not reset twice to avoid discarding data written just after a flush and before 691 // the audioflinger thread detects the track is stopped. 692 if (!mResetDone) { 693 // Force underrun condition to avoid false underrun callback until first data is 694 // written to buffer 695 android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags); 696 mFillingUpStatus = FS_FILLING; 697 mResetDone = true; 698 if (mState == FLUSHED) { 699 mState = IDLE; 700 } 701 } 702} 703 704status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs) 705{ 706 sp<ThreadBase> thread = mThread.promote(); 707 if (thread == 0) { 708 ALOGE("thread is dead"); 709 return FAILED_TRANSACTION; 710 } else if ((thread->type() == ThreadBase::DIRECT) || 711 (thread->type() == ThreadBase::OFFLOAD)) { 712 return thread->setParameters(keyValuePairs); 713 } else { 714 return PERMISSION_DENIED; 715 } 716} 717 718status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId) 719{ 720 status_t status = DEAD_OBJECT; 721 sp<ThreadBase> thread = mThread.promote(); 722 if (thread != 0) { 723 PlaybackThread *playbackThread = (PlaybackThread *)thread.get(); 724 sp<AudioFlinger> af = mClient->audioFlinger(); 725 726 Mutex::Autolock _l(af->mLock); 727 728 sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId); 729 730 if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) { 731 Mutex::Autolock _dl(playbackThread->mLock); 732 Mutex::Autolock _sl(srcThread->mLock); 733 sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX); 734 if (chain == 0) { 735 return INVALID_OPERATION; 736 } 737 738 sp<EffectModule> effect = chain->getEffectFromId_l(EffectId); 739 if (effect == 0) { 740 return INVALID_OPERATION; 741 } 742 srcThread->removeEffect_l(effect); 743 playbackThread->addEffect_l(effect); 744 // removeEffect_l() has stopped the effect if it was active so it must be restarted 745 if (effect->state() == EffectModule::ACTIVE || 746 effect->state() == EffectModule::STOPPING) { 747 effect->start(); 748 } 749 750 sp<EffectChain> dstChain = effect->chain().promote(); 751 if (dstChain == 0) { 752 srcThread->addEffect_l(effect); 753 return INVALID_OPERATION; 754 } 755 AudioSystem::unregisterEffect(effect->id()); 756 AudioSystem::registerEffect(&effect->desc(), 757 srcThread->id(), 758 dstChain->strategy(), 759 AUDIO_SESSION_OUTPUT_MIX, 760 effect->id()); 761 } 762 status = playbackThread->attachAuxEffect(this, EffectId); 763 } 764 return status; 765} 766 767void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer) 768{ 769 mAuxEffectId = EffectId; 770 mAuxBuffer = buffer; 771} 772 773bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten, 774 size_t audioHalFrames) 775{ 776 // a track is considered presented when the total number of frames written to audio HAL 777 // corresponds to the number of frames written when presentationComplete() is called for the 778 // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time. 779 // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used 780 // to detect when all frames have been played. In this case framesWritten isn't 781 // useful because it doesn't always reflect whether there is data in the h/w 782 // buffers, particularly if a track has been paused and resumed during draining 783 ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d", 784 mPresentationCompleteFrames, framesWritten); 785 if (mPresentationCompleteFrames == 0) { 786 mPresentationCompleteFrames = framesWritten + audioHalFrames; 787 ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d", 788 mPresentationCompleteFrames, audioHalFrames); 789 } 790 791 if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) { 792 ALOGV("presentationComplete() session %d complete: framesWritten %d", 793 mSessionId, framesWritten); 794 triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE); 795 mAudioTrackServerProxy->setStreamEndDone(); 796 return true; 797 } 798 return false; 799} 800 801void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type) 802{ 803 for (int i = 0; i < (int)mSyncEvents.size(); i++) { 804 if (mSyncEvents[i]->type() == type) { 805 mSyncEvents[i]->trigger(); 806 mSyncEvents.removeAt(i); 807 i--; 808 } 809 } 810} 811 812// implement VolumeBufferProvider interface 813 814uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR() 815{ 816 // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs 817 ALOG_ASSERT(isFastTrack() && (mCblk != NULL)); 818 uint32_t vlr = mAudioTrackServerProxy->getVolumeLR(); 819 uint32_t vl = vlr & 0xFFFF; 820 uint32_t vr = vlr >> 16; 821 // track volumes come from shared memory, so can't be trusted and must be clamped 822 if (vl > MAX_GAIN_INT) { 823 vl = MAX_GAIN_INT; 824 } 825 if (vr > MAX_GAIN_INT) { 826 vr = MAX_GAIN_INT; 827 } 828 // now apply the cached master volume and stream type volume; 829 // this is trusted but lacks any synchronization or barrier so may be stale 830 float v = mCachedVolume; 831 vl *= v; 832 vr *= v; 833 // re-combine into U4.16 834 vlr = (vr << 16) | (vl & 0xFFFF); 835 // FIXME look at mute, pause, and stop flags 836 return vlr; 837} 838 839status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event) 840{ 841 if (isTerminated() || mState == PAUSED || 842 ((framesReady() == 0) && ((mSharedBuffer != 0) || 843 (mState == STOPPED)))) { 844 ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ", 845 mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady()); 846 event->cancel(); 847 return INVALID_OPERATION; 848 } 849 (void) TrackBase::setSyncEvent(event); 850 return NO_ERROR; 851} 852 853void AudioFlinger::PlaybackThread::Track::invalidate() 854{ 855 // FIXME should use proxy, and needs work 856 audio_track_cblk_t* cblk = mCblk; 857 android_atomic_or(CBLK_INVALID, &cblk->mFlags); 858 android_atomic_release_store(0x40000000, &cblk->mFutex); 859 // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE 860 (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX); 861 mIsInvalid = true; 862} 863 864// ---------------------------------------------------------------------------- 865 866sp<AudioFlinger::PlaybackThread::TimedTrack> 867AudioFlinger::PlaybackThread::TimedTrack::create( 868 PlaybackThread *thread, 869 const sp<Client>& client, 870 audio_stream_type_t streamType, 871 uint32_t sampleRate, 872 audio_format_t format, 873 audio_channel_mask_t channelMask, 874 size_t frameCount, 875 const sp<IMemory>& sharedBuffer, 876 int sessionId) { 877 if (!client->reserveTimedTrack()) 878 return 0; 879 880 return new TimedTrack( 881 thread, client, streamType, sampleRate, format, channelMask, frameCount, 882 sharedBuffer, sessionId); 883} 884 885AudioFlinger::PlaybackThread::TimedTrack::TimedTrack( 886 PlaybackThread *thread, 887 const sp<Client>& client, 888 audio_stream_type_t streamType, 889 uint32_t sampleRate, 890 audio_format_t format, 891 audio_channel_mask_t channelMask, 892 size_t frameCount, 893 const sp<IMemory>& sharedBuffer, 894 int sessionId) 895 : Track(thread, client, streamType, sampleRate, format, channelMask, 896 frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED), 897 mQueueHeadInFlight(false), 898 mTrimQueueHeadOnRelease(false), 899 mFramesPendingInQueue(0), 900 mTimedSilenceBuffer(NULL), 901 mTimedSilenceBufferSize(0), 902 mTimedAudioOutputOnTime(false), 903 mMediaTimeTransformValid(false) 904{ 905 LocalClock lc; 906 mLocalTimeFreq = lc.getLocalFreq(); 907 908 mLocalTimeToSampleTransform.a_zero = 0; 909 mLocalTimeToSampleTransform.b_zero = 0; 910 mLocalTimeToSampleTransform.a_to_b_numer = sampleRate; 911 mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq; 912 LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer, 913 &mLocalTimeToSampleTransform.a_to_b_denom); 914 915 mMediaTimeToSampleTransform.a_zero = 0; 916 mMediaTimeToSampleTransform.b_zero = 0; 917 mMediaTimeToSampleTransform.a_to_b_numer = sampleRate; 918 mMediaTimeToSampleTransform.a_to_b_denom = 1000000; 919 LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer, 920 &mMediaTimeToSampleTransform.a_to_b_denom); 921} 922 923AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() { 924 mClient->releaseTimedTrack(); 925 delete [] mTimedSilenceBuffer; 926} 927 928status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer( 929 size_t size, sp<IMemory>* buffer) { 930 931 Mutex::Autolock _l(mTimedBufferQueueLock); 932 933 trimTimedBufferQueue_l(); 934 935 // lazily initialize the shared memory heap for timed buffers 936 if (mTimedMemoryDealer == NULL) { 937 const int kTimedBufferHeapSize = 512 << 10; 938 939 mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize, 940 "AudioFlingerTimed"); 941 if (mTimedMemoryDealer == NULL) 942 return NO_MEMORY; 943 } 944 945 sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size); 946 if (newBuffer == NULL) { 947 newBuffer = mTimedMemoryDealer->allocate(size); 948 if (newBuffer == NULL) 949 return NO_MEMORY; 950 } 951 952 *buffer = newBuffer; 953 return NO_ERROR; 954} 955 956// caller must hold mTimedBufferQueueLock 957void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() { 958 int64_t mediaTimeNow; 959 { 960 Mutex::Autolock mttLock(mMediaTimeTransformLock); 961 if (!mMediaTimeTransformValid) 962 return; 963 964 int64_t targetTimeNow; 965 status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) 966 ? mCCHelper.getCommonTime(&targetTimeNow) 967 : mCCHelper.getLocalTime(&targetTimeNow); 968 969 if (OK != res) 970 return; 971 972 if (!mMediaTimeTransform.doReverseTransform(targetTimeNow, 973 &mediaTimeNow)) { 974 return; 975 } 976 } 977 978 size_t trimEnd; 979 for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) { 980 int64_t bufEnd; 981 982 if ((trimEnd + 1) < mTimedBufferQueue.size()) { 983 // We have a next buffer. Just use its PTS as the PTS of the frame 984 // following the last frame in this buffer. If the stream is sparse 985 // (ie, there are deliberate gaps left in the stream which should be 986 // filled with silence by the TimedAudioTrack), then this can result 987 // in one extra buffer being left un-trimmed when it could have 988 // been. In general, this is not typical, and we would rather 989 // optimized away the TS calculation below for the more common case 990 // where PTSes are contiguous. 991 bufEnd = mTimedBufferQueue[trimEnd + 1].pts(); 992 } else { 993 // We have no next buffer. Compute the PTS of the frame following 994 // the last frame in this buffer by computing the duration of of 995 // this frame in media time units and adding it to the PTS of the 996 // buffer. 997 int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size() 998 / mFrameSize; 999 1000 if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount, 1001 &bufEnd)) { 1002 ALOGE("Failed to convert frame count of %lld to media time" 1003 " duration" " (scale factor %d/%u) in %s", 1004 frameCount, 1005 mMediaTimeToSampleTransform.a_to_b_numer, 1006 mMediaTimeToSampleTransform.a_to_b_denom, 1007 __PRETTY_FUNCTION__); 1008 break; 1009 } 1010 bufEnd += mTimedBufferQueue[trimEnd].pts(); 1011 } 1012 1013 if (bufEnd > mediaTimeNow) 1014 break; 1015 1016 // Is the buffer we want to use in the middle of a mix operation right 1017 // now? If so, don't actually trim it. Just wait for the releaseBuffer 1018 // from the mixer which should be coming back shortly. 1019 if (!trimEnd && mQueueHeadInFlight) { 1020 mTrimQueueHeadOnRelease = true; 1021 } 1022 } 1023 1024 size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0; 1025 if (trimStart < trimEnd) { 1026 // Update the bookkeeping for framesReady() 1027 for (size_t i = trimStart; i < trimEnd; ++i) { 1028 updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim"); 1029 } 1030 1031 // Now actually remove the buffers from the queue. 1032 mTimedBufferQueue.removeItemsAt(trimStart, trimEnd); 1033 } 1034} 1035 1036void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l( 1037 const char* logTag) { 1038 ALOG_ASSERT(mTimedBufferQueue.size() > 0, 1039 "%s called (reason \"%s\"), but timed buffer queue has no" 1040 " elements to trim.", __FUNCTION__, logTag); 1041 1042 updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag); 1043 mTimedBufferQueue.removeAt(0); 1044} 1045 1046void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l( 1047 const TimedBuffer& buf, 1048 const char* logTag) { 1049 uint32_t bufBytes = buf.buffer()->size(); 1050 uint32_t consumedAlready = buf.position(); 1051 1052 ALOG_ASSERT(consumedAlready <= bufBytes, 1053 "Bad bookkeeping while updating frames pending. Timed buffer is" 1054 " only %u bytes long, but claims to have consumed %u" 1055 " bytes. (update reason: \"%s\")", 1056 bufBytes, consumedAlready, logTag); 1057 1058 uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize; 1059 ALOG_ASSERT(mFramesPendingInQueue >= bufFrames, 1060 "Bad bookkeeping while updating frames pending. Should have at" 1061 " least %u queued frames, but we think we have only %u. (update" 1062 " reason: \"%s\")", 1063 bufFrames, mFramesPendingInQueue, logTag); 1064 1065 mFramesPendingInQueue -= bufFrames; 1066} 1067 1068status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer( 1069 const sp<IMemory>& buffer, int64_t pts) { 1070 1071 { 1072 Mutex::Autolock mttLock(mMediaTimeTransformLock); 1073 if (!mMediaTimeTransformValid) 1074 return INVALID_OPERATION; 1075 } 1076 1077 Mutex::Autolock _l(mTimedBufferQueueLock); 1078 1079 uint32_t bufFrames = buffer->size() / mFrameSize; 1080 mFramesPendingInQueue += bufFrames; 1081 mTimedBufferQueue.add(TimedBuffer(buffer, pts)); 1082 1083 return NO_ERROR; 1084} 1085 1086status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform( 1087 const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) { 1088 1089 ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d", 1090 xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom, 1091 target); 1092 1093 if (!(target == TimedAudioTrack::LOCAL_TIME || 1094 target == TimedAudioTrack::COMMON_TIME)) { 1095 return BAD_VALUE; 1096 } 1097 1098 Mutex::Autolock lock(mMediaTimeTransformLock); 1099 mMediaTimeTransform = xform; 1100 mMediaTimeTransformTarget = target; 1101 mMediaTimeTransformValid = true; 1102 1103 return NO_ERROR; 1104} 1105 1106#define min(a, b) ((a) < (b) ? (a) : (b)) 1107 1108// implementation of getNextBuffer for tracks whose buffers have timestamps 1109status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer( 1110 AudioBufferProvider::Buffer* buffer, int64_t pts) 1111{ 1112 if (pts == AudioBufferProvider::kInvalidPTS) { 1113 buffer->raw = NULL; 1114 buffer->frameCount = 0; 1115 mTimedAudioOutputOnTime = false; 1116 return INVALID_OPERATION; 1117 } 1118 1119 Mutex::Autolock _l(mTimedBufferQueueLock); 1120 1121 ALOG_ASSERT(!mQueueHeadInFlight, 1122 "getNextBuffer called without releaseBuffer!"); 1123 1124 while (true) { 1125 1126 // if we have no timed buffers, then fail 1127 if (mTimedBufferQueue.isEmpty()) { 1128 buffer->raw = NULL; 1129 buffer->frameCount = 0; 1130 return NOT_ENOUGH_DATA; 1131 } 1132 1133 TimedBuffer& head = mTimedBufferQueue.editItemAt(0); 1134 1135 // calculate the PTS of the head of the timed buffer queue expressed in 1136 // local time 1137 int64_t headLocalPTS; 1138 { 1139 Mutex::Autolock mttLock(mMediaTimeTransformLock); 1140 1141 ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid"); 1142 1143 if (mMediaTimeTransform.a_to_b_denom == 0) { 1144 // the transform represents a pause, so yield silence 1145 timedYieldSilence_l(buffer->frameCount, buffer); 1146 return NO_ERROR; 1147 } 1148 1149 int64_t transformedPTS; 1150 if (!mMediaTimeTransform.doForwardTransform(head.pts(), 1151 &transformedPTS)) { 1152 // the transform failed. this shouldn't happen, but if it does 1153 // then just drop this buffer 1154 ALOGW("timedGetNextBuffer transform failed"); 1155 buffer->raw = NULL; 1156 buffer->frameCount = 0; 1157 trimTimedBufferQueueHead_l("getNextBuffer; no transform"); 1158 return NO_ERROR; 1159 } 1160 1161 if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) { 1162 if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS, 1163 &headLocalPTS)) { 1164 buffer->raw = NULL; 1165 buffer->frameCount = 0; 1166 return INVALID_OPERATION; 1167 } 1168 } else { 1169 headLocalPTS = transformedPTS; 1170 } 1171 } 1172 1173 uint32_t sr = sampleRate(); 1174 1175 // adjust the head buffer's PTS to reflect the portion of the head buffer 1176 // that has already been consumed 1177 int64_t effectivePTS = headLocalPTS + 1178 ((head.position() / mFrameSize) * mLocalTimeFreq / sr); 1179 1180 // Calculate the delta in samples between the head of the input buffer 1181 // queue and the start of the next output buffer that will be written. 1182 // If the transformation fails because of over or underflow, it means 1183 // that the sample's position in the output stream is so far out of 1184 // whack that it should just be dropped. 1185 int64_t sampleDelta; 1186 if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) { 1187 ALOGV("*** head buffer is too far from PTS: dropped buffer"); 1188 trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from" 1189 " mix"); 1190 continue; 1191 } 1192 if (!mLocalTimeToSampleTransform.doForwardTransform( 1193 (effectivePTS - pts) << 32, &sampleDelta)) { 1194 ALOGV("*** too late during sample rate transform: dropped buffer"); 1195 trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample"); 1196 continue; 1197 } 1198 1199 ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld" 1200 " sampleDelta=[%d.%08x]", 1201 head.pts(), head.position(), pts, 1202 static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1) 1203 + (sampleDelta >> 32)), 1204 static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF)); 1205 1206 // if the delta between the ideal placement for the next input sample and 1207 // the current output position is within this threshold, then we will 1208 // concatenate the next input samples to the previous output 1209 const int64_t kSampleContinuityThreshold = 1210 (static_cast<int64_t>(sr) << 32) / 250; 1211 1212 // if this is the first buffer of audio that we're emitting from this track 1213 // then it should be almost exactly on time. 1214 const int64_t kSampleStartupThreshold = 1LL << 32; 1215 1216 if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) || 1217 (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) { 1218 // the next input is close enough to being on time, so concatenate it 1219 // with the last output 1220 timedYieldSamples_l(buffer); 1221 1222 ALOGVV("*** on time: head.pos=%d frameCount=%u", 1223 head.position(), buffer->frameCount); 1224 return NO_ERROR; 1225 } 1226 1227 // Looks like our output is not on time. Reset our on timed status. 1228 // Next time we mix samples from our input queue, then should be within 1229 // the StartupThreshold. 1230 mTimedAudioOutputOnTime = false; 1231 if (sampleDelta > 0) { 1232 // the gap between the current output position and the proper start of 1233 // the next input sample is too big, so fill it with silence 1234 uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32; 1235 1236 timedYieldSilence_l(framesUntilNextInput, buffer); 1237 ALOGV("*** silence: frameCount=%u", buffer->frameCount); 1238 return NO_ERROR; 1239 } else { 1240 // the next input sample is late 1241 uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32)); 1242 size_t onTimeSamplePosition = 1243 head.position() + lateFrames * mFrameSize; 1244 1245 if (onTimeSamplePosition > head.buffer()->size()) { 1246 // all the remaining samples in the head are too late, so 1247 // drop it and move on 1248 ALOGV("*** too late: dropped buffer"); 1249 trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer"); 1250 continue; 1251 } else { 1252 // skip over the late samples 1253 head.setPosition(onTimeSamplePosition); 1254 1255 // yield the available samples 1256 timedYieldSamples_l(buffer); 1257 1258 ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount); 1259 return NO_ERROR; 1260 } 1261 } 1262 } 1263} 1264 1265// Yield samples from the timed buffer queue head up to the given output 1266// buffer's capacity. 1267// 1268// Caller must hold mTimedBufferQueueLock 1269void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l( 1270 AudioBufferProvider::Buffer* buffer) { 1271 1272 const TimedBuffer& head = mTimedBufferQueue[0]; 1273 1274 buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) + 1275 head.position()); 1276 1277 uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) / 1278 mFrameSize); 1279 size_t framesRequested = buffer->frameCount; 1280 buffer->frameCount = min(framesLeftInHead, framesRequested); 1281 1282 mQueueHeadInFlight = true; 1283 mTimedAudioOutputOnTime = true; 1284} 1285 1286// Yield samples of silence up to the given output buffer's capacity 1287// 1288// Caller must hold mTimedBufferQueueLock 1289void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l( 1290 uint32_t numFrames, AudioBufferProvider::Buffer* buffer) { 1291 1292 // lazily allocate a buffer filled with silence 1293 if (mTimedSilenceBufferSize < numFrames * mFrameSize) { 1294 delete [] mTimedSilenceBuffer; 1295 mTimedSilenceBufferSize = numFrames * mFrameSize; 1296 mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize]; 1297 memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize); 1298 } 1299 1300 buffer->raw = mTimedSilenceBuffer; 1301 size_t framesRequested = buffer->frameCount; 1302 buffer->frameCount = min(numFrames, framesRequested); 1303 1304 mTimedAudioOutputOnTime = false; 1305} 1306 1307// AudioBufferProvider interface 1308void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer( 1309 AudioBufferProvider::Buffer* buffer) { 1310 1311 Mutex::Autolock _l(mTimedBufferQueueLock); 1312 1313 // If the buffer which was just released is part of the buffer at the head 1314 // of the queue, be sure to update the amt of the buffer which has been 1315 // consumed. If the buffer being returned is not part of the head of the 1316 // queue, its either because the buffer is part of the silence buffer, or 1317 // because the head of the timed queue was trimmed after the mixer called 1318 // getNextBuffer but before the mixer called releaseBuffer. 1319 if (buffer->raw == mTimedSilenceBuffer) { 1320 ALOG_ASSERT(!mQueueHeadInFlight, 1321 "Queue head in flight during release of silence buffer!"); 1322 goto done; 1323 } 1324 1325 ALOG_ASSERT(mQueueHeadInFlight, 1326 "TimedTrack::releaseBuffer of non-silence buffer, but no queue" 1327 " head in flight."); 1328 1329 if (mTimedBufferQueue.size()) { 1330 TimedBuffer& head = mTimedBufferQueue.editItemAt(0); 1331 1332 void* start = head.buffer()->pointer(); 1333 void* end = reinterpret_cast<void*>( 1334 reinterpret_cast<uint8_t*>(head.buffer()->pointer()) 1335 + head.buffer()->size()); 1336 1337 ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end), 1338 "released buffer not within the head of the timed buffer" 1339 " queue; qHead = [%p, %p], released buffer = %p", 1340 start, end, buffer->raw); 1341 1342 head.setPosition(head.position() + 1343 (buffer->frameCount * mFrameSize)); 1344 mQueueHeadInFlight = false; 1345 1346 ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount, 1347 "Bad bookkeeping during releaseBuffer! Should have at" 1348 " least %u queued frames, but we think we have only %u", 1349 buffer->frameCount, mFramesPendingInQueue); 1350 1351 mFramesPendingInQueue -= buffer->frameCount; 1352 1353 if ((static_cast<size_t>(head.position()) >= head.buffer()->size()) 1354 || mTrimQueueHeadOnRelease) { 1355 trimTimedBufferQueueHead_l("releaseBuffer"); 1356 mTrimQueueHeadOnRelease = false; 1357 } 1358 } else { 1359 LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no" 1360 " buffers in the timed buffer queue"); 1361 } 1362 1363done: 1364 buffer->raw = 0; 1365 buffer->frameCount = 0; 1366} 1367 1368size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const { 1369 Mutex::Autolock _l(mTimedBufferQueueLock); 1370 return mFramesPendingInQueue; 1371} 1372 1373AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer() 1374 : mPTS(0), mPosition(0) {} 1375 1376AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer( 1377 const sp<IMemory>& buffer, int64_t pts) 1378 : mBuffer(buffer), mPTS(pts), mPosition(0) {} 1379 1380 1381// ---------------------------------------------------------------------------- 1382 1383AudioFlinger::PlaybackThread::OutputTrack::OutputTrack( 1384 PlaybackThread *playbackThread, 1385 DuplicatingThread *sourceThread, 1386 uint32_t sampleRate, 1387 audio_format_t format, 1388 audio_channel_mask_t channelMask, 1389 size_t frameCount) 1390 : Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount, 1391 NULL, 0, IAudioFlinger::TRACK_DEFAULT), 1392 mActive(false), mSourceThread(sourceThread), mClientProxy(NULL) 1393{ 1394 1395 if (mCblk != NULL) { 1396 mOutBuffer.frameCount = 0; 1397 playbackThread->mTracks.add(this); 1398 ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, " 1399 "mCblk->frameCount_ %u, mChannelMask 0x%08x", 1400 mCblk, mBuffer, 1401 mCblk->frameCount_, mChannelMask); 1402 // since client and server are in the same process, 1403 // the buffer has the same virtual address on both sides 1404 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize); 1405 mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000)); 1406 mClientProxy->setSendLevel(0.0); 1407 mClientProxy->setSampleRate(sampleRate); 1408 mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize, 1409 true /*clientInServer*/); 1410 } else { 1411 ALOGW("Error creating output track on thread %p", playbackThread); 1412 } 1413} 1414 1415AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack() 1416{ 1417 clearBufferQueue(); 1418 delete mClientProxy; 1419 // superclass destructor will now delete the server proxy and shared memory both refer to 1420} 1421 1422status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event, 1423 int triggerSession) 1424{ 1425 status_t status = Track::start(event, triggerSession); 1426 if (status != NO_ERROR) { 1427 return status; 1428 } 1429 1430 mActive = true; 1431 mRetryCount = 127; 1432 return status; 1433} 1434 1435void AudioFlinger::PlaybackThread::OutputTrack::stop() 1436{ 1437 Track::stop(); 1438 clearBufferQueue(); 1439 mOutBuffer.frameCount = 0; 1440 mActive = false; 1441} 1442 1443bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames) 1444{ 1445 Buffer *pInBuffer; 1446 Buffer inBuffer; 1447 uint32_t channelCount = mChannelCount; 1448 bool outputBufferFull = false; 1449 inBuffer.frameCount = frames; 1450 inBuffer.i16 = data; 1451 1452 uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs(); 1453 1454 if (!mActive && frames != 0) { 1455 start(); 1456 sp<ThreadBase> thread = mThread.promote(); 1457 if (thread != 0) { 1458 MixerThread *mixerThread = (MixerThread *)thread.get(); 1459 if (mFrameCount > frames) { 1460 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 1461 uint32_t startFrames = (mFrameCount - frames); 1462 pInBuffer = new Buffer; 1463 pInBuffer->mBuffer = new int16_t[startFrames * channelCount]; 1464 pInBuffer->frameCount = startFrames; 1465 pInBuffer->i16 = pInBuffer->mBuffer; 1466 memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t)); 1467 mBufferQueue.add(pInBuffer); 1468 } else { 1469 ALOGW("OutputTrack::write() %p no more buffers in queue", this); 1470 } 1471 } 1472 } 1473 } 1474 1475 while (waitTimeLeftMs) { 1476 // First write pending buffers, then new data 1477 if (mBufferQueue.size()) { 1478 pInBuffer = mBufferQueue.itemAt(0); 1479 } else { 1480 pInBuffer = &inBuffer; 1481 } 1482 1483 if (pInBuffer->frameCount == 0) { 1484 break; 1485 } 1486 1487 if (mOutBuffer.frameCount == 0) { 1488 mOutBuffer.frameCount = pInBuffer->frameCount; 1489 nsecs_t startTime = systemTime(); 1490 status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs); 1491 if (status != NO_ERROR) { 1492 ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this, 1493 mThread.unsafe_get(), status); 1494 outputBufferFull = true; 1495 break; 1496 } 1497 uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime); 1498 if (waitTimeLeftMs >= waitTimeMs) { 1499 waitTimeLeftMs -= waitTimeMs; 1500 } else { 1501 waitTimeLeftMs = 0; 1502 } 1503 } 1504 1505 uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount : 1506 pInBuffer->frameCount; 1507 memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t)); 1508 Proxy::Buffer buf; 1509 buf.mFrameCount = outFrames; 1510 buf.mRaw = NULL; 1511 mClientProxy->releaseBuffer(&buf); 1512 pInBuffer->frameCount -= outFrames; 1513 pInBuffer->i16 += outFrames * channelCount; 1514 mOutBuffer.frameCount -= outFrames; 1515 mOutBuffer.i16 += outFrames * channelCount; 1516 1517 if (pInBuffer->frameCount == 0) { 1518 if (mBufferQueue.size()) { 1519 mBufferQueue.removeAt(0); 1520 delete [] pInBuffer->mBuffer; 1521 delete pInBuffer; 1522 ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this, 1523 mThread.unsafe_get(), mBufferQueue.size()); 1524 } else { 1525 break; 1526 } 1527 } 1528 } 1529 1530 // If we could not write all frames, allocate a buffer and queue it for next time. 1531 if (inBuffer.frameCount) { 1532 sp<ThreadBase> thread = mThread.promote(); 1533 if (thread != 0 && !thread->standby()) { 1534 if (mBufferQueue.size() < kMaxOverFlowBuffers) { 1535 pInBuffer = new Buffer; 1536 pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount]; 1537 pInBuffer->frameCount = inBuffer.frameCount; 1538 pInBuffer->i16 = pInBuffer->mBuffer; 1539 memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount * 1540 sizeof(int16_t)); 1541 mBufferQueue.add(pInBuffer); 1542 ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this, 1543 mThread.unsafe_get(), mBufferQueue.size()); 1544 } else { 1545 ALOGW("OutputTrack::write() %p thread %p no more overflow buffers", 1546 mThread.unsafe_get(), this); 1547 } 1548 } 1549 } 1550 1551 // Calling write() with a 0 length buffer, means that no more data will be written: 1552 // If no more buffers are pending, fill output track buffer to make sure it is started 1553 // by output mixer. 1554 if (frames == 0 && mBufferQueue.size() == 0) { 1555 // FIXME borken, replace by getting framesReady() from proxy 1556 size_t user = 0; // was mCblk->user 1557 if (user < mFrameCount) { 1558 frames = mFrameCount - user; 1559 pInBuffer = new Buffer; 1560 pInBuffer->mBuffer = new int16_t[frames * channelCount]; 1561 pInBuffer->frameCount = frames; 1562 pInBuffer->i16 = pInBuffer->mBuffer; 1563 memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t)); 1564 mBufferQueue.add(pInBuffer); 1565 } else if (mActive) { 1566 stop(); 1567 } 1568 } 1569 1570 return outputBufferFull; 1571} 1572 1573status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer( 1574 AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs) 1575{ 1576 ClientProxy::Buffer buf; 1577 buf.mFrameCount = buffer->frameCount; 1578 struct timespec timeout; 1579 timeout.tv_sec = waitTimeMs / 1000; 1580 timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000; 1581 status_t status = mClientProxy->obtainBuffer(&buf, &timeout); 1582 buffer->frameCount = buf.mFrameCount; 1583 buffer->raw = buf.mRaw; 1584 return status; 1585} 1586 1587void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue() 1588{ 1589 size_t size = mBufferQueue.size(); 1590 1591 for (size_t i = 0; i < size; i++) { 1592 Buffer *pBuffer = mBufferQueue.itemAt(i); 1593 delete [] pBuffer->mBuffer; 1594 delete pBuffer; 1595 } 1596 mBufferQueue.clear(); 1597} 1598 1599 1600// ---------------------------------------------------------------------------- 1601// Record 1602// ---------------------------------------------------------------------------- 1603 1604AudioFlinger::RecordHandle::RecordHandle( 1605 const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack) 1606 : BnAudioRecord(), 1607 mRecordTrack(recordTrack) 1608{ 1609} 1610 1611AudioFlinger::RecordHandle::~RecordHandle() { 1612 stop_nonvirtual(); 1613 mRecordTrack->destroy(); 1614} 1615 1616sp<IMemory> AudioFlinger::RecordHandle::getCblk() const { 1617 return mRecordTrack->getCblk(); 1618} 1619 1620status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event, 1621 int triggerSession) { 1622 ALOGV("RecordHandle::start()"); 1623 return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession); 1624} 1625 1626void AudioFlinger::RecordHandle::stop() { 1627 stop_nonvirtual(); 1628} 1629 1630void AudioFlinger::RecordHandle::stop_nonvirtual() { 1631 ALOGV("RecordHandle::stop()"); 1632 mRecordTrack->stop(); 1633} 1634 1635status_t AudioFlinger::RecordHandle::onTransact( 1636 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 1637{ 1638 return BnAudioRecord::onTransact(code, data, reply, flags); 1639} 1640 1641// ---------------------------------------------------------------------------- 1642 1643// RecordTrack constructor must be called with AudioFlinger::mLock held 1644AudioFlinger::RecordThread::RecordTrack::RecordTrack( 1645 RecordThread *thread, 1646 const sp<Client>& client, 1647 uint32_t sampleRate, 1648 audio_format_t format, 1649 audio_channel_mask_t channelMask, 1650 size_t frameCount, 1651 int sessionId) 1652 : TrackBase(thread, client, sampleRate, format, 1653 channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/), 1654 mOverflow(false) 1655{ 1656 ALOGV("RecordTrack constructor"); 1657 if (mCblk != NULL) { 1658 mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, 1659 mFrameSize); 1660 mServerProxy = mAudioRecordServerProxy; 1661 } 1662} 1663 1664AudioFlinger::RecordThread::RecordTrack::~RecordTrack() 1665{ 1666 ALOGV("%s", __func__); 1667} 1668 1669// AudioBufferProvider interface 1670status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer, 1671 int64_t pts) 1672{ 1673 ServerProxy::Buffer buf; 1674 buf.mFrameCount = buffer->frameCount; 1675 status_t status = mServerProxy->obtainBuffer(&buf); 1676 buffer->frameCount = buf.mFrameCount; 1677 buffer->raw = buf.mRaw; 1678 if (buf.mFrameCount == 0) { 1679 // FIXME also wake futex so that overrun is noticed more quickly 1680 (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags); 1681 } 1682 return status; 1683} 1684 1685status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event, 1686 int triggerSession) 1687{ 1688 sp<ThreadBase> thread = mThread.promote(); 1689 if (thread != 0) { 1690 RecordThread *recordThread = (RecordThread *)thread.get(); 1691 return recordThread->start(this, event, triggerSession); 1692 } else { 1693 return BAD_VALUE; 1694 } 1695} 1696 1697void AudioFlinger::RecordThread::RecordTrack::stop() 1698{ 1699 sp<ThreadBase> thread = mThread.promote(); 1700 if (thread != 0) { 1701 RecordThread *recordThread = (RecordThread *)thread.get(); 1702 if (recordThread->stop(this)) { 1703 AudioSystem::stopInput(recordThread->id()); 1704 } 1705 } 1706} 1707 1708void AudioFlinger::RecordThread::RecordTrack::destroy() 1709{ 1710 // see comments at AudioFlinger::PlaybackThread::Track::destroy() 1711 sp<RecordTrack> keep(this); 1712 { 1713 sp<ThreadBase> thread = mThread.promote(); 1714 if (thread != 0) { 1715 if (mState == ACTIVE || mState == RESUMING) { 1716 AudioSystem::stopInput(thread->id()); 1717 } 1718 AudioSystem::releaseInput(thread->id()); 1719 Mutex::Autolock _l(thread->mLock); 1720 RecordThread *recordThread = (RecordThread *) thread.get(); 1721 recordThread->destroyTrack_l(this); 1722 } 1723 } 1724} 1725 1726 1727/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result) 1728{ 1729 result.append("Client Fmt Chn mask Session S Server fCount\n"); 1730} 1731 1732void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size) 1733{ 1734 snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n", 1735 (mClient == 0) ? getpid_cached : mClient->pid(), 1736 mFormat, 1737 mChannelMask, 1738 mSessionId, 1739 mState, 1740 mCblk->mServer, 1741 mFrameCount); 1742} 1743 1744}; // namespace android 1745