Tracks.cpp revision d72b7c0180ee83fc3754629ed68fc5887a125c4c
1f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org/*
2f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org**
3f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** Copyright 2012, The Android Open Source Project
4f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org**
5f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** Licensed under the Apache License, Version 2.0 (the "License");
6f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** you may not use this file except in compliance with the License.
7f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** You may obtain a copy of the License at
8f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org**
9f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org**     http://www.apache.org/licenses/LICENSE-2.0
10f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org**
11f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** Unless required by applicable law or agreed to in writing, software
12f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** distributed under the License is distributed on an "AS IS" BASIS,
13f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** See the License for the specific language governing permissions and
15f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org** limitations under the License.
16f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org*/
17f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
18f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
19f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#define LOG_TAG "AudioFlinger"
20f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//#define LOG_NDEBUG 0
21f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
22f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "Configuration.h"
23f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <math.h>
24f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <utils/Log.h>
25f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
26f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <private/media/AudioTrackShared.h>
27f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
28f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <common_time/cc_helper.h>
29f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <common_time/local_clock.h>
30f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
31f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "AudioMixer.h"
32f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "AudioFlinger.h"
33f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include "ServiceUtilities.h"
34f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
35f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <media/nbaio/Pipe.h>
36f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#include <media/nbaio/PipeReader.h>
37f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
38f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// ----------------------------------------------------------------------------
39f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org
40f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// Note: the following macro is used for extremely verbose logging message.  In
41f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// order to run with ALOG_ASSERT turned on, we need to have LOG_NDEBUG set to
42f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// 0; but one side effect of this is to turn all LOGV's as well.  Some messages
43f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// are so verbose that we want to suppress them even when we have ALOG_ASSERT
44f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// turned on.  Do not uncomment the #def below unless you really know what you
45f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org// are doing and want to see all of the extremely verbose messages.
46f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org//#define VERY_VERY_VERBOSE_LOGGING
47f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#ifdef VERY_VERY_VERBOSE_LOGGING
48f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#define ALOGVV ALOGV
49f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#else
50f2ba7591b1407a7ee9209f842c50696914dc2dedkbr@chromium.org#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            AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
833        }
834        status = playbackThread->attachAuxEffect(this, EffectId);
835    }
836    return status;
837}
838
839void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
840{
841    mAuxEffectId = EffectId;
842    mAuxBuffer = buffer;
843}
844
845bool AudioFlinger::PlaybackThread::Track::presentationComplete(size_t framesWritten,
846                                                         size_t audioHalFrames)
847{
848    // a track is considered presented when the total number of frames written to audio HAL
849    // corresponds to the number of frames written when presentationComplete() is called for the
850    // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
851    // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
852    // to detect when all frames have been played. In this case framesWritten isn't
853    // useful because it doesn't always reflect whether there is data in the h/w
854    // buffers, particularly if a track has been paused and resumed during draining
855    ALOGV("presentationComplete() mPresentationCompleteFrames %d framesWritten %d",
856                      mPresentationCompleteFrames, framesWritten);
857    if (mPresentationCompleteFrames == 0) {
858        mPresentationCompleteFrames = framesWritten + audioHalFrames;
859        ALOGV("presentationComplete() reset: mPresentationCompleteFrames %d audioHalFrames %d",
860                  mPresentationCompleteFrames, audioHalFrames);
861    }
862
863    if (framesWritten >= mPresentationCompleteFrames || isOffloaded()) {
864        ALOGV("presentationComplete() session %d complete: framesWritten %d",
865                  mSessionId, framesWritten);
866        triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
867        mAudioTrackServerProxy->setStreamEndDone();
868        return true;
869    }
870    return false;
871}
872
873void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
874{
875    for (int i = 0; i < (int)mSyncEvents.size(); i++) {
876        if (mSyncEvents[i]->type() == type) {
877            mSyncEvents[i]->trigger();
878            mSyncEvents.removeAt(i);
879            i--;
880        }
881    }
882}
883
884// implement VolumeBufferProvider interface
885
886uint32_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
887{
888    // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
889    ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
890    uint32_t vlr = mAudioTrackServerProxy->getVolumeLR();
891    uint32_t vl = vlr & 0xFFFF;
892    uint32_t vr = vlr >> 16;
893    // track volumes come from shared memory, so can't be trusted and must be clamped
894    if (vl > MAX_GAIN_INT) {
895        vl = MAX_GAIN_INT;
896    }
897    if (vr > MAX_GAIN_INT) {
898        vr = MAX_GAIN_INT;
899    }
900    // now apply the cached master volume and stream type volume;
901    // this is trusted but lacks any synchronization or barrier so may be stale
902    float v = mCachedVolume;
903    vl *= v;
904    vr *= v;
905    // re-combine into U4.16
906    vlr = (vr << 16) | (vl & 0xFFFF);
907    // FIXME look at mute, pause, and stop flags
908    return vlr;
909}
910
911status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
912{
913    if (isTerminated() || mState == PAUSED ||
914            ((framesReady() == 0) && ((mSharedBuffer != 0) ||
915                                      (mState == STOPPED)))) {
916        ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
917              mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
918        event->cancel();
919        return INVALID_OPERATION;
920    }
921    (void) TrackBase::setSyncEvent(event);
922    return NO_ERROR;
923}
924
925void AudioFlinger::PlaybackThread::Track::invalidate()
926{
927    // FIXME should use proxy, and needs work
928    audio_track_cblk_t* cblk = mCblk;
929    android_atomic_or(CBLK_INVALID, &cblk->mFlags);
930    android_atomic_release_store(0x40000000, &cblk->mFutex);
931    // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
932    (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
933    mIsInvalid = true;
934}
935
936void AudioFlinger::PlaybackThread::Track::signal()
937{
938    sp<ThreadBase> thread = mThread.promote();
939    if (thread != 0) {
940        PlaybackThread *t = (PlaybackThread *)thread.get();
941        Mutex::Autolock _l(t->mLock);
942        t->broadcast_l();
943    }
944}
945
946// ----------------------------------------------------------------------------
947
948sp<AudioFlinger::PlaybackThread::TimedTrack>
949AudioFlinger::PlaybackThread::TimedTrack::create(
950            PlaybackThread *thread,
951            const sp<Client>& client,
952            audio_stream_type_t streamType,
953            uint32_t sampleRate,
954            audio_format_t format,
955            audio_channel_mask_t channelMask,
956            size_t frameCount,
957            const sp<IMemory>& sharedBuffer,
958            int sessionId) {
959    if (!client->reserveTimedTrack())
960        return 0;
961
962    return new TimedTrack(
963        thread, client, streamType, sampleRate, format, channelMask, frameCount,
964        sharedBuffer, sessionId);
965}
966
967AudioFlinger::PlaybackThread::TimedTrack::TimedTrack(
968            PlaybackThread *thread,
969            const sp<Client>& client,
970            audio_stream_type_t streamType,
971            uint32_t sampleRate,
972            audio_format_t format,
973            audio_channel_mask_t channelMask,
974            size_t frameCount,
975            const sp<IMemory>& sharedBuffer,
976            int sessionId)
977    : Track(thread, client, streamType, sampleRate, format, channelMask,
978            frameCount, sharedBuffer, sessionId, IAudioFlinger::TRACK_TIMED),
979      mQueueHeadInFlight(false),
980      mTrimQueueHeadOnRelease(false),
981      mFramesPendingInQueue(0),
982      mTimedSilenceBuffer(NULL),
983      mTimedSilenceBufferSize(0),
984      mTimedAudioOutputOnTime(false),
985      mMediaTimeTransformValid(false)
986{
987    LocalClock lc;
988    mLocalTimeFreq = lc.getLocalFreq();
989
990    mLocalTimeToSampleTransform.a_zero = 0;
991    mLocalTimeToSampleTransform.b_zero = 0;
992    mLocalTimeToSampleTransform.a_to_b_numer = sampleRate;
993    mLocalTimeToSampleTransform.a_to_b_denom = mLocalTimeFreq;
994    LinearTransform::reduce(&mLocalTimeToSampleTransform.a_to_b_numer,
995                            &mLocalTimeToSampleTransform.a_to_b_denom);
996
997    mMediaTimeToSampleTransform.a_zero = 0;
998    mMediaTimeToSampleTransform.b_zero = 0;
999    mMediaTimeToSampleTransform.a_to_b_numer = sampleRate;
1000    mMediaTimeToSampleTransform.a_to_b_denom = 1000000;
1001    LinearTransform::reduce(&mMediaTimeToSampleTransform.a_to_b_numer,
1002                            &mMediaTimeToSampleTransform.a_to_b_denom);
1003}
1004
1005AudioFlinger::PlaybackThread::TimedTrack::~TimedTrack() {
1006    mClient->releaseTimedTrack();
1007    delete [] mTimedSilenceBuffer;
1008}
1009
1010status_t AudioFlinger::PlaybackThread::TimedTrack::allocateTimedBuffer(
1011    size_t size, sp<IMemory>* buffer) {
1012
1013    Mutex::Autolock _l(mTimedBufferQueueLock);
1014
1015    trimTimedBufferQueue_l();
1016
1017    // lazily initialize the shared memory heap for timed buffers
1018    if (mTimedMemoryDealer == NULL) {
1019        const int kTimedBufferHeapSize = 512 << 10;
1020
1021        mTimedMemoryDealer = new MemoryDealer(kTimedBufferHeapSize,
1022                                              "AudioFlingerTimed");
1023        if (mTimedMemoryDealer == NULL)
1024            return NO_MEMORY;
1025    }
1026
1027    sp<IMemory> newBuffer = mTimedMemoryDealer->allocate(size);
1028    if (newBuffer == NULL) {
1029        newBuffer = mTimedMemoryDealer->allocate(size);
1030        if (newBuffer == NULL)
1031            return NO_MEMORY;
1032    }
1033
1034    *buffer = newBuffer;
1035    return NO_ERROR;
1036}
1037
1038// caller must hold mTimedBufferQueueLock
1039void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueue_l() {
1040    int64_t mediaTimeNow;
1041    {
1042        Mutex::Autolock mttLock(mMediaTimeTransformLock);
1043        if (!mMediaTimeTransformValid)
1044            return;
1045
1046        int64_t targetTimeNow;
1047        status_t res = (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME)
1048            ? mCCHelper.getCommonTime(&targetTimeNow)
1049            : mCCHelper.getLocalTime(&targetTimeNow);
1050
1051        if (OK != res)
1052            return;
1053
1054        if (!mMediaTimeTransform.doReverseTransform(targetTimeNow,
1055                                                    &mediaTimeNow)) {
1056            return;
1057        }
1058    }
1059
1060    size_t trimEnd;
1061    for (trimEnd = 0; trimEnd < mTimedBufferQueue.size(); trimEnd++) {
1062        int64_t bufEnd;
1063
1064        if ((trimEnd + 1) < mTimedBufferQueue.size()) {
1065            // We have a next buffer.  Just use its PTS as the PTS of the frame
1066            // following the last frame in this buffer.  If the stream is sparse
1067            // (ie, there are deliberate gaps left in the stream which should be
1068            // filled with silence by the TimedAudioTrack), then this can result
1069            // in one extra buffer being left un-trimmed when it could have
1070            // been.  In general, this is not typical, and we would rather
1071            // optimized away the TS calculation below for the more common case
1072            // where PTSes are contiguous.
1073            bufEnd = mTimedBufferQueue[trimEnd + 1].pts();
1074        } else {
1075            // We have no next buffer.  Compute the PTS of the frame following
1076            // the last frame in this buffer by computing the duration of of
1077            // this frame in media time units and adding it to the PTS of the
1078            // buffer.
1079            int64_t frameCount = mTimedBufferQueue[trimEnd].buffer()->size()
1080                               / mFrameSize;
1081
1082            if (!mMediaTimeToSampleTransform.doReverseTransform(frameCount,
1083                                                                &bufEnd)) {
1084                ALOGE("Failed to convert frame count of %lld to media time"
1085                      " duration" " (scale factor %d/%u) in %s",
1086                      frameCount,
1087                      mMediaTimeToSampleTransform.a_to_b_numer,
1088                      mMediaTimeToSampleTransform.a_to_b_denom,
1089                      __PRETTY_FUNCTION__);
1090                break;
1091            }
1092            bufEnd += mTimedBufferQueue[trimEnd].pts();
1093        }
1094
1095        if (bufEnd > mediaTimeNow)
1096            break;
1097
1098        // Is the buffer we want to use in the middle of a mix operation right
1099        // now?  If so, don't actually trim it.  Just wait for the releaseBuffer
1100        // from the mixer which should be coming back shortly.
1101        if (!trimEnd && mQueueHeadInFlight) {
1102            mTrimQueueHeadOnRelease = true;
1103        }
1104    }
1105
1106    size_t trimStart = mTrimQueueHeadOnRelease ? 1 : 0;
1107    if (trimStart < trimEnd) {
1108        // Update the bookkeeping for framesReady()
1109        for (size_t i = trimStart; i < trimEnd; ++i) {
1110            updateFramesPendingAfterTrim_l(mTimedBufferQueue[i], "trim");
1111        }
1112
1113        // Now actually remove the buffers from the queue.
1114        mTimedBufferQueue.removeItemsAt(trimStart, trimEnd);
1115    }
1116}
1117
1118void AudioFlinger::PlaybackThread::TimedTrack::trimTimedBufferQueueHead_l(
1119        const char* logTag) {
1120    ALOG_ASSERT(mTimedBufferQueue.size() > 0,
1121                "%s called (reason \"%s\"), but timed buffer queue has no"
1122                " elements to trim.", __FUNCTION__, logTag);
1123
1124    updateFramesPendingAfterTrim_l(mTimedBufferQueue[0], logTag);
1125    mTimedBufferQueue.removeAt(0);
1126}
1127
1128void AudioFlinger::PlaybackThread::TimedTrack::updateFramesPendingAfterTrim_l(
1129        const TimedBuffer& buf,
1130        const char* logTag) {
1131    uint32_t bufBytes        = buf.buffer()->size();
1132    uint32_t consumedAlready = buf.position();
1133
1134    ALOG_ASSERT(consumedAlready <= bufBytes,
1135                "Bad bookkeeping while updating frames pending.  Timed buffer is"
1136                " only %u bytes long, but claims to have consumed %u"
1137                " bytes.  (update reason: \"%s\")",
1138                bufBytes, consumedAlready, logTag);
1139
1140    uint32_t bufFrames = (bufBytes - consumedAlready) / mFrameSize;
1141    ALOG_ASSERT(mFramesPendingInQueue >= bufFrames,
1142                "Bad bookkeeping while updating frames pending.  Should have at"
1143                " least %u queued frames, but we think we have only %u.  (update"
1144                " reason: \"%s\")",
1145                bufFrames, mFramesPendingInQueue, logTag);
1146
1147    mFramesPendingInQueue -= bufFrames;
1148}
1149
1150status_t AudioFlinger::PlaybackThread::TimedTrack::queueTimedBuffer(
1151    const sp<IMemory>& buffer, int64_t pts) {
1152
1153    {
1154        Mutex::Autolock mttLock(mMediaTimeTransformLock);
1155        if (!mMediaTimeTransformValid)
1156            return INVALID_OPERATION;
1157    }
1158
1159    Mutex::Autolock _l(mTimedBufferQueueLock);
1160
1161    uint32_t bufFrames = buffer->size() / mFrameSize;
1162    mFramesPendingInQueue += bufFrames;
1163    mTimedBufferQueue.add(TimedBuffer(buffer, pts));
1164
1165    return NO_ERROR;
1166}
1167
1168status_t AudioFlinger::PlaybackThread::TimedTrack::setMediaTimeTransform(
1169    const LinearTransform& xform, TimedAudioTrack::TargetTimeline target) {
1170
1171    ALOGVV("setMediaTimeTransform az=%lld bz=%lld n=%d d=%u tgt=%d",
1172           xform.a_zero, xform.b_zero, xform.a_to_b_numer, xform.a_to_b_denom,
1173           target);
1174
1175    if (!(target == TimedAudioTrack::LOCAL_TIME ||
1176          target == TimedAudioTrack::COMMON_TIME)) {
1177        return BAD_VALUE;
1178    }
1179
1180    Mutex::Autolock lock(mMediaTimeTransformLock);
1181    mMediaTimeTransform = xform;
1182    mMediaTimeTransformTarget = target;
1183    mMediaTimeTransformValid = true;
1184
1185    return NO_ERROR;
1186}
1187
1188#define min(a, b) ((a) < (b) ? (a) : (b))
1189
1190// implementation of getNextBuffer for tracks whose buffers have timestamps
1191status_t AudioFlinger::PlaybackThread::TimedTrack::getNextBuffer(
1192    AudioBufferProvider::Buffer* buffer, int64_t pts)
1193{
1194    if (pts == AudioBufferProvider::kInvalidPTS) {
1195        buffer->raw = NULL;
1196        buffer->frameCount = 0;
1197        mTimedAudioOutputOnTime = false;
1198        return INVALID_OPERATION;
1199    }
1200
1201    Mutex::Autolock _l(mTimedBufferQueueLock);
1202
1203    ALOG_ASSERT(!mQueueHeadInFlight,
1204                "getNextBuffer called without releaseBuffer!");
1205
1206    while (true) {
1207
1208        // if we have no timed buffers, then fail
1209        if (mTimedBufferQueue.isEmpty()) {
1210            buffer->raw = NULL;
1211            buffer->frameCount = 0;
1212            return NOT_ENOUGH_DATA;
1213        }
1214
1215        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1216
1217        // calculate the PTS of the head of the timed buffer queue expressed in
1218        // local time
1219        int64_t headLocalPTS;
1220        {
1221            Mutex::Autolock mttLock(mMediaTimeTransformLock);
1222
1223            ALOG_ASSERT(mMediaTimeTransformValid, "media time transform invalid");
1224
1225            if (mMediaTimeTransform.a_to_b_denom == 0) {
1226                // the transform represents a pause, so yield silence
1227                timedYieldSilence_l(buffer->frameCount, buffer);
1228                return NO_ERROR;
1229            }
1230
1231            int64_t transformedPTS;
1232            if (!mMediaTimeTransform.doForwardTransform(head.pts(),
1233                                                        &transformedPTS)) {
1234                // the transform failed.  this shouldn't happen, but if it does
1235                // then just drop this buffer
1236                ALOGW("timedGetNextBuffer transform failed");
1237                buffer->raw = NULL;
1238                buffer->frameCount = 0;
1239                trimTimedBufferQueueHead_l("getNextBuffer; no transform");
1240                return NO_ERROR;
1241            }
1242
1243            if (mMediaTimeTransformTarget == TimedAudioTrack::COMMON_TIME) {
1244                if (OK != mCCHelper.commonTimeToLocalTime(transformedPTS,
1245                                                          &headLocalPTS)) {
1246                    buffer->raw = NULL;
1247                    buffer->frameCount = 0;
1248                    return INVALID_OPERATION;
1249                }
1250            } else {
1251                headLocalPTS = transformedPTS;
1252            }
1253        }
1254
1255        uint32_t sr = sampleRate();
1256
1257        // adjust the head buffer's PTS to reflect the portion of the head buffer
1258        // that has already been consumed
1259        int64_t effectivePTS = headLocalPTS +
1260                ((head.position() / mFrameSize) * mLocalTimeFreq / sr);
1261
1262        // Calculate the delta in samples between the head of the input buffer
1263        // queue and the start of the next output buffer that will be written.
1264        // If the transformation fails because of over or underflow, it means
1265        // that the sample's position in the output stream is so far out of
1266        // whack that it should just be dropped.
1267        int64_t sampleDelta;
1268        if (llabs(effectivePTS - pts) >= (static_cast<int64_t>(1) << 31)) {
1269            ALOGV("*** head buffer is too far from PTS: dropped buffer");
1270            trimTimedBufferQueueHead_l("getNextBuffer, buf pts too far from"
1271                                       " mix");
1272            continue;
1273        }
1274        if (!mLocalTimeToSampleTransform.doForwardTransform(
1275                (effectivePTS - pts) << 32, &sampleDelta)) {
1276            ALOGV("*** too late during sample rate transform: dropped buffer");
1277            trimTimedBufferQueueHead_l("getNextBuffer, bad local to sample");
1278            continue;
1279        }
1280
1281        ALOGVV("*** getNextBuffer head.pts=%lld head.pos=%d pts=%lld"
1282               " sampleDelta=[%d.%08x]",
1283               head.pts(), head.position(), pts,
1284               static_cast<int32_t>((sampleDelta >= 0 ? 0 : 1)
1285                   + (sampleDelta >> 32)),
1286               static_cast<uint32_t>(sampleDelta & 0xFFFFFFFF));
1287
1288        // if the delta between the ideal placement for the next input sample and
1289        // the current output position is within this threshold, then we will
1290        // concatenate the next input samples to the previous output
1291        const int64_t kSampleContinuityThreshold =
1292                (static_cast<int64_t>(sr) << 32) / 250;
1293
1294        // if this is the first buffer of audio that we're emitting from this track
1295        // then it should be almost exactly on time.
1296        const int64_t kSampleStartupThreshold = 1LL << 32;
1297
1298        if ((mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleContinuityThreshold) ||
1299           (!mTimedAudioOutputOnTime && llabs(sampleDelta) <= kSampleStartupThreshold)) {
1300            // the next input is close enough to being on time, so concatenate it
1301            // with the last output
1302            timedYieldSamples_l(buffer);
1303
1304            ALOGVV("*** on time: head.pos=%d frameCount=%u",
1305                    head.position(), buffer->frameCount);
1306            return NO_ERROR;
1307        }
1308
1309        // Looks like our output is not on time.  Reset our on timed status.
1310        // Next time we mix samples from our input queue, then should be within
1311        // the StartupThreshold.
1312        mTimedAudioOutputOnTime = false;
1313        if (sampleDelta > 0) {
1314            // the gap between the current output position and the proper start of
1315            // the next input sample is too big, so fill it with silence
1316            uint32_t framesUntilNextInput = (sampleDelta + 0x80000000) >> 32;
1317
1318            timedYieldSilence_l(framesUntilNextInput, buffer);
1319            ALOGV("*** silence: frameCount=%u", buffer->frameCount);
1320            return NO_ERROR;
1321        } else {
1322            // the next input sample is late
1323            uint32_t lateFrames = static_cast<uint32_t>(-((sampleDelta + 0x80000000) >> 32));
1324            size_t onTimeSamplePosition =
1325                    head.position() + lateFrames * mFrameSize;
1326
1327            if (onTimeSamplePosition > head.buffer()->size()) {
1328                // all the remaining samples in the head are too late, so
1329                // drop it and move on
1330                ALOGV("*** too late: dropped buffer");
1331                trimTimedBufferQueueHead_l("getNextBuffer, dropped late buffer");
1332                continue;
1333            } else {
1334                // skip over the late samples
1335                head.setPosition(onTimeSamplePosition);
1336
1337                // yield the available samples
1338                timedYieldSamples_l(buffer);
1339
1340                ALOGV("*** late: head.pos=%d frameCount=%u", head.position(), buffer->frameCount);
1341                return NO_ERROR;
1342            }
1343        }
1344    }
1345}
1346
1347// Yield samples from the timed buffer queue head up to the given output
1348// buffer's capacity.
1349//
1350// Caller must hold mTimedBufferQueueLock
1351void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSamples_l(
1352    AudioBufferProvider::Buffer* buffer) {
1353
1354    const TimedBuffer& head = mTimedBufferQueue[0];
1355
1356    buffer->raw = (static_cast<uint8_t*>(head.buffer()->pointer()) +
1357                   head.position());
1358
1359    uint32_t framesLeftInHead = ((head.buffer()->size() - head.position()) /
1360                                 mFrameSize);
1361    size_t framesRequested = buffer->frameCount;
1362    buffer->frameCount = min(framesLeftInHead, framesRequested);
1363
1364    mQueueHeadInFlight = true;
1365    mTimedAudioOutputOnTime = true;
1366}
1367
1368// Yield samples of silence up to the given output buffer's capacity
1369//
1370// Caller must hold mTimedBufferQueueLock
1371void AudioFlinger::PlaybackThread::TimedTrack::timedYieldSilence_l(
1372    uint32_t numFrames, AudioBufferProvider::Buffer* buffer) {
1373
1374    // lazily allocate a buffer filled with silence
1375    if (mTimedSilenceBufferSize < numFrames * mFrameSize) {
1376        delete [] mTimedSilenceBuffer;
1377        mTimedSilenceBufferSize = numFrames * mFrameSize;
1378        mTimedSilenceBuffer = new uint8_t[mTimedSilenceBufferSize];
1379        memset(mTimedSilenceBuffer, 0, mTimedSilenceBufferSize);
1380    }
1381
1382    buffer->raw = mTimedSilenceBuffer;
1383    size_t framesRequested = buffer->frameCount;
1384    buffer->frameCount = min(numFrames, framesRequested);
1385
1386    mTimedAudioOutputOnTime = false;
1387}
1388
1389// AudioBufferProvider interface
1390void AudioFlinger::PlaybackThread::TimedTrack::releaseBuffer(
1391    AudioBufferProvider::Buffer* buffer) {
1392
1393    Mutex::Autolock _l(mTimedBufferQueueLock);
1394
1395    // If the buffer which was just released is part of the buffer at the head
1396    // of the queue, be sure to update the amt of the buffer which has been
1397    // consumed.  If the buffer being returned is not part of the head of the
1398    // queue, its either because the buffer is part of the silence buffer, or
1399    // because the head of the timed queue was trimmed after the mixer called
1400    // getNextBuffer but before the mixer called releaseBuffer.
1401    if (buffer->raw == mTimedSilenceBuffer) {
1402        ALOG_ASSERT(!mQueueHeadInFlight,
1403                    "Queue head in flight during release of silence buffer!");
1404        goto done;
1405    }
1406
1407    ALOG_ASSERT(mQueueHeadInFlight,
1408                "TimedTrack::releaseBuffer of non-silence buffer, but no queue"
1409                " head in flight.");
1410
1411    if (mTimedBufferQueue.size()) {
1412        TimedBuffer& head = mTimedBufferQueue.editItemAt(0);
1413
1414        void* start = head.buffer()->pointer();
1415        void* end   = reinterpret_cast<void*>(
1416                        reinterpret_cast<uint8_t*>(head.buffer()->pointer())
1417                        + head.buffer()->size());
1418
1419        ALOG_ASSERT((buffer->raw >= start) && (buffer->raw < end),
1420                    "released buffer not within the head of the timed buffer"
1421                    " queue; qHead = [%p, %p], released buffer = %p",
1422                    start, end, buffer->raw);
1423
1424        head.setPosition(head.position() +
1425                (buffer->frameCount * mFrameSize));
1426        mQueueHeadInFlight = false;
1427
1428        ALOG_ASSERT(mFramesPendingInQueue >= buffer->frameCount,
1429                    "Bad bookkeeping during releaseBuffer!  Should have at"
1430                    " least %u queued frames, but we think we have only %u",
1431                    buffer->frameCount, mFramesPendingInQueue);
1432
1433        mFramesPendingInQueue -= buffer->frameCount;
1434
1435        if ((static_cast<size_t>(head.position()) >= head.buffer()->size())
1436            || mTrimQueueHeadOnRelease) {
1437            trimTimedBufferQueueHead_l("releaseBuffer");
1438            mTrimQueueHeadOnRelease = false;
1439        }
1440    } else {
1441        LOG_FATAL("TimedTrack::releaseBuffer of non-silence buffer with no"
1442                  " buffers in the timed buffer queue");
1443    }
1444
1445done:
1446    buffer->raw = 0;
1447    buffer->frameCount = 0;
1448}
1449
1450size_t AudioFlinger::PlaybackThread::TimedTrack::framesReady() const {
1451    Mutex::Autolock _l(mTimedBufferQueueLock);
1452    return mFramesPendingInQueue;
1453}
1454
1455AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer()
1456        : mPTS(0), mPosition(0) {}
1457
1458AudioFlinger::PlaybackThread::TimedTrack::TimedBuffer::TimedBuffer(
1459    const sp<IMemory>& buffer, int64_t pts)
1460        : mBuffer(buffer), mPTS(pts), mPosition(0) {}
1461
1462
1463// ----------------------------------------------------------------------------
1464
1465AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1466            PlaybackThread *playbackThread,
1467            DuplicatingThread *sourceThread,
1468            uint32_t sampleRate,
1469            audio_format_t format,
1470            audio_channel_mask_t channelMask,
1471            size_t frameCount)
1472    :   Track(playbackThread, NULL, AUDIO_STREAM_CNT, sampleRate, format, channelMask, frameCount,
1473                NULL, 0, IAudioFlinger::TRACK_DEFAULT),
1474    mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
1475{
1476
1477    if (mCblk != NULL) {
1478        mOutBuffer.frameCount = 0;
1479        playbackThread->mTracks.add(this);
1480        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
1481                "mCblk->frameCount_ %u, mChannelMask 0x%08x",
1482                mCblk, mBuffer,
1483                mCblk->frameCount_, mChannelMask);
1484        // since client and server are in the same process,
1485        // the buffer has the same virtual address on both sides
1486        mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize);
1487        mClientProxy->setVolumeLR((uint32_t(uint16_t(0x1000)) << 16) | uint16_t(0x1000));
1488        mClientProxy->setSendLevel(0.0);
1489        mClientProxy->setSampleRate(sampleRate);
1490        mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1491                true /*clientInServer*/);
1492    } else {
1493        ALOGW("Error creating output track on thread %p", playbackThread);
1494    }
1495}
1496
1497AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1498{
1499    clearBufferQueue();
1500    delete mClientProxy;
1501    // superclass destructor will now delete the server proxy and shared memory both refer to
1502}
1503
1504status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1505                                                          int triggerSession)
1506{
1507    status_t status = Track::start(event, triggerSession);
1508    if (status != NO_ERROR) {
1509        return status;
1510    }
1511
1512    mActive = true;
1513    mRetryCount = 127;
1514    return status;
1515}
1516
1517void AudioFlinger::PlaybackThread::OutputTrack::stop()
1518{
1519    Track::stop();
1520    clearBufferQueue();
1521    mOutBuffer.frameCount = 0;
1522    mActive = false;
1523}
1524
1525bool AudioFlinger::PlaybackThread::OutputTrack::write(int16_t* data, uint32_t frames)
1526{
1527    Buffer *pInBuffer;
1528    Buffer inBuffer;
1529    uint32_t channelCount = mChannelCount;
1530    bool outputBufferFull = false;
1531    inBuffer.frameCount = frames;
1532    inBuffer.i16 = data;
1533
1534    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1535
1536    if (!mActive && frames != 0) {
1537        start();
1538        sp<ThreadBase> thread = mThread.promote();
1539        if (thread != 0) {
1540            MixerThread *mixerThread = (MixerThread *)thread.get();
1541            if (mFrameCount > frames) {
1542                if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1543                    uint32_t startFrames = (mFrameCount - frames);
1544                    pInBuffer = new Buffer;
1545                    pInBuffer->mBuffer = new int16_t[startFrames * channelCount];
1546                    pInBuffer->frameCount = startFrames;
1547                    pInBuffer->i16 = pInBuffer->mBuffer;
1548                    memset(pInBuffer->raw, 0, startFrames * channelCount * sizeof(int16_t));
1549                    mBufferQueue.add(pInBuffer);
1550                } else {
1551                    ALOGW("OutputTrack::write() %p no more buffers in queue", this);
1552                }
1553            }
1554        }
1555    }
1556
1557    while (waitTimeLeftMs) {
1558        // First write pending buffers, then new data
1559        if (mBufferQueue.size()) {
1560            pInBuffer = mBufferQueue.itemAt(0);
1561        } else {
1562            pInBuffer = &inBuffer;
1563        }
1564
1565        if (pInBuffer->frameCount == 0) {
1566            break;
1567        }
1568
1569        if (mOutBuffer.frameCount == 0) {
1570            mOutBuffer.frameCount = pInBuffer->frameCount;
1571            nsecs_t startTime = systemTime();
1572            status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1573            if (status != NO_ERROR) {
1574                ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1575                        mThread.unsafe_get(), status);
1576                outputBufferFull = true;
1577                break;
1578            }
1579            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1580            if (waitTimeLeftMs >= waitTimeMs) {
1581                waitTimeLeftMs -= waitTimeMs;
1582            } else {
1583                waitTimeLeftMs = 0;
1584            }
1585        }
1586
1587        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1588                pInBuffer->frameCount;
1589        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * channelCount * sizeof(int16_t));
1590        Proxy::Buffer buf;
1591        buf.mFrameCount = outFrames;
1592        buf.mRaw = NULL;
1593        mClientProxy->releaseBuffer(&buf);
1594        pInBuffer->frameCount -= outFrames;
1595        pInBuffer->i16 += outFrames * channelCount;
1596        mOutBuffer.frameCount -= outFrames;
1597        mOutBuffer.i16 += outFrames * channelCount;
1598
1599        if (pInBuffer->frameCount == 0) {
1600            if (mBufferQueue.size()) {
1601                mBufferQueue.removeAt(0);
1602                delete [] pInBuffer->mBuffer;
1603                delete pInBuffer;
1604                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1605                        mThread.unsafe_get(), mBufferQueue.size());
1606            } else {
1607                break;
1608            }
1609        }
1610    }
1611
1612    // If we could not write all frames, allocate a buffer and queue it for next time.
1613    if (inBuffer.frameCount) {
1614        sp<ThreadBase> thread = mThread.promote();
1615        if (thread != 0 && !thread->standby()) {
1616            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1617                pInBuffer = new Buffer;
1618                pInBuffer->mBuffer = new int16_t[inBuffer.frameCount * channelCount];
1619                pInBuffer->frameCount = inBuffer.frameCount;
1620                pInBuffer->i16 = pInBuffer->mBuffer;
1621                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * channelCount *
1622                        sizeof(int16_t));
1623                mBufferQueue.add(pInBuffer);
1624                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1625                        mThread.unsafe_get(), mBufferQueue.size());
1626            } else {
1627                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1628                        mThread.unsafe_get(), this);
1629            }
1630        }
1631    }
1632
1633    // Calling write() with a 0 length buffer, means that no more data will be written:
1634    // If no more buffers are pending, fill output track buffer to make sure it is started
1635    // by output mixer.
1636    if (frames == 0 && mBufferQueue.size() == 0) {
1637        // FIXME borken, replace by getting framesReady() from proxy
1638        size_t user = 0;    // was mCblk->user
1639        if (user < mFrameCount) {
1640            frames = mFrameCount - user;
1641            pInBuffer = new Buffer;
1642            pInBuffer->mBuffer = new int16_t[frames * channelCount];
1643            pInBuffer->frameCount = frames;
1644            pInBuffer->i16 = pInBuffer->mBuffer;
1645            memset(pInBuffer->raw, 0, frames * channelCount * sizeof(int16_t));
1646            mBufferQueue.add(pInBuffer);
1647        } else if (mActive) {
1648            stop();
1649        }
1650    }
1651
1652    return outputBufferFull;
1653}
1654
1655status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1656        AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1657{
1658    ClientProxy::Buffer buf;
1659    buf.mFrameCount = buffer->frameCount;
1660    struct timespec timeout;
1661    timeout.tv_sec = waitTimeMs / 1000;
1662    timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1663    status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1664    buffer->frameCount = buf.mFrameCount;
1665    buffer->raw = buf.mRaw;
1666    return status;
1667}
1668
1669void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1670{
1671    size_t size = mBufferQueue.size();
1672
1673    for (size_t i = 0; i < size; i++) {
1674        Buffer *pBuffer = mBufferQueue.itemAt(i);
1675        delete [] pBuffer->mBuffer;
1676        delete pBuffer;
1677    }
1678    mBufferQueue.clear();
1679}
1680
1681
1682// ----------------------------------------------------------------------------
1683//      Record
1684// ----------------------------------------------------------------------------
1685
1686AudioFlinger::RecordHandle::RecordHandle(
1687        const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1688    : BnAudioRecord(),
1689    mRecordTrack(recordTrack)
1690{
1691}
1692
1693AudioFlinger::RecordHandle::~RecordHandle() {
1694    stop_nonvirtual();
1695    mRecordTrack->destroy();
1696}
1697
1698sp<IMemory> AudioFlinger::RecordHandle::getCblk() const {
1699    return mRecordTrack->getCblk();
1700}
1701
1702status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1703        int triggerSession) {
1704    ALOGV("RecordHandle::start()");
1705    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1706}
1707
1708void AudioFlinger::RecordHandle::stop() {
1709    stop_nonvirtual();
1710}
1711
1712void AudioFlinger::RecordHandle::stop_nonvirtual() {
1713    ALOGV("RecordHandle::stop()");
1714    mRecordTrack->stop();
1715}
1716
1717status_t AudioFlinger::RecordHandle::onTransact(
1718    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1719{
1720    return BnAudioRecord::onTransact(code, data, reply, flags);
1721}
1722
1723// ----------------------------------------------------------------------------
1724
1725// RecordTrack constructor must be called with AudioFlinger::mLock held
1726AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1727            RecordThread *thread,
1728            const sp<Client>& client,
1729            uint32_t sampleRate,
1730            audio_format_t format,
1731            audio_channel_mask_t channelMask,
1732            size_t frameCount,
1733            int sessionId)
1734    :   TrackBase(thread, client, sampleRate, format,
1735                  channelMask, frameCount, 0 /*sharedBuffer*/, sessionId, false /*isOut*/),
1736        mOverflow(false)
1737{
1738    ALOGV("RecordTrack constructor");
1739    if (mCblk != NULL) {
1740        mAudioRecordServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1741                mFrameSize);
1742        mServerProxy = mAudioRecordServerProxy;
1743    }
1744}
1745
1746AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1747{
1748    ALOGV("%s", __func__);
1749}
1750
1751// AudioBufferProvider interface
1752status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer,
1753        int64_t pts)
1754{
1755    ServerProxy::Buffer buf;
1756    buf.mFrameCount = buffer->frameCount;
1757    status_t status = mServerProxy->obtainBuffer(&buf);
1758    buffer->frameCount = buf.mFrameCount;
1759    buffer->raw = buf.mRaw;
1760    if (buf.mFrameCount == 0) {
1761        // FIXME also wake futex so that overrun is noticed more quickly
1762        (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
1763    }
1764    return status;
1765}
1766
1767status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1768                                                        int triggerSession)
1769{
1770    sp<ThreadBase> thread = mThread.promote();
1771    if (thread != 0) {
1772        RecordThread *recordThread = (RecordThread *)thread.get();
1773        return recordThread->start(this, event, triggerSession);
1774    } else {
1775        return BAD_VALUE;
1776    }
1777}
1778
1779void AudioFlinger::RecordThread::RecordTrack::stop()
1780{
1781    sp<ThreadBase> thread = mThread.promote();
1782    if (thread != 0) {
1783        RecordThread *recordThread = (RecordThread *)thread.get();
1784        if (recordThread->stop(this)) {
1785            AudioSystem::stopInput(recordThread->id());
1786        }
1787    }
1788}
1789
1790void AudioFlinger::RecordThread::RecordTrack::destroy()
1791{
1792    // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1793    sp<RecordTrack> keep(this);
1794    {
1795        sp<ThreadBase> thread = mThread.promote();
1796        if (thread != 0) {
1797            if (mState == ACTIVE || mState == RESUMING) {
1798                AudioSystem::stopInput(thread->id());
1799            }
1800            AudioSystem::releaseInput(thread->id());
1801            Mutex::Autolock _l(thread->mLock);
1802            RecordThread *recordThread = (RecordThread *) thread.get();
1803            recordThread->destroyTrack_l(this);
1804        }
1805    }
1806}
1807
1808void AudioFlinger::RecordThread::RecordTrack::invalidate()
1809{
1810    // FIXME should use proxy, and needs work
1811    audio_track_cblk_t* cblk = mCblk;
1812    android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1813    android_atomic_release_store(0x40000000, &cblk->mFutex);
1814    // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1815    (void) __futex_syscall3(&cblk->mFutex, FUTEX_WAKE, INT_MAX);
1816}
1817
1818
1819/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1820{
1821    result.append("Client Fmt Chn mask Session S   Server fCount\n");
1822}
1823
1824void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size)
1825{
1826    snprintf(buffer, size, "%6u %3u %08X %7u %1d %08X %6u\n",
1827            (mClient == 0) ? getpid_cached : mClient->pid(),
1828            mFormat,
1829            mChannelMask,
1830            mSessionId,
1831            mState,
1832            mCblk->mServer,
1833            mFrameCount);
1834}
1835
1836}; // namespace android
1837