Tracks.cpp revision 6e2ebe97f2ad0a21907f20f9ee644c4eacbb7a40
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::onTransact(
287    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
288{
289    return BnAudioTrack::onTransact(code, data, reply, flags);
290}
291
292// ----------------------------------------------------------------------------
293
294// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
295AudioFlinger::PlaybackThread::Track::Track(
296            PlaybackThread *thread,
297            const sp<Client>& client,
298            audio_stream_type_t streamType,
299            uint32_t sampleRate,
300            audio_format_t format,
301            audio_channel_mask_t channelMask,
302            size_t frameCount,
303            const sp<IMemory>& sharedBuffer,
304            int sessionId,
305            IAudioFlinger::track_flags_t flags)
306    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount, sharedBuffer,
307            sessionId, true /*isOut*/),
308    mFillingUpStatus(FS_INVALID),
309    // mRetryCount initialized later when needed
310    mSharedBuffer(sharedBuffer),
311    mStreamType(streamType),
312    mName(-1),  // see note below
313    mMainBuffer(thread->mixBuffer()),
314    mAuxBuffer(NULL),
315    mAuxEffectId(0), mHasVolumeController(false),
316    mPresentationCompleteFrames(0),
317    mFlags(flags),
318    mFastIndex(-1),
319    mCachedVolume(1.0),
320    mIsInvalid(false),
321    mAudioTrackServerProxy(NULL),
322    mResumeToStopping(false)
323{
324    if (mCblk != NULL) {
325        if (sharedBuffer == 0) {
326            mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
327                    mFrameSize);
328        } else {
329            mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
330                    mFrameSize);
331        }
332        mServerProxy = mAudioTrackServerProxy;
333        // to avoid leaking a track name, do not allocate one unless there is an mCblk
334        mName = thread->getTrackName_l(channelMask, sessionId);
335        if (mName < 0) {
336            ALOGE("no more track names available");
337            return;
338        }
339        // only allocate a fast track index if we were able to allocate a normal track name
340        if (flags & IAudioFlinger::TRACK_FAST) {
341            mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
342            ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
343            int i = __builtin_ctz(thread->mFastTrackAvailMask);
344            ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
345            // FIXME This is too eager.  We allocate a fast track index before the
346            //       fast track becomes active.  Since fast tracks are a scarce resource,
347            //       this means we are potentially denying other more important fast tracks from
348            //       being created.  It would be better to allocate the index dynamically.
349            mFastIndex = i;
350            // Read the initial underruns because this field is never cleared by the fast mixer
351            mObservedUnderruns = thread->getFastTrackUnderruns(i);
352            thread->mFastTrackAvailMask &= ~(1 << i);
353        }
354    }
355    ALOGV("Track constructor name %d, calling pid %d", mName,
356            IPCThreadState::self()->getCallingPid());
357}
358
359AudioFlinger::PlaybackThread::Track::~Track()
360{
361    ALOGV("PlaybackThread::Track destructor");
362}
363
364status_t AudioFlinger::PlaybackThread::Track::initCheck() const
365{
366    status_t status = TrackBase::initCheck();
367    if (status == NO_ERROR && mName < 0) {
368        status = NO_MEMORY;
369    }
370    return status;
371}
372
373void AudioFlinger::PlaybackThread::Track::destroy()
374{
375    // NOTE: destroyTrack_l() can remove a strong reference to this Track
376    // by removing it from mTracks vector, so there is a risk that this Tracks's
377    // destructor is called. As the destructor needs to lock mLock,
378    // we must acquire a strong reference on this Track before locking mLock
379    // here so that the destructor is called only when exiting this function.
380    // On the other hand, as long as Track::destroy() is only called by
381    // TrackHandle destructor, the TrackHandle still holds a strong ref on
382    // this Track with its member mTrack.
383    sp<Track> keep(this);
384    { // scope for mLock
385        sp<ThreadBase> thread = mThread.promote();
386        if (thread != 0) {
387            Mutex::Autolock _l(thread->mLock);
388            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
389            bool wasActive = playbackThread->destroyTrack_l(this);
390            if (!isOutputTrack() && !wasActive) {
391                AudioSystem::releaseOutput(thread->id());
392            }
393        }
394    }
395}
396
397/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
398{
399    result.append("   Name Client Type Fmt Chn mask Session fCount S F SRate  "
400                  "L dB  R dB    Server Main buf  Aux Buf Flags UndFrmCnt\n");
401}
402
403void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size)
404{
405    uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
406    if (isFastTrack()) {
407        sprintf(buffer, "   F %2d", mFastIndex);
408    } else {
409        sprintf(buffer, "   %4d", mName - AudioMixer::TRACK0);
410    }
411    track_state state = mState;
412    char stateChar;
413    if (isTerminated()) {
414        stateChar = 'T';
415    } else {
416        switch (state) {
417        case IDLE:
418            stateChar = 'I';
419            break;
420        case STOPPING_1:
421            stateChar = 's';
422            break;
423        case STOPPING_2:
424            stateChar = '5';
425            break;
426        case STOPPED:
427            stateChar = 'S';
428            break;
429        case RESUMING:
430            stateChar = 'R';
431            break;
432        case ACTIVE:
433            stateChar = 'A';
434            break;
435        case PAUSING:
436            stateChar = 'p';
437            break;
438        case PAUSED:
439            stateChar = 'P';
440            break;
441        case FLUSHED:
442            stateChar = 'F';
443            break;
444        default:
445            stateChar = '?';
446            break;
447        }
448    }
449    char nowInUnderrun;
450    switch (mObservedUnderruns.mBitFields.mMostRecent) {
451    case UNDERRUN_FULL:
452        nowInUnderrun = ' ';
453        break;
454    case UNDERRUN_PARTIAL:
455        nowInUnderrun = '<';
456        break;
457    case UNDERRUN_EMPTY:
458        nowInUnderrun = '*';
459        break;
460    default:
461        nowInUnderrun = '?';
462        break;
463    }
464    snprintf(&buffer[7], size-7, " %6u %4u %3u %08X %7u %6u %1c %1d %5u %5.2g %5.2g  "
465                                 "%08X %08X %08X 0x%03X %9u%c\n",
466            (mClient == 0) ? getpid_cached : mClient->pid(),
467            mStreamType,
468            mFormat,
469            mChannelMask,
470            mSessionId,
471            mFrameCount,
472            stateChar,
473            mFillingUpStatus,
474            mAudioTrackServerProxy->getSampleRate(),
475            20.0 * log10((vlr & 0xFFFF) / 4096.0),
476            20.0 * log10((vlr >> 16) / 4096.0),
477            mCblk->mServer,
478            (int)mMainBuffer,
479            (int)mAuxBuffer,
480            mCblk->mFlags,
481            mAudioTrackServerProxy->getUnderrunFrames(),
482            nowInUnderrun);
483}
484
485uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
486    return mAudioTrackServerProxy->getSampleRate();
487}
488
489// AudioBufferProvider interface
490status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
491        AudioBufferProvider::Buffer* buffer, int64_t pts)
492{
493    ServerProxy::Buffer buf;
494    size_t desiredFrames = buffer->frameCount;
495    buf.mFrameCount = desiredFrames;
496    status_t status = mServerProxy->obtainBuffer(&buf);
497    buffer->frameCount = buf.mFrameCount;
498    buffer->raw = buf.mRaw;
499    if (buf.mFrameCount == 0) {
500        mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
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->mFlags & CBLK_FORCEREADY)) {
525        mFillingUpStatus = FS_FILLED;
526        android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
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->mFlags);
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->mFlags);
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
951    sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
952    if (newBuffer == NULL) {
953        newBuffer = mTimedMemoryDealer->allocate(size);
954        if (newBuffer == NULL) {
955            return NO_MEMORY;
956        }
957    }
958
959    *buffer = newBuffer;
960    return NO_ERROR;
961}
962
963// caller must hold mTimedBufferQueueLock
964void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
965    int64_t mediaTimeNow;
966    {
967        Mutex::Autolock mttLock(mMediaTimeTransformLock);
968        if (!mMediaTimeTransformValid)
969            return;
970
971        int64_t targetTimeNow;
972        status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
973            ? mCCHelper.getCommonTime(&targetTimeNow)
974            : mCCHelper.getLocalTime(&targetTimeNow);
975
976        if (OK != res)
977            return;
978
979        if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
980                                                    &mediaTimeNow)) {
981            return;
982        }
983    }
984
985    size_t trimEnd;
986    for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
987        int64_t bufEnd;
988
989        if ((trimEnd + 1) < mTimedBufferQueue.size()) {
990            // We have a next buffer.  Just use its PTS as the PTS of the frame
991            // following the last frame in this buffer.  If the stream is sparse
992            // (ie, there are deliberate gaps left in the stream which should be
993            // filled with silence by the TimedAudioTrack), then this can result
994            // in one extra buffer being left un-trimmed when it could have
995            // been.  In general, this is not typical, and we would rather
996            // optimized away the TS calculation below for the more common case
997            // where PTSes are contiguous.
998            bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
999        } else {
1000            // We have no next buffer.  Compute the PTS of the frame following
1001            // the last frame in this buffer by computing the duration of of
1002            // this frame in media time units and adding it to the PTS of the
1003            // buffer.
1004            int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1005                               / mFrameSize;
1006
1007            if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1008                                                                &bufEnd)) {
1009                ALOGE("Failed to convert frame count of %lld to media time"
1010                      " duration" " (scale factor %d/%u) in %s",
1011                      frameCount,
1012                      mMediaTimeToSampleTransform.a_to_b_numer,
1013                      mMediaTimeToSampleTransform.a_to_b_denom,
1014                      __PRETTY_FUNCTION__);
1015                break;
1016            }
1017            bufEnd += mTimedBufferQueue[trimEnd].pts();
1018        }
1019
1020        if (bufEnd > mediaTimeNow)
1021            break;
1022
1023        // Is the buffer we want to use in the middle of a mix operation right
1024        // now?  If so, don't actually trim it.  Just wait for the releaseBuffer
1025        // from the mixer which should be coming back shortly.
1026        if (!trimEnd && mQueueHeadInFlight) {
1027            mTrimQueueHeadOnRelease = true;
1028        }
1029    }
1030
1031    size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1032    if (trimStart < trimEnd) {
1033        // Update the bookkeeping for framesReady()
1034        for (size_t i = trimStart; i < trimEnd; ++i) {
1035            updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1036        }
1037
1038        // Now actually remove the buffers from the queue.
1039        mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1040    }
1041}
1042
1043void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1044        const char* logTag) {
1045    ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1046                "%s called (reason \"%s\"), but timed buffer queue has no"
1047                " elements to trim.", __FUNCTION__, logTag);
1048
1049    updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1050    mTimedBufferQueue.removeAt(0);
1051}
1052
1053void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1054        const TimedBuffer& buf,
1055        const char* logTag) {
1056    uint32_t bufBytes        = buf.buffer()->size();
1057    uint32_t consumedAlready = buf.position();
1058
1059    ALOG_ASSERT(consumedAlready <= bufBytes,
1060                "Bad bookkeeping while updating frames pending.  Timed buffer is"
1061                " only %u bytes long, but claims to have consumed %u"
1062                " bytes.  (update reason: \"%s\")",
1063                bufBytes, consumedAlready, logTag);
1064
1065    uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1066    ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1067                "Bad bookkeeping while updating frames pending.  Should have at"
1068                " least %u queued frames, but we think we have only %u.  (update"
1069                " reason: \"%s\")",
1070                bufFrames, mFramesPendingInQueue, logTag);
1071
1072    mFramesPendingInQueue -= bufFrames;
1073}
1074
1075status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1076    const sp<IMemory>& buffer, int64_t pts) {
1077
1078    {
1079        Mutex::Autolock mttLock(mMediaTimeTransformLock);
1080        if (!mMediaTimeTransformValid)
1081            return INVALID_OPERATION;
1082    }
1083
1084    Mutex::Autolock _l(mTimedBufferQueueLock);
1085
1086    uint32_t bufFrames = buffer->size() / mFrameSize;
1087    mFramesPendingInQueue += bufFrames;
1088    mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1089
1090    return NO_ERROR;
1091}
1092
1093status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1094    const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1095
1096    ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1097           xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1098           target);
1099
1100    if (!(target == TimedAudioTrack::LOCAL_TIME ||
1101          target == TimedAudioTrack::COMMON_TIME)) {
1102        return BAD_VALUE;
1103    }
1104
1105    Mutex::Autolock lock(mMediaTimeTransformLock);
1106    mMediaTimeTransform = xform;
1107    mMediaTimeTransformTarget = target;
1108    mMediaTimeTransformValid = true;
1109
1110    return NO_ERROR;
1111}
1112
1113#define min(a, b) ((a) < (b) ? (a) : (b))
1114
1115// implementation of getNextBuffer for tracks whose buffers have timestamps
1116status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1117    AudioBufferProvider::Buffer* buffer, int64_t pts)
1118{
1119    if (pts == AudioBufferProvider::kInvalidPTS) {
1120        buffer->raw = NULL;
1121        buffer->frameCount = 0;
1122        mTimedAudioOutputOnTime = false;
1123        return INVALID_OPERATION;
1124    }
1125
1126    Mutex::Autolock _l(mTimedBufferQueueLock);
1127
1128    ALOG_ASSERT(!mQueueHeadInFlight,
1129                "getNextBuffer called without releaseBuffer!");
1130
1131    while (true) {
1132
1133        // if we have no timed buffers, then fail
1134        if (mTimedBufferQueue.isEmpty()) {
1135            buffer->raw = NULL;
1136            buffer->frameCount = 0;
1137            return NOT_ENOUGH_DATA;
1138        }
1139
1140        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1141
1142        // calculate the PTS of the head of the timed buffer queue expressed in
1143        // local time
1144        int64_t headLocalPTS;
1145        {
1146            Mutex::Autolock mttLock(mMediaTimeTransformLock);
1147
1148            ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1149
1150            if (mMediaTimeTransform.a_to_b_denom == 0) {
1151                // the transform represents a pause, so yield silence
1152                timedYieldSilence_l(buffer->frameCount, buffer);
1153                return NO_ERROR;
1154            }
1155
1156            int64_t transformedPTS;
1157            if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1158                                                        &transformedPTS)) {
1159                // the transform failed.  this shouldn't happen, but if it does
1160                // then just drop this buffer
1161                ALOGW("timedGetNextBuffer transform failed");
1162                buffer->raw = NULL;
1163                buffer->frameCount = 0;
1164                trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1165                return NO_ERROR;
1166            }
1167
1168            if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1169                if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1170                                                          &headLocalPTS)) {
1171                    buffer->raw = NULL;
1172                    buffer->frameCount = 0;
1173                    return INVALID_OPERATION;
1174                }
1175            } else {
1176                headLocalPTS = transformedPTS;
1177            }
1178        }
1179
1180        uint32_t sr = sampleRate();
1181
1182        // adjust the head buffer's PTS to reflect the portion of the head buffer
1183        // that has already been consumed
1184        int64_t effectivePTS = headLocalPTS +
1185                ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
1186
1187        // Calculate the delta in samples between the head of the input buffer
1188        // queue and the start of the next output buffer that will be written.
1189        // If the transformation fails because of over or underflow, it means
1190        // that the sample's position in the output stream is so far out of
1191        // whack that it should just be dropped.
1192        int64_t sampleDelta;
1193        if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1194            ALOGV("*** head buffer is too far from PTS: dropped buffer");
1195            trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1196                                       " mix");
1197            continue;
1198        }
1199        if (!mLocalTimeToSampleTransform.doForwardTransform(
1200                (effectivePTS - pts) << 32, &sampleDelta)) {
1201            ALOGV("*** too late during sample rate transform: dropped buffer");
1202            trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1203            continue;
1204        }
1205
1206        ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1207               " sampleDelta=[%d.%08x]",
1208               head.pts(), head.position(), pts,
1209               static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1210                   + (sampleDelta >> 32)),
1211               static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1212
1213        // if the delta between the ideal placement for the next input sample and
1214        // the current output position is within this threshold, then we will
1215        // concatenate the next input samples to the previous output
1216        const int64_t kSampleContinuityThreshold =
1217                (static_cast<int64_t>(sr) << 32) / 250;
1218
1219        // if this is the first buffer of audio that we're emitting from this track
1220        // then it should be almost exactly on time.
1221        const int64_t kSampleStartupThreshold = 1LL << 32;
1222
1223        if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1224           (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1225            // the next input is close enough to being on time, so concatenate it
1226            // with the last output
1227            timedYieldSamples_l(buffer);
1228
1229            ALOGVV("*** on time: head.pos=%d frameCount=%u",
1230                    head.position(), buffer->frameCount);
1231            return NO_ERROR;
1232        }
1233
1234        // Looks like our output is not on time.  Reset our on timed status.
1235        // Next time we mix samples from our input queue, then should be within
1236        // the StartupThreshold.
1237        mTimedAudioOutputOnTime = false;
1238        if (sampleDelta > 0) {
1239            // the gap between the current output position and the proper start of
1240            // the next input sample is too big, so fill it with silence
1241            uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1242
1243            timedYieldSilence_l(framesUntilNextInput, buffer);
1244            ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1245            return NO_ERROR;
1246        } else {
1247            // the next input sample is late
1248            uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1249            size_t onTimeSamplePosition =
1250                    head.position() + lateFrames * mFrameSize;
1251
1252            if (onTimeSamplePosition > head.buffer()->size()) {
1253                // all the remaining samples in the head are too late, so
1254                // drop it and move on
1255                ALOGV("*** too late: dropped buffer");
1256                trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1257                continue;
1258            } else {
1259                // skip over the late samples
1260                head.setPosition(onTimeSamplePosition);
1261
1262                // yield the available samples
1263                timedYieldSamples_l(buffer);
1264
1265                ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1266                return NO_ERROR;
1267            }
1268        }
1269    }
1270}
1271
1272// Yield samples from the timed buffer queue head up to the given output
1273// buffer's capacity.
1274//
1275// Caller must hold mTimedBufferQueueLock
1276void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1277    AudioBufferProvider::Buffer* buffer) {
1278
1279    const TimedBuffer& head = mTimedBufferQueue[0];
1280
1281    buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1282                   head.position());
1283
1284    uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1285                                 mFrameSize);
1286    size_t framesRequested = buffer->frameCount;
1287    buffer->frameCount = min(framesLeftInHead, framesRequested);
1288
1289    mQueueHeadInFlight = true;
1290    mTimedAudioOutputOnTime = true;
1291}
1292
1293// Yield samples of silence up to the given output buffer's capacity
1294//
1295// Caller must hold mTimedBufferQueueLock
1296void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1297    uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1298
1299    // lazily allocate a buffer filled with silence
1300    if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1301        delete [] mTimedSilenceBuffer;
1302        mTimedSilenceBufferSize = numFrames * mFrameSize;
1303        mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1304        memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1305    }
1306
1307    buffer->raw = mTimedSilenceBuffer;
1308    size_t framesRequested = buffer->frameCount;
1309    buffer->frameCount = min(numFrames, framesRequested);
1310
1311    mTimedAudioOutputOnTime = false;
1312}
1313
1314// AudioBufferProvider interface
1315void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1316    AudioBufferProvider::Buffer* buffer) {
1317
1318    Mutex::Autolock _l(mTimedBufferQueueLock);
1319
1320    // If the buffer which was just released is part of the buffer at the head
1321    // of the queue, be sure to update the amt of the buffer which has been
1322    // consumed.  If the buffer being returned is not part of the head of the
1323    // queue, its either because the buffer is part of the silence buffer, or
1324    // because the head of the timed queue was trimmed after the mixer called
1325    // getNextBuffer but before the mixer called releaseBuffer.
1326    if (buffer->raw == mTimedSilenceBuffer) {
1327        ALOG_ASSERT(!mQueueHeadInFlight,
1328                    "Queue head in flight during release of silence buffer!");
1329        goto done;
1330    }
1331
1332    ALOG_ASSERT(mQueueHeadInFlight,
1333                "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1334                " head in flight.");
1335
1336    if (mTimedBufferQueue.size()) {
1337        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1338
1339        void* start = head.buffer()->pointer();
1340        void* end   = reinterpret_cast<void*>(
1341                        reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1342                        + head.buffer()->size());
1343
1344        ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1345                    "released buffer not within the head of the timed buffer"
1346                    " queue; qHead = [%p, %p], released buffer = %p",
1347                    start, end, buffer->raw);
1348
1349        head.setPosition(head.position() +
1350                (buffer->frameCount * mFrameSize));
1351        mQueueHeadInFlight = false;
1352
1353        ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1354                    "Bad bookkeeping during releaseBuffer!  Should have at"
1355                    " least %u queued frames, but we think we have only %u",
1356                    buffer->frameCount, mFramesPendingInQueue);
1357
1358        mFramesPendingInQueue -= buffer->frameCount;
1359
1360        if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1361            || mTrimQueueHeadOnRelease) {
1362            trimTimedBufferQueueHead_l("releaseBuffer");
1363            mTrimQueueHeadOnRelease = false;
1364        }
1365    } else {
1366        LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1367                  " buffers in the timed buffer queue");
1368    }
1369
1370done:
1371    buffer->raw = 0;
1372    buffer->frameCount = 0;
1373}
1374
1375size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1376    Mutex::Autolock _l(mTimedBufferQueueLock);
1377    return mFramesPendingInQueue;
1378}
1379
1380AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1381        : mPTS(0), mPosition(0) {}
1382
1383AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1384    const sp<IMemory>& buffer, int64_t pts)
1385        : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1386
1387
1388// ----------------------------------------------------------------------------
1389
1390AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1391            PlaybackThread *playbackThread,
1392            DuplicatingThread *sourceThread,
1393            uint32_t sampleRate,
1394            audio_format_t format,
1395            audio_channel_mask_t channelMask,
1396            size_t frameCount)
1397    :   Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1398                NULL, 0, IAudioFlinger::TRACK_DEFAULT),
1399    mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
1400{
1401
1402    if (mCblk != NULL) {
1403        mOutBuffer.frameCount = 0;
1404        playbackThread->mTracks.add(this);
1405        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
1406                "mCblk->frameCount_ %u, mChannelMask 0x%08x",
1407                mCblk, mBuffer,
1408                mCblk->frameCount_, mChannelMask);
1409        // since client and server are in the same process,
1410        // the buffer has the same virtual address on both sides
1411        mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
1412        mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1413        mClientProxy->setSendLevel(0.0);
1414        mClientProxy->setSampleRate(sampleRate);
1415        mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1416                true /*clientInServer*/);
1417    } else {
1418        ALOGW("Error creating output track on thread %p", playbackThread);
1419    }
1420}
1421
1422AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1423{
1424    clearBufferQueue();
1425    delete mClientProxy;
1426    // superclass destructor will now delete the server proxy and shared memory both refer to
1427}
1428
1429status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1430                                                          int triggerSession)
1431{
1432    status_t status = Track::start(event, triggerSession);
1433    if (status != NO_ERROR) {
1434        return status;
1435    }
1436
1437    mActive = true;
1438    mRetryCount = 127;
1439    return status;
1440}
1441
1442void AudioFlinger::PlaybackThread::OutputTrack::stop()
1443{
1444    Track::stop();
1445    clearBufferQueue();
1446    mOutBuffer.frameCount = 0;
1447    mActive = false;
1448}
1449
1450bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1451{
1452    Buffer *pInBuffer;
1453    Buffer inBuffer;
1454    uint32_t channelCount = mChannelCount;
1455    bool outputBufferFull = false;
1456    inBuffer.frameCount = frames;
1457    inBuffer.i16 = data;
1458
1459    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1460
1461    if (!mActive && frames != 0) {
1462        start();
1463        sp<ThreadBase> thread = mThread.promote();
1464        if (thread != 0) {
1465            MixerThread *mixerThread = (MixerThread *)thread.get();
1466            if (mFrameCount > frames) {
1467                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1468                    uint32_t startFrames = (mFrameCount - frames);
1469                    pInBuffer = new Buffer;
1470                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1471                    pInBuffer->frameCount = startFrames;
1472                    pInBuffer->i16 = pInBuffer->mBuffer;
1473                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1474                    mBufferQueue.add(pInBuffer);
1475                } else {
1476                    ALOGW("OutputTrack::write() %p no more buffers in queue", this);
1477                }
1478            }
1479        }
1480    }
1481
1482    while (waitTimeLeftMs) {
1483        // First write pending buffers, then new data
1484        if (mBufferQueue.size()) {
1485            pInBuffer = mBufferQueue.itemAt(0);
1486        } else {
1487            pInBuffer = &inBuffer;
1488        }
1489
1490        if (pInBuffer->frameCount == 0) {
1491            break;
1492        }
1493
1494        if (mOutBuffer.frameCount == 0) {
1495            mOutBuffer.frameCount = pInBuffer->frameCount;
1496            nsecs_t startTime = systemTime();
1497            status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1498            if (status != NO_ERROR) {
1499                ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1500                        mThread.unsafe_get(), status);
1501                outputBufferFull = true;
1502                break;
1503            }
1504            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1505            if (waitTimeLeftMs >= waitTimeMs) {
1506                waitTimeLeftMs -= waitTimeMs;
1507            } else {
1508                waitTimeLeftMs = 0;
1509            }
1510        }
1511
1512        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1513                pInBuffer->frameCount;
1514        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
1515        Proxy::Buffer buf;
1516        buf.mFrameCount = outFrames;
1517        buf.mRaw = NULL;
1518        mClientProxy->releaseBuffer(&buf);
1519        pInBuffer->frameCount -= outFrames;
1520        pInBuffer->i16 += outFrames * channelCount;
1521        mOutBuffer.frameCount -= outFrames;
1522        mOutBuffer.i16 += outFrames * channelCount;
1523
1524        if (pInBuffer->frameCount == 0) {
1525            if (mBufferQueue.size()) {
1526                mBufferQueue.removeAt(0);
1527                delete [] pInBuffer->mBuffer;
1528                delete pInBuffer;
1529                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1530                        mThread.unsafe_get(), mBufferQueue.size());
1531            } else {
1532                break;
1533            }
1534        }
1535    }
1536
1537    // If we could not write all frames, allocate a buffer and queue it for next time.
1538    if (inBuffer.frameCount) {
1539        sp<ThreadBase> thread = mThread.promote();
1540        if (thread != 0 && !thread->standby()) {
1541            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1542                pInBuffer = new Buffer;
1543                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1544                pInBuffer->frameCount = inBuffer.frameCount;
1545                pInBuffer->i16 = pInBuffer->mBuffer;
1546                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1547                        sizeof(int16_t));
1548                mBufferQueue.add(pInBuffer);
1549                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1550                        mThread.unsafe_get(), mBufferQueue.size());
1551            } else {
1552                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1553                        mThread.unsafe_get(), this);
1554            }
1555        }
1556    }
1557
1558    // Calling write() with a 0 length buffer, means that no more data will be written:
1559    // If no more buffers are pending, fill output track buffer to make sure it is started
1560    // by output mixer.
1561    if (frames == 0 && mBufferQueue.size() == 0) {
1562        // FIXME borken, replace by getting framesReady() from proxy
1563        size_t user = 0;    // was mCblk->user
1564        if (user < mFrameCount) {
1565            frames = mFrameCount - user;
1566            pInBuffer = new Buffer;
1567            pInBuffer->mBuffer = new int16_t[frames * channelCount];
1568            pInBuffer->frameCount = frames;
1569            pInBuffer->i16 = pInBuffer->mBuffer;
1570            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1571            mBufferQueue.add(pInBuffer);
1572        } else if (mActive) {
1573            stop();
1574        }
1575    }
1576
1577    return outputBufferFull;
1578}
1579
1580status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1581        AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1582{
1583    ClientProxy::Buffer buf;
1584    buf.mFrameCount = buffer->frameCount;
1585    struct timespec timeout;
1586    timeout.tv_sec = waitTimeMs / 1000;
1587    timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1588    status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1589    buffer->frameCount = buf.mFrameCount;
1590    buffer->raw = buf.mRaw;
1591    return status;
1592}
1593
1594void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1595{
1596    size_t size = mBufferQueue.size();
1597
1598    for (size_t i = 0; i < size; i++) {
1599        Buffer *pBuffer = mBufferQueue.itemAt(i);
1600        delete [] pBuffer->mBuffer;
1601        delete pBuffer;
1602    }
1603    mBufferQueue.clear();
1604}
1605
1606
1607// ----------------------------------------------------------------------------
1608//      Record
1609// ----------------------------------------------------------------------------
1610
1611AudioFlinger::RecordHandle::RecordHandle(
1612        const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1613    : BnAudioRecord(),
1614    mRecordTrack(recordTrack)
1615{
1616}
1617
1618AudioFlinger::RecordHandle::~RecordHandle() {
1619    stop_nonvirtual();
1620    mRecordTrack->destroy();
1621}
1622
1623sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1624    return mRecordTrack->getCblk();
1625}
1626
1627status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1628        int triggerSession) {
1629    ALOGV("RecordHandle::start()");
1630    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1631}
1632
1633void AudioFlinger::RecordHandle::stop() {
1634    stop_nonvirtual();
1635}
1636
1637void AudioFlinger::RecordHandle::stop_nonvirtual() {
1638    ALOGV("RecordHandle::stop()");
1639    mRecordTrack->stop();
1640}
1641
1642status_t AudioFlinger::RecordHandle::onTransact(
1643    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1644{
1645    return BnAudioRecord::onTransact(code, data, reply, flags);
1646}
1647
1648// ----------------------------------------------------------------------------
1649
1650// RecordTrack constructor must be called with AudioFlinger::mLock held
1651AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1652            RecordThread *thread,
1653            const sp<Client>& client,
1654            uint32_t sampleRate,
1655            audio_format_t format,
1656            audio_channel_mask_t channelMask,
1657            size_t frameCount,
1658            int sessionId)
1659    :   TrackBase(thread, client, sampleRate, format,
1660                  channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
1661        mOverflow(false)
1662{
1663    ALOGV("RecordTrack constructor");
1664    if (mCblk != NULL) {
1665        mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount, mFrameSize);
1666    }
1667}
1668
1669AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1670{
1671    ALOGV("%s", __func__);
1672}
1673
1674// AudioBufferProvider interface
1675status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1676        int64_t pts)
1677{
1678    ServerProxy::Buffer buf;
1679    buf.mFrameCount = buffer->frameCount;
1680    status_t status = mServerProxy->obtainBuffer(&buf);
1681    buffer->frameCount = buf.mFrameCount;
1682    buffer->raw = buf.mRaw;
1683    if (buf.mFrameCount == 0) {
1684        // FIXME also wake futex so that overrun is noticed more quickly
1685        (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
1686    }
1687    return status;
1688}
1689
1690status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1691                                                        int triggerSession)
1692{
1693    sp<ThreadBase> thread = mThread.promote();
1694    if (thread != 0) {
1695        RecordThread *recordThread = (RecordThread *)thread.get();
1696        return recordThread->start(this, event, triggerSession);
1697    } else {
1698        return BAD_VALUE;
1699    }
1700}
1701
1702void AudioFlinger::RecordThread::RecordTrack::stop()
1703{
1704    sp<ThreadBase> thread = mThread.promote();
1705    if (thread != 0) {
1706        RecordThread *recordThread = (RecordThread *)thread.get();
1707        if (recordThread->stop(this)) {
1708            AudioSystem::stopInput(recordThread->id());
1709        }
1710    }
1711}
1712
1713void AudioFlinger::RecordThread::RecordTrack::destroy()
1714{
1715    // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1716    sp<RecordTrack> keep(this);
1717    {
1718        sp<ThreadBase> thread = mThread.promote();
1719        if (thread != 0) {
1720            if (mState == ACTIVE || mState == RESUMING) {
1721                AudioSystem::stopInput(thread->id());
1722            }
1723            AudioSystem::releaseInput(thread->id());
1724            Mutex::Autolock _l(thread->mLock);
1725            RecordThread *recordThread = (RecordThread *) thread.get();
1726            recordThread->destroyTrack_l(this);
1727        }
1728    }
1729}
1730
1731
1732/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1733{
1734    result.append("Client Fmt Chn mask Session S   Server fCount\n");
1735}
1736
1737void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1738{
1739    snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
1740            (mClient == 0) ? getpid_cached : mClient->pid(),
1741            mFormat,
1742            mChannelMask,
1743            mSessionId,
1744            mState,
1745            mCblk->mServer,
1746            mFrameCount);
1747}
1748
1749}; // namespace android
1750