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