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