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