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