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