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