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