Tracks.cpp revision fc38a2e0268b5e531db2975c3a81462a3593c861
1/*
2**
3** Copyright 2012, The Android Open Source Project
4**
5** Licensed under the Apache License, Version 2.0 (the "License");
6** you may not use this file except in compliance with the License.
7** You may obtain a copy of the License at
8**
9**     http://www.apache.org/licenses/LICENSE-2.0
10**
11** Unless required by applicable law or agreed to in writing, software
12** distributed under the License is distributed on an "AS IS" BASIS,
13** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14** See the License for the specific language governing permissions and
15** limitations under the License.
16*/
17
18
19#define LOG_TAG "AudioFlinger"
20//#define LOG_NDEBUG 0
21
22#include "Configuration.h"
23#include <math.h>
24#include <cutils/compiler.h>
25#include <utils/Log.h>
26
27#include <private/media/AudioTrackShared.h>
28
29#include <common_time/cc_helper.h>
30#include <common_time/local_clock.h>
31
32#include "AudioMixer.h"
33#include "AudioFlinger.h"
34#include "ServiceUtilities.h"
35
36#include <media/nbaio/Pipe.h>
37#include <media/nbaio/PipeReader.h>
38
39// ----------------------------------------------------------------------------
40
41// Note: the following macro is used for extremely verbose logging message.  In
42// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
43// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
44// are so verbose that we want to suppress them even when we have ALOG_ASSERT
45// turned on.  Do not uncomment the #def below unless you really know what you
46// are doing and want to see all of the extremely verbose messages.
47//#define VERY_VERY_VERBOSE_LOGGING
48#ifdef VERY_VERY_VERBOSE_LOGGING
49#define ALOGVV ALOGV
50#else
51#define ALOGVV(a...) do { } while(0)
52#endif
53
54namespace android {
55
56// ----------------------------------------------------------------------------
57//      TrackBase
58// ----------------------------------------------------------------------------
59
60static volatile int32_t nextTrackId = 55;
61
62// TrackBase constructor must be called with AudioFlinger::mLock held
63AudioFlinger::ThreadBase::TrackBase::TrackBase(
64            ThreadBase *thread,
65            const sp<Client>& client,
66            uint32_t sampleRate,
67            audio_format_t format,
68            audio_channel_mask_t channelMask,
69            size_t frameCount,
70            const sp<IMemory>& sharedBuffer,
71            int sessionId,
72            bool isOut)
73    :   RefBase(),
74        mThread(thread),
75        mClient(client),
76        mCblk(NULL),
77        // mBuffer
78        // mBufferEnd
79        mStepCount(0),
80        mState(IDLE),
81        mSampleRate(sampleRate),
82        mFormat(format),
83        mChannelMask(channelMask),
84        mChannelCount(popcount(channelMask)),
85        mFrameSize(audio_is_linear_pcm(format) ?
86                mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
87        mFrameCount(frameCount),
88        mStepServerFailed(false),
89        mSessionId(sessionId),
90        mIsOut(isOut),
91        mServerProxy(NULL),
92        mId(android_atomic_inc(&nextTrackId))
93{
94    // client == 0 implies sharedBuffer == 0
95    ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
96
97    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
98            sharedBuffer->size());
99
100    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
101    size_t size = sizeof(audio_track_cblk_t);
102    size_t bufferSize = (sharedBuffer == 0 ? roundup(frameCount) : frameCount) * mFrameSize;
103    if (sharedBuffer == 0) {
104        size += bufferSize;
105    }
106
107    if (client != 0) {
108        mCblkMemory = client->heap()->allocate(size);
109        if (mCblkMemory != 0) {
110            mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer());
111            // can't assume mCblk != NULL
112        } else {
113            ALOGE("not enough memory for AudioTrack size=%u", size);
114            client->heap()->dump("AudioTrack");
115            return;
116        }
117    } else {
118        // this syntax avoids calling the audio_track_cblk_t constructor twice
119        mCblk = (audio_track_cblk_t *) new uint8_t[size];
120        // assume mCblk != NULL
121    }
122
123    // construct the shared structure in-place.
124    if (mCblk != NULL) {
125        new(mCblk) audio_track_cblk_t();
126        // clear all buffers
127        mCblk->frameCount_ = frameCount;
128        if (sharedBuffer == 0) {
129            mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
130            memset(mBuffer, 0, bufferSize);
131        } else {
132            mBuffer = sharedBuffer->pointer();
133#if 0
134            mCblk->flags = CBLK_FORCEREADY;     // FIXME hack, need to fix the track ready logic
135#endif
136        }
137        mBufferEnd = (uint8_t *)mBuffer + bufferSize;
138
139#ifdef TEE_SINK
140        if (mTeeSinkTrackEnabled) {
141            NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount);
142            if (pipeFormat != Format_Invalid) {
143                Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
144                size_t numCounterOffers = 0;
145                const NBAIO_Format offers[1] = {pipeFormat};
146                ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
147                ALOG_ASSERT(index == 0);
148                PipeReader *pipeReader = new PipeReader(*pipe);
149                numCounterOffers = 0;
150                index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
151                ALOG_ASSERT(index == 0);
152                mTeeSink = pipe;
153                mTeeSource = pipeReader;
154            }
155        }
156#endif
157
158    }
159}
160
161AudioFlinger::ThreadBase::TrackBase::~TrackBase()
162{
163#ifdef TEE_SINK
164    dumpTee(-1, mTeeSource, mId);
165#endif
166    // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
167    delete mServerProxy;
168    if (mCblk != NULL) {
169        if (mClient == 0) {
170            delete mCblk;
171        } else {
172            mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
173        }
174    }
175    mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
176    if (mClient != 0) {
177        // Client destructor must run with AudioFlinger mutex locked
178        Mutex::Autolock _l(mClient->audioFlinger()->mLock);
179        // If the client's reference count drops to zero, the associated destructor
180        // must run with AudioFlinger lock held. Thus the explicit clear() rather than
181        // relying on the automatic clear() at end of scope.
182        mClient.clear();
183    }
184}
185
186// AudioBufferProvider interface
187// getNextBuffer() = 0;
188// This implementation of releaseBuffer() is used by Track and RecordTrack, but not TimedTrack
189void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
190{
191#ifdef TEE_SINK
192    if (mTeeSink != 0) {
193        (void) mTeeSink->write(buffer->raw, buffer->frameCount);
194    }
195#endif
196
197    ServerProxy::Buffer buf;
198    buf.mFrameCount = buffer->frameCount;
199    buf.mRaw = buffer->raw;
200    buffer->frameCount = 0;
201    buffer->raw = NULL;
202    mServerProxy->releaseBuffer(&buf);
203}
204
205status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
206{
207    mSyncEvents.add(event);
208    return NO_ERROR;
209}
210
211// ----------------------------------------------------------------------------
212//      Playback
213// ----------------------------------------------------------------------------
214
215AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
216    : BnAudioTrack(),
217      mTrack(track)
218{
219}
220
221AudioFlinger::TrackHandle::~TrackHandle() {
222    // just stop the track on deletion, associated resources
223    // will be freed from the main thread once all pending buffers have
224    // been played. Unless it's not in the active track list, in which
225    // case we free everything now...
226    mTrack->destroy();
227}
228
229sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
230    return mTrack->getCblk();
231}
232
233status_t AudioFlinger::TrackHandle::start() {
234    return mTrack->start();
235}
236
237void AudioFlinger::TrackHandle::stop() {
238    mTrack->stop();
239}
240
241void AudioFlinger::TrackHandle::flush() {
242    mTrack->flush();
243}
244
245void AudioFlinger::TrackHandle::pause() {
246    mTrack->pause();
247}
248
249status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
250    return INVALID_OPERATION;   // stub function
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        // Force underrun condition to avoid false underrun callback until first data is
675        // written to buffer
676        android_atomic_and(~CBLK_FORCEREADY, &mCblk->flags);
677        mFillingUpStatus = FS_FILLING;
678        mResetDone = true;
679        if (mState == FLUSHED) {
680            mState = IDLE;
681        }
682    }
683}
684
685status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
686{
687    status_t status = DEAD_OBJECT;
688    sp<ThreadBase> thread = mThread.promote();
689    if (thread != 0) {
690        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
691        sp<AudioFlinger> af = mClient->audioFlinger();
692
693        Mutex::Autolock _l(af->mLock);
694
695        sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
696
697        if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
698            Mutex::Autolock _dl(playbackThread->mLock);
699            Mutex::Autolock _sl(srcThread->mLock);
700            sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
701            if (chain == 0) {
702                return INVALID_OPERATION;
703            }
704
705            sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
706            if (effect == 0) {
707                return INVALID_OPERATION;
708            }
709            srcThread->removeEffect_l(effect);
710            playbackThread->addEffect_l(effect);
711            // removeEffect_l() has stopped the effect if it was active so it must be restarted
712            if (effect->state() == EffectModule::ACTIVE ||
713                    effect->state() == EffectModule::STOPPING) {
714                effect->start();
715            }
716
717            sp<EffectChain> dstChain = effect->chain().promote();
718            if (dstChain == 0) {
719                srcThread->addEffect_l(effect);
720                return INVALID_OPERATION;
721            }
722            AudioSystem::unregisterEffect(effect->id());
723            AudioSystem::registerEffect(&effect->desc(),
724                                        srcThread->id(),
725                                        dstChain->strategy(),
726                                        AUDIO_SESSION_OUTPUT_MIX,
727                                        effect->id());
728        }
729        status = playbackThread->attachAuxEffect(this, EffectId);
730    }
731    return status;
732}
733
734void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
735{
736    mAuxEffectId = EffectId;
737    mAuxBuffer = buffer;
738}
739
740bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
741                                                         size_t audioHalFrames)
742{
743    // a track is considered presented when the total number of frames written to audio HAL
744    // corresponds to the number of frames written when presentationComplete() is called for the
745    // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
746    if (mPresentationCompleteFrames == 0) {
747        mPresentationCompleteFrames = framesWritten + audioHalFrames;
748        ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
749                  mPresentationCompleteFrames, audioHalFrames);
750    }
751    if (framesWritten >= mPresentationCompleteFrames) {
752        ALOGV("presentationComplete() session %d complete: framesWritten %d",
753                  mSessionId, framesWritten);
754        triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
755        return true;
756    }
757    return false;
758}
759
760void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
761{
762    for (int i = 0; i < (int)mSyncEvents.size(); i++) {
763        if (mSyncEvents[i]->type() == type) {
764            mSyncEvents[i]->trigger();
765            mSyncEvents.removeAt(i);
766            i--;
767        }
768    }
769}
770
771// implement VolumeBufferProvider interface
772
773uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
774{
775    // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
776    ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
777    uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
778    uint32_t vl = vlr & 0xFFFF;
779    uint32_t vr = vlr >> 16;
780    // track volumes come from shared memory, so can't be trusted and must be clamped
781    if (vl > MAX_GAIN_INT) {
782        vl = MAX_GAIN_INT;
783    }
784    if (vr > MAX_GAIN_INT) {
785        vr = MAX_GAIN_INT;
786    }
787    // now apply the cached master volume and stream type volume;
788    // this is trusted but lacks any synchronization or barrier so may be stale
789    float v = mCachedVolume;
790    vl *= v;
791    vr *= v;
792    // re-combine into U4.16
793    vlr = (vr << 16) | (vl & 0xFFFF);
794    // FIXME look at mute, pause, and stop flags
795    return vlr;
796}
797
798status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
799{
800    if (mState == TERMINATED || mState == PAUSED ||
801            ((framesReady() == 0) && ((mSharedBuffer != 0) ||
802                                      (mState == STOPPED)))) {
803        ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
804              mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
805        event->cancel();
806        return INVALID_OPERATION;
807    }
808    (void) TrackBase::setSyncEvent(event);
809    return NO_ERROR;
810}
811
812void AudioFlinger::PlaybackThread::Track::invalidate()
813{
814    // FIXME should use proxy, and needs work
815    audio_track_cblk_t* cblk = mCblk;
816    android_atomic_or(CBLK_INVALID, &cblk->flags);
817    android_atomic_release_store(0x40000000, &cblk->mFutex);
818    // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
819    (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
820    mIsInvalid = true;
821}
822
823// ----------------------------------------------------------------------------
824
825sp<AudioFlinger::PlaybackThread::TimedTrack>
826AudioFlinger::PlaybackThread::TimedTrack::create(
827            PlaybackThread *thread,
828            const sp<Client>& client,
829            audio_stream_type_t streamType,
830            uint32_t sampleRate,
831            audio_format_t format,
832            audio_channel_mask_t channelMask,
833            size_t frameCount,
834            const sp<IMemory>& sharedBuffer,
835            int sessionId) {
836    if (!client->reserveTimedTrack())
837        return 0;
838
839    return new TimedTrack(
840        thread, client, streamType, sampleRate, format, channelMask, frameCount,
841        sharedBuffer, sessionId);
842}
843
844AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
845            PlaybackThread *thread,
846            const sp<Client>& client,
847            audio_stream_type_t streamType,
848            uint32_t sampleRate,
849            audio_format_t format,
850            audio_channel_mask_t channelMask,
851            size_t frameCount,
852            const sp<IMemory>& sharedBuffer,
853            int sessionId)
854    : Track(thread, client, streamType, sampleRate, format, channelMask,
855            frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
856      mQueueHeadInFlight(false),
857      mTrimQueueHeadOnRelease(false),
858      mFramesPendingInQueue(0),
859      mTimedSilenceBuffer(NULL),
860      mTimedSilenceBufferSize(0),
861      mTimedAudioOutputOnTime(false),
862      mMediaTimeTransformValid(false)
863{
864    LocalClock lc;
865    mLocalTimeFreq = lc.getLocalFreq();
866
867    mLocalTimeToSampleTransform.a_zero = 0;
868    mLocalTimeToSampleTransform.b_zero = 0;
869    mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
870    mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
871    LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
872                            &mLocalTimeToSampleTransform.a_to_b_denom);
873
874    mMediaTimeToSampleTransform.a_zero = 0;
875    mMediaTimeToSampleTransform.b_zero = 0;
876    mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
877    mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
878    LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
879                            &mMediaTimeToSampleTransform.a_to_b_denom);
880}
881
882AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
883    mClient->releaseTimedTrack();
884    delete [] mTimedSilenceBuffer;
885}
886
887status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
888    size_t size, sp<IMemory>* buffer) {
889
890    Mutex::Autolock _l(mTimedBufferQueueLock);
891
892    trimTimedBufferQueue_l();
893
894    // lazily initialize the shared memory heap for timed buffers
895    if (mTimedMemoryDealer == NULL) {
896        const int kTimedBufferHeapSize = 512 << 10;
897
898        mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
899                                              "AudioFlingerTimed");
900        if (mTimedMemoryDealer == NULL)
901            return NO_MEMORY;
902    }
903
904    sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
905    if (newBuffer == NULL) {
906        newBuffer = mTimedMemoryDealer->allocate(size);
907        if (newBuffer == NULL)
908            return NO_MEMORY;
909    }
910
911    *buffer = newBuffer;
912    return NO_ERROR;
913}
914
915// caller must hold mTimedBufferQueueLock
916void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
917    int64_t mediaTimeNow;
918    {
919        Mutex::Autolock mttLock(mMediaTimeTransformLock);
920        if (!mMediaTimeTransformValid)
921            return;
922
923        int64_t targetTimeNow;
924        status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
925            ? mCCHelper.getCommonTime(&targetTimeNow)
926            : mCCHelper.getLocalTime(&targetTimeNow);
927
928        if (OK != res)
929            return;
930
931        if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
932                                                    &mediaTimeNow)) {
933            return;
934        }
935    }
936
937    size_t trimEnd;
938    for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
939        int64_t bufEnd;
940
941        if ((trimEnd + 1) < mTimedBufferQueue.size()) {
942            // We have a next buffer.  Just use its PTS as the PTS of the frame
943            // following the last frame in this buffer.  If the stream is sparse
944            // (ie, there are deliberate gaps left in the stream which should be
945            // filled with silence by the TimedAudioTrack), then this can result
946            // in one extra buffer being left un-trimmed when it could have
947            // been.  In general, this is not typical, and we would rather
948            // optimized away the TS calculation below for the more common case
949            // where PTSes are contiguous.
950            bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
951        } else {
952            // We have no next buffer.  Compute the PTS of the frame following
953            // the last frame in this buffer by computing the duration of of
954            // this frame in media time units and adding it to the PTS of the
955            // buffer.
956            int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
957                               / mFrameSize;
958
959            if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
960                                                                &bufEnd)) {
961                ALOGE("Failed to convert frame count of %lld to media time"
962                      " duration" " (scale factor %d/%u) in %s",
963                      frameCount,
964                      mMediaTimeToSampleTransform.a_to_b_numer,
965                      mMediaTimeToSampleTransform.a_to_b_denom,
966                      __PRETTY_FUNCTION__);
967                break;
968            }
969            bufEnd += mTimedBufferQueue[trimEnd].pts();
970        }
971
972        if (bufEnd > mediaTimeNow)
973            break;
974
975        // Is the buffer we want to use in the middle of a mix operation right
976        // now?  If so, don't actually trim it.  Just wait for the releaseBuffer
977        // from the mixer which should be coming back shortly.
978        if (!trimEnd && mQueueHeadInFlight) {
979            mTrimQueueHeadOnRelease = true;
980        }
981    }
982
983    size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
984    if (trimStart < trimEnd) {
985        // Update the bookkeeping for framesReady()
986        for (size_t i = trimStart; i < trimEnd; ++i) {
987            updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
988        }
989
990        // Now actually remove the buffers from the queue.
991        mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
992    }
993}
994
995void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
996        const char* logTag) {
997    ALOG_ASSERT(mTimedBufferQueue.size() > 0,
998                "%s called (reason \"%s\"), but timed buffer queue has no"
999                " elements to trim.", __FUNCTION__, logTag);
1000
1001    updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1002    mTimedBufferQueue.removeAt(0);
1003}
1004
1005void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1006        const TimedBuffer& buf,
1007        const char* logTag) {
1008    uint32_t bufBytes        = buf.buffer()->size();
1009    uint32_t consumedAlready = buf.position();
1010
1011    ALOG_ASSERT(consumedAlready <= bufBytes,
1012                "Bad bookkeeping while updating frames pending.  Timed buffer is"
1013                " only %u bytes long, but claims to have consumed %u"
1014                " bytes.  (update reason: \"%s\")",
1015                bufBytes, consumedAlready, logTag);
1016
1017    uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1018    ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1019                "Bad bookkeeping while updating frames pending.  Should have at"
1020                " least %u queued frames, but we think we have only %u.  (update"
1021                " reason: \"%s\")",
1022                bufFrames, mFramesPendingInQueue, logTag);
1023
1024    mFramesPendingInQueue -= bufFrames;
1025}
1026
1027status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1028    const sp<IMemory>& buffer, int64_t pts) {
1029
1030    {
1031        Mutex::Autolock mttLock(mMediaTimeTransformLock);
1032        if (!mMediaTimeTransformValid)
1033            return INVALID_OPERATION;
1034    }
1035
1036    Mutex::Autolock _l(mTimedBufferQueueLock);
1037
1038    uint32_t bufFrames = buffer->size() / mFrameSize;
1039    mFramesPendingInQueue += bufFrames;
1040    mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1041
1042    return NO_ERROR;
1043}
1044
1045status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1046    const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1047
1048    ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1049           xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1050           target);
1051
1052    if (!(target == TimedAudioTrack::LOCAL_TIME ||
1053          target == TimedAudioTrack::COMMON_TIME)) {
1054        return BAD_VALUE;
1055    }
1056
1057    Mutex::Autolock lock(mMediaTimeTransformLock);
1058    mMediaTimeTransform = xform;
1059    mMediaTimeTransformTarget = target;
1060    mMediaTimeTransformValid = true;
1061
1062    return NO_ERROR;
1063}
1064
1065#define min(a, b) ((a) < (b) ? (a) : (b))
1066
1067// implementation of getNextBuffer for tracks whose buffers have timestamps
1068status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1069    AudioBufferProvider::Buffer* buffer, int64_t pts)
1070{
1071    if (pts == AudioBufferProvider::kInvalidPTS) {
1072        buffer->raw = NULL;
1073        buffer->frameCount = 0;
1074        mTimedAudioOutputOnTime = false;
1075        return INVALID_OPERATION;
1076    }
1077
1078    Mutex::Autolock _l(mTimedBufferQueueLock);
1079
1080    ALOG_ASSERT(!mQueueHeadInFlight,
1081                "getNextBuffer called without releaseBuffer!");
1082
1083    while (true) {
1084
1085        // if we have no timed buffers, then fail
1086        if (mTimedBufferQueue.isEmpty()) {
1087            buffer->raw = NULL;
1088            buffer->frameCount = 0;
1089            return NOT_ENOUGH_DATA;
1090        }
1091
1092        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1093
1094        // calculate the PTS of the head of the timed buffer queue expressed in
1095        // local time
1096        int64_t headLocalPTS;
1097        {
1098            Mutex::Autolock mttLock(mMediaTimeTransformLock);
1099
1100            ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1101
1102            if (mMediaTimeTransform.a_to_b_denom == 0) {
1103                // the transform represents a pause, so yield silence
1104                timedYieldSilence_l(buffer->frameCount, buffer);
1105                return NO_ERROR;
1106            }
1107
1108            int64_t transformedPTS;
1109            if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1110                                                        &transformedPTS)) {
1111                // the transform failed.  this shouldn't happen, but if it does
1112                // then just drop this buffer
1113                ALOGW("timedGetNextBuffer transform failed");
1114                buffer->raw = NULL;
1115                buffer->frameCount = 0;
1116                trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1117                return NO_ERROR;
1118            }
1119
1120            if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1121                if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1122                                                          &headLocalPTS)) {
1123                    buffer->raw = NULL;
1124                    buffer->frameCount = 0;
1125                    return INVALID_OPERATION;
1126                }
1127            } else {
1128                headLocalPTS = transformedPTS;
1129            }
1130        }
1131
1132        // adjust the head buffer's PTS to reflect the portion of the head buffer
1133        // that has already been consumed
1134        int64_t effectivePTS = headLocalPTS +
1135                ((head.position() / mFrameSize) * mLocalTimeFreq / sampleRate());
1136
1137        // Calculate the delta in samples between the head of the input buffer
1138        // queue and the start of the next output buffer that will be written.
1139        // If the transformation fails because of over or underflow, it means
1140        // that the sample's position in the output stream is so far out of
1141        // whack that it should just be dropped.
1142        int64_t sampleDelta;
1143        if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1144            ALOGV("*** head buffer is too far from PTS: dropped buffer");
1145            trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1146                                       " mix");
1147            continue;
1148        }
1149        if (!mLocalTimeToSampleTransform.doForwardTransform(
1150                (effectivePTS - pts) << 32, &sampleDelta)) {
1151            ALOGV("*** too late during sample rate transform: dropped buffer");
1152            trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1153            continue;
1154        }
1155
1156        ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1157               " sampleDelta=[%d.%08x]",
1158               head.pts(), head.position(), pts,
1159               static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1160                   + (sampleDelta >> 32)),
1161               static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1162
1163        // if the delta between the ideal placement for the next input sample and
1164        // the current output position is within this threshold, then we will
1165        // concatenate the next input samples to the previous output
1166        const int64_t kSampleContinuityThreshold =
1167                (static_cast<int64_t>(sampleRate()) << 32) / 250;
1168
1169        // if this is the first buffer of audio that we're emitting from this track
1170        // then it should be almost exactly on time.
1171        const int64_t kSampleStartupThreshold = 1LL << 32;
1172
1173        if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1174           (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1175            // the next input is close enough to being on time, so concatenate it
1176            // with the last output
1177            timedYieldSamples_l(buffer);
1178
1179            ALOGVV("*** on time: head.pos=%d frameCount=%u",
1180                    head.position(), buffer->frameCount);
1181            return NO_ERROR;
1182        }
1183
1184        // Looks like our output is not on time.  Reset our on timed status.
1185        // Next time we mix samples from our input queue, then should be within
1186        // the StartupThreshold.
1187        mTimedAudioOutputOnTime = false;
1188        if (sampleDelta > 0) {
1189            // the gap between the current output position and the proper start of
1190            // the next input sample is too big, so fill it with silence
1191            uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1192
1193            timedYieldSilence_l(framesUntilNextInput, buffer);
1194            ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1195            return NO_ERROR;
1196        } else {
1197            // the next input sample is late
1198            uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1199            size_t onTimeSamplePosition =
1200                    head.position() + lateFrames * mFrameSize;
1201
1202            if (onTimeSamplePosition > head.buffer()->size()) {
1203                // all the remaining samples in the head are too late, so
1204                // drop it and move on
1205                ALOGV("*** too late: dropped buffer");
1206                trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1207                continue;
1208            } else {
1209                // skip over the late samples
1210                head.setPosition(onTimeSamplePosition);
1211
1212                // yield the available samples
1213                timedYieldSamples_l(buffer);
1214
1215                ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1216                return NO_ERROR;
1217            }
1218        }
1219    }
1220}
1221
1222// Yield samples from the timed buffer queue head up to the given output
1223// buffer's capacity.
1224//
1225// Caller must hold mTimedBufferQueueLock
1226void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1227    AudioBufferProvider::Buffer* buffer) {
1228
1229    const TimedBuffer& head = mTimedBufferQueue[0];
1230
1231    buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1232                   head.position());
1233
1234    uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1235                                 mFrameSize);
1236    size_t framesRequested = buffer->frameCount;
1237    buffer->frameCount = min(framesLeftInHead, framesRequested);
1238
1239    mQueueHeadInFlight = true;
1240    mTimedAudioOutputOnTime = true;
1241}
1242
1243// Yield samples of silence up to the given output buffer's capacity
1244//
1245// Caller must hold mTimedBufferQueueLock
1246void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1247    uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1248
1249    // lazily allocate a buffer filled with silence
1250    if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1251        delete [] mTimedSilenceBuffer;
1252        mTimedSilenceBufferSize = numFrames * mFrameSize;
1253        mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1254        memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1255    }
1256
1257    buffer->raw = mTimedSilenceBuffer;
1258    size_t framesRequested = buffer->frameCount;
1259    buffer->frameCount = min(numFrames, framesRequested);
1260
1261    mTimedAudioOutputOnTime = false;
1262}
1263
1264// AudioBufferProvider interface
1265void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1266    AudioBufferProvider::Buffer* buffer) {
1267
1268    Mutex::Autolock _l(mTimedBufferQueueLock);
1269
1270    // If the buffer which was just released is part of the buffer at the head
1271    // of the queue, be sure to update the amt of the buffer which has been
1272    // consumed.  If the buffer being returned is not part of the head of the
1273    // queue, its either because the buffer is part of the silence buffer, or
1274    // because the head of the timed queue was trimmed after the mixer called
1275    // getNextBuffer but before the mixer called releaseBuffer.
1276    if (buffer->raw == mTimedSilenceBuffer) {
1277        ALOG_ASSERT(!mQueueHeadInFlight,
1278                    "Queue head in flight during release of silence buffer!");
1279        goto done;
1280    }
1281
1282    ALOG_ASSERT(mQueueHeadInFlight,
1283                "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1284                " head in flight.");
1285
1286    if (mTimedBufferQueue.size()) {
1287        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1288
1289        void* start = head.buffer()->pointer();
1290        void* end   = reinterpret_cast<void*>(
1291                        reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1292                        + head.buffer()->size());
1293
1294        ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1295                    "released buffer not within the head of the timed buffer"
1296                    " queue; qHead = [%p, %p], released buffer = %p",
1297                    start, end, buffer->raw);
1298
1299        head.setPosition(head.position() +
1300                (buffer->frameCount * mFrameSize));
1301        mQueueHeadInFlight = false;
1302
1303        ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1304                    "Bad bookkeeping during releaseBuffer!  Should have at"
1305                    " least %u queued frames, but we think we have only %u",
1306                    buffer->frameCount, mFramesPendingInQueue);
1307
1308        mFramesPendingInQueue -= buffer->frameCount;
1309
1310        if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1311            || mTrimQueueHeadOnRelease) {
1312            trimTimedBufferQueueHead_l("releaseBuffer");
1313            mTrimQueueHeadOnRelease = false;
1314        }
1315    } else {
1316        LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1317                  " buffers in the timed buffer queue");
1318    }
1319
1320done:
1321    buffer->raw = 0;
1322    buffer->frameCount = 0;
1323}
1324
1325size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1326    Mutex::Autolock _l(mTimedBufferQueueLock);
1327    return mFramesPendingInQueue;
1328}
1329
1330AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1331        : mPTS(0), mPosition(0) {}
1332
1333AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1334    const sp<IMemory>& buffer, int64_t pts)
1335        : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1336
1337
1338// ----------------------------------------------------------------------------
1339
1340AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1341            PlaybackThread *playbackThread,
1342            DuplicatingThread *sourceThread,
1343            uint32_t sampleRate,
1344            audio_format_t format,
1345            audio_channel_mask_t channelMask,
1346            size_t frameCount)
1347    :   Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1348                NULL, 0, IAudioFlinger::TRACK_DEFAULT),
1349    mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
1350{
1351
1352    if (mCblk != NULL) {
1353        mOutBuffer.frameCount = 0;
1354        playbackThread->mTracks.add(this);
1355        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
1356                "mCblk->frameCount_ %u, mChannelMask 0x%08x mBufferEnd %p",
1357                mCblk, mBuffer,
1358                mCblk->frameCount_, mChannelMask, mBufferEnd);
1359        // since client and server are in the same process,
1360        // the buffer has the same virtual address on both sides
1361        mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
1362        mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1363        mClientProxy->setSendLevel(0.0);
1364        mClientProxy->setSampleRate(sampleRate);
1365        mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1366                true /*clientInServer*/);
1367    } else {
1368        ALOGW("Error creating output track on thread %p", playbackThread);
1369    }
1370}
1371
1372AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1373{
1374    clearBufferQueue();
1375    delete mClientProxy;
1376    // superclass destructor will now delete the server proxy and shared memory both refer to
1377}
1378
1379status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1380                                                          int triggerSession)
1381{
1382    status_t status = Track::start(event, triggerSession);
1383    if (status != NO_ERROR) {
1384        return status;
1385    }
1386
1387    mActive = true;
1388    mRetryCount = 127;
1389    return status;
1390}
1391
1392void AudioFlinger::PlaybackThread::OutputTrack::stop()
1393{
1394    Track::stop();
1395    clearBufferQueue();
1396    mOutBuffer.frameCount = 0;
1397    mActive = false;
1398}
1399
1400bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1401{
1402    Buffer *pInBuffer;
1403    Buffer inBuffer;
1404    uint32_t channelCount = mChannelCount;
1405    bool outputBufferFull = false;
1406    inBuffer.frameCount = frames;
1407    inBuffer.i16 = data;
1408
1409    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1410
1411    if (!mActive && frames != 0) {
1412        start();
1413        sp<ThreadBase> thread = mThread.promote();
1414        if (thread != 0) {
1415            MixerThread *mixerThread = (MixerThread *)thread.get();
1416            if (mFrameCount > frames) {
1417                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1418                    uint32_t startFrames = (mFrameCount - frames);
1419                    pInBuffer = new Buffer;
1420                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1421                    pInBuffer->frameCount = startFrames;
1422                    pInBuffer->i16 = pInBuffer->mBuffer;
1423                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1424                    mBufferQueue.add(pInBuffer);
1425                } else {
1426                    ALOGW("OutputTrack::write() %p no more buffers in queue", this);
1427                }
1428            }
1429        }
1430    }
1431
1432    while (waitTimeLeftMs) {
1433        // First write pending buffers, then new data
1434        if (mBufferQueue.size()) {
1435            pInBuffer = mBufferQueue.itemAt(0);
1436        } else {
1437            pInBuffer = &inBuffer;
1438        }
1439
1440        if (pInBuffer->frameCount == 0) {
1441            break;
1442        }
1443
1444        if (mOutBuffer.frameCount == 0) {
1445            mOutBuffer.frameCount = pInBuffer->frameCount;
1446            nsecs_t startTime = systemTime();
1447            status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1448            if (status != NO_ERROR) {
1449                ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1450                        mThread.unsafe_get(), status);
1451                outputBufferFull = true;
1452                break;
1453            }
1454            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1455            if (waitTimeLeftMs >= waitTimeMs) {
1456                waitTimeLeftMs -= waitTimeMs;
1457            } else {
1458                waitTimeLeftMs = 0;
1459            }
1460        }
1461
1462        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1463                pInBuffer->frameCount;
1464        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
1465        Proxy::Buffer buf;
1466        buf.mFrameCount = outFrames;
1467        buf.mRaw = NULL;
1468        mClientProxy->releaseBuffer(&buf);
1469        pInBuffer->frameCount -= outFrames;
1470        pInBuffer->i16 += outFrames * channelCount;
1471        mOutBuffer.frameCount -= outFrames;
1472        mOutBuffer.i16 += outFrames * channelCount;
1473
1474        if (pInBuffer->frameCount == 0) {
1475            if (mBufferQueue.size()) {
1476                mBufferQueue.removeAt(0);
1477                delete [] pInBuffer->mBuffer;
1478                delete pInBuffer;
1479                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1480                        mThread.unsafe_get(), mBufferQueue.size());
1481            } else {
1482                break;
1483            }
1484        }
1485    }
1486
1487    // If we could not write all frames, allocate a buffer and queue it for next time.
1488    if (inBuffer.frameCount) {
1489        sp<ThreadBase> thread = mThread.promote();
1490        if (thread != 0 && !thread->standby()) {
1491            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1492                pInBuffer = new Buffer;
1493                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1494                pInBuffer->frameCount = inBuffer.frameCount;
1495                pInBuffer->i16 = pInBuffer->mBuffer;
1496                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1497                        sizeof(int16_t));
1498                mBufferQueue.add(pInBuffer);
1499                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1500                        mThread.unsafe_get(), mBufferQueue.size());
1501            } else {
1502                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1503                        mThread.unsafe_get(), this);
1504            }
1505        }
1506    }
1507
1508    // Calling write() with a 0 length buffer, means that no more data will be written:
1509    // If no more buffers are pending, fill output track buffer to make sure it is started
1510    // by output mixer.
1511    if (frames == 0 && mBufferQueue.size() == 0) {
1512        // FIXME borken, replace by getting framesReady() from proxy
1513        size_t user = 0;    // was mCblk->user
1514        if (user < mFrameCount) {
1515            frames = mFrameCount - user;
1516            pInBuffer = new Buffer;
1517            pInBuffer->mBuffer = new int16_t[frames * channelCount];
1518            pInBuffer->frameCount = frames;
1519            pInBuffer->i16 = pInBuffer->mBuffer;
1520            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1521            mBufferQueue.add(pInBuffer);
1522        } else if (mActive) {
1523            stop();
1524        }
1525    }
1526
1527    return outputBufferFull;
1528}
1529
1530status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1531        AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1532{
1533    ClientProxy::Buffer buf;
1534    buf.mFrameCount = buffer->frameCount;
1535    struct timespec timeout;
1536    timeout.tv_sec = waitTimeMs / 1000;
1537    timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1538    status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1539    buffer->frameCount = buf.mFrameCount;
1540    buffer->raw = buf.mRaw;
1541    return status;
1542}
1543
1544void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1545{
1546    size_t size = mBufferQueue.size();
1547
1548    for (size_t i = 0; i < size; i++) {
1549        Buffer *pBuffer = mBufferQueue.itemAt(i);
1550        delete [] pBuffer->mBuffer;
1551        delete pBuffer;
1552    }
1553    mBufferQueue.clear();
1554}
1555
1556
1557// ----------------------------------------------------------------------------
1558//      Record
1559// ----------------------------------------------------------------------------
1560
1561AudioFlinger::RecordHandle::RecordHandle(
1562        const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1563    : BnAudioRecord(),
1564    mRecordTrack(recordTrack)
1565{
1566}
1567
1568AudioFlinger::RecordHandle::~RecordHandle() {
1569    stop_nonvirtual();
1570    mRecordTrack->destroy();
1571}
1572
1573sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1574    return mRecordTrack->getCblk();
1575}
1576
1577status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1578        int triggerSession) {
1579    ALOGV("RecordHandle::start()");
1580    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1581}
1582
1583void AudioFlinger::RecordHandle::stop() {
1584    stop_nonvirtual();
1585}
1586
1587void AudioFlinger::RecordHandle::stop_nonvirtual() {
1588    ALOGV("RecordHandle::stop()");
1589    mRecordTrack->stop();
1590}
1591
1592status_t AudioFlinger::RecordHandle::onTransact(
1593    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1594{
1595    return BnAudioRecord::onTransact(code, data, reply, flags);
1596}
1597
1598// ----------------------------------------------------------------------------
1599
1600// RecordTrack constructor must be called with AudioFlinger::mLock held
1601AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1602            RecordThread *thread,
1603            const sp<Client>& client,
1604            uint32_t sampleRate,
1605            audio_format_t format,
1606            audio_channel_mask_t channelMask,
1607            size_t frameCount,
1608            int sessionId)
1609    :   TrackBase(thread, client, sampleRate, format,
1610                  channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
1611        mOverflow(false)
1612{
1613    ALOGV("RecordTrack constructor, size %d", (int)mBufferEnd - (int)mBuffer);
1614    if (mCblk != NULL) {
1615        mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1616                mFrameSize);
1617        mServerProxy = mAudioRecordServerProxy;
1618    }
1619}
1620
1621AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1622{
1623    ALOGV("%s", __func__);
1624}
1625
1626// AudioBufferProvider interface
1627status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1628        int64_t pts)
1629{
1630    ServerProxy::Buffer buf;
1631    buf.mFrameCount = buffer->frameCount;
1632    status_t status = mServerProxy->obtainBuffer(&buf);
1633    buffer->frameCount = buf.mFrameCount;
1634    buffer->raw = buf.mRaw;
1635    if (buf.mFrameCount == 0) {
1636        // FIXME also wake futex so that overrun is noticed more quickly
1637        (void) android_atomic_or(CBLK_OVERRUN, &mCblk->flags);
1638    }
1639    return status;
1640}
1641
1642status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1643                                                        int triggerSession)
1644{
1645    sp<ThreadBase> thread = mThread.promote();
1646    if (thread != 0) {
1647        RecordThread *recordThread = (RecordThread *)thread.get();
1648        return recordThread->start(this, event, triggerSession);
1649    } else {
1650        return BAD_VALUE;
1651    }
1652}
1653
1654void AudioFlinger::RecordThread::RecordTrack::stop()
1655{
1656    sp<ThreadBase> thread = mThread.promote();
1657    if (thread != 0) {
1658        RecordThread *recordThread = (RecordThread *)thread.get();
1659        recordThread->mLock.lock();
1660        bool doStop = recordThread->stop_l(this);
1661        if (doStop) {
1662        }
1663        recordThread->mLock.unlock();
1664        if (doStop) {
1665            AudioSystem::stopInput(recordThread->id());
1666        }
1667    }
1668}
1669
1670void AudioFlinger::RecordThread::RecordTrack::destroy()
1671{
1672    // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1673    sp<RecordTrack> keep(this);
1674    {
1675        sp<ThreadBase> thread = mThread.promote();
1676        if (thread != 0) {
1677            if (mState == ACTIVE || mState == RESUMING) {
1678                AudioSystem::stopInput(thread->id());
1679            }
1680            AudioSystem::releaseInput(thread->id());
1681            Mutex::Autolock _l(thread->mLock);
1682            RecordThread *recordThread = (RecordThread *) thread.get();
1683            recordThread->destroyTrack_l(this);
1684        }
1685    }
1686}
1687
1688
1689/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1690{
1691    result.append("   Clien Fmt Chn mask   Session Step S Serv   FrameCount\n");
1692}
1693
1694void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1695{
1696    snprintf(buffer, size, "   %05d %03u 0x%08x %05d   %04u %01d %08x %05d\n",
1697            (mClient == 0) ? getpid_cached : mClient->pid(),
1698            mFormat,
1699            mChannelMask,
1700            mSessionId,
1701            mStepCount,
1702            mState,
1703            mCblk->server,
1704            mFrameCount);
1705}
1706
1707}; // namespace android
1708