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