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