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