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