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