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