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