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