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