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