Tracks.cpp revision 517161856d74f5fe39cce131f29b977bc1745991
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 <linux/futex.h>
24#include <math.h>
25#include <sys/syscall.h>
26#include <utils/Log.h>
27
28#include <private/media/AudioTrackShared.h>
29
30#include "AudioMixer.h"
31#include "AudioFlinger.h"
32#include "ServiceUtilities.h"
33
34#include <media/nbaio/Pipe.h>
35#include <media/nbaio/PipeReader.h>
36#include <audio_utils/minifloat.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
53// TODO move to a common header  (Also shared with AudioTrack.cpp)
54#define NANOS_PER_SECOND    1000000000
55#define TIME_TO_NANOS(time) ((uint64_t)time.tv_sec * NANOS_PER_SECOND + time.tv_nsec)
56
57namespace android {
58
59// ----------------------------------------------------------------------------
60//      TrackBase
61// ----------------------------------------------------------------------------
62
63static volatile int32_t nextTrackId = 55;
64
65// TrackBase constructor must be called with AudioFlinger::mLock held
66AudioFlinger::ThreadBase::TrackBase::TrackBase(
67            ThreadBase *thread,
68            const sp<Client>& client,
69            uint32_t sampleRate,
70            audio_format_t format,
71            audio_channel_mask_t channelMask,
72            size_t frameCount,
73            void *buffer,
74            int sessionId,
75            int clientUid,
76            IAudioFlinger::track_flags_t flags,
77            bool isOut,
78            alloc_type alloc,
79            track_type type)
80    :   RefBase(),
81        mThread(thread),
82        mClient(client),
83        mCblk(NULL),
84        // mBuffer
85        mState(IDLE),
86        mSampleRate(sampleRate),
87        mFormat(format),
88        mChannelMask(channelMask),
89        mChannelCount(isOut ?
90                audio_channel_count_from_out_mask(channelMask) :
91                audio_channel_count_from_in_mask(channelMask)),
92        mFrameSize(audio_has_proportional_frames(format) ?
93                mChannelCount * audio_bytes_per_sample(format) : sizeof(int8_t)),
94        mFrameCount(frameCount),
95        mSessionId(sessionId),
96        mFlags(flags),
97        mIsOut(isOut),
98        mServerProxy(NULL),
99        mId(android_atomic_inc(&nextTrackId)),
100        mTerminated(false),
101        mType(type),
102        mThreadIoHandle(thread->id())
103{
104    const uid_t callingUid = IPCThreadState::self()->getCallingUid();
105    if (!isTrustedCallingUid(callingUid) || clientUid == -1) {
106        ALOGW_IF(clientUid != -1 && clientUid != (int)callingUid,
107                "%s uid %d tried to pass itself off as %d", __FUNCTION__, callingUid, clientUid);
108        clientUid = (int)callingUid;
109    }
110    // clientUid contains the uid of the app that is responsible for this track, so we can blame
111    // battery usage on it.
112    mUid = clientUid;
113
114    // ALOGD("Creating track with %d buffers @ %d bytes", bufferCount, bufferSize);
115    size_t size = sizeof(audio_track_cblk_t);
116    size_t bufferSize = (buffer == NULL ? roundup(frameCount) : frameCount) * mFrameSize;
117    if (buffer == NULL && alloc == ALLOC_CBLK) {
118        size += bufferSize;
119    }
120
121    if (client != 0) {
122        mCblkMemory = client->heap()->allocate(size);
123        if (mCblkMemory == 0 ||
124                (mCblk = static_cast<audio_track_cblk_t *>(mCblkMemory->pointer())) == NULL) {
125            ALOGE("not enough memory for AudioTrack size=%u", size);
126            client->heap()->dump("AudioTrack");
127            mCblkMemory.clear();
128            return;
129        }
130    } else {
131        // this syntax avoids calling the audio_track_cblk_t constructor twice
132        mCblk = (audio_track_cblk_t *) new uint8_t[size];
133        // assume mCblk != NULL
134    }
135
136    // construct the shared structure in-place.
137    if (mCblk != NULL) {
138        new(mCblk) audio_track_cblk_t();
139        switch (alloc) {
140        case ALLOC_READONLY: {
141            const sp<MemoryDealer> roHeap(thread->readOnlyHeap());
142            if (roHeap == 0 ||
143                    (mBufferMemory = roHeap->allocate(bufferSize)) == 0 ||
144                    (mBuffer = mBufferMemory->pointer()) == NULL) {
145                ALOGE("not enough memory for read-only buffer size=%zu", bufferSize);
146                if (roHeap != 0) {
147                    roHeap->dump("buffer");
148                }
149                mCblkMemory.clear();
150                mBufferMemory.clear();
151                return;
152            }
153            memset(mBuffer, 0, bufferSize);
154            } break;
155        case ALLOC_PIPE:
156            mBufferMemory = thread->pipeMemory();
157            // mBuffer is the virtual address as seen from current process (mediaserver),
158            // and should normally be coming from mBufferMemory->pointer().
159            // However in this case the TrackBase does not reference the buffer directly.
160            // It should references the buffer via the pipe.
161            // Therefore, to detect incorrect usage of the buffer, we set mBuffer to NULL.
162            mBuffer = NULL;
163            break;
164        case ALLOC_CBLK:
165            // clear all buffers
166            if (buffer == NULL) {
167                mBuffer = (char*)mCblk + sizeof(audio_track_cblk_t);
168                memset(mBuffer, 0, bufferSize);
169            } else {
170                mBuffer = buffer;
171#if 0
172                mCblk->mFlags = CBLK_FORCEREADY;    // FIXME hack, need to fix the track ready logic
173#endif
174            }
175            break;
176        case ALLOC_LOCAL:
177            mBuffer = calloc(1, bufferSize);
178            break;
179        case ALLOC_NONE:
180            mBuffer = buffer;
181            break;
182        }
183
184#ifdef TEE_SINK
185        if (mTeeSinkTrackEnabled) {
186            NBAIO_Format pipeFormat = Format_from_SR_C(mSampleRate, mChannelCount, mFormat);
187            if (Format_isValid(pipeFormat)) {
188                Pipe *pipe = new Pipe(mTeeSinkTrackFrames, pipeFormat);
189                size_t numCounterOffers = 0;
190                const NBAIO_Format offers[1] = {pipeFormat};
191                ssize_t index = pipe->negotiate(offers, 1, NULL, numCounterOffers);
192                ALOG_ASSERT(index == 0);
193                PipeReader *pipeReader = new PipeReader(*pipe);
194                numCounterOffers = 0;
195                index = pipeReader->negotiate(offers, 1, NULL, numCounterOffers);
196                ALOG_ASSERT(index == 0);
197                mTeeSink = pipe;
198                mTeeSource = pipeReader;
199            }
200        }
201#endif
202
203    }
204}
205
206status_t AudioFlinger::ThreadBase::TrackBase::initCheck() const
207{
208    status_t status;
209    if (mType == TYPE_OUTPUT || mType == TYPE_PATCH) {
210        status = cblk() != NULL ? NO_ERROR : NO_MEMORY;
211    } else {
212        status = getCblk() != 0 ? NO_ERROR : NO_MEMORY;
213    }
214    return status;
215}
216
217AudioFlinger::ThreadBase::TrackBase::~TrackBase()
218{
219#ifdef TEE_SINK
220    dumpTee(-1, mTeeSource, mId);
221#endif
222    // delete the proxy before deleting the shared memory it refers to, to avoid dangling reference
223    delete mServerProxy;
224    if (mCblk != NULL) {
225        if (mClient == 0) {
226            delete mCblk;
227        } else {
228            mCblk->~audio_track_cblk_t();   // destroy our shared-structure.
229        }
230    }
231    mCblkMemory.clear();    // free the shared memory before releasing the heap it belongs to
232    if (mClient != 0) {
233        // Client destructor must run with AudioFlinger client mutex locked
234        Mutex::Autolock _l(mClient->audioFlinger()->mClientLock);
235        // If the client's reference count drops to zero, the associated destructor
236        // must run with AudioFlinger lock held. Thus the explicit clear() rather than
237        // relying on the automatic clear() at end of scope.
238        mClient.clear();
239    }
240    // flush the binder command buffer
241    IPCThreadState::self()->flushCommands();
242}
243
244// AudioBufferProvider interface
245// getNextBuffer() = 0;
246// This implementation of releaseBuffer() is used by Track and RecordTrack
247void AudioFlinger::ThreadBase::TrackBase::releaseBuffer(AudioBufferProvider::Buffer* buffer)
248{
249#ifdef TEE_SINK
250    if (mTeeSink != 0) {
251        (void) mTeeSink->write(buffer->raw, buffer->frameCount);
252    }
253#endif
254
255    ServerProxy::Buffer buf;
256    buf.mFrameCount = buffer->frameCount;
257    buf.mRaw = buffer->raw;
258    buffer->frameCount = 0;
259    buffer->raw = NULL;
260    mServerProxy->releaseBuffer(&buf);
261}
262
263status_t AudioFlinger::ThreadBase::TrackBase::setSyncEvent(const sp<SyncEvent>& event)
264{
265    mSyncEvents.add(event);
266    return NO_ERROR;
267}
268
269// ----------------------------------------------------------------------------
270//      Playback
271// ----------------------------------------------------------------------------
272
273AudioFlinger::TrackHandle::TrackHandle(const sp<AudioFlinger::PlaybackThread::Track>& track)
274    : BnAudioTrack(),
275      mTrack(track)
276{
277}
278
279AudioFlinger::TrackHandle::~TrackHandle() {
280    // just stop the track on deletion, associated resources
281    // will be freed from the main thread once all pending buffers have
282    // been played. Unless it's not in the active track list, in which
283    // case we free everything now...
284    mTrack->destroy();
285}
286
287sp<IMemory> AudioFlinger::TrackHandle::getCblk() const {
288    return mTrack->getCblk();
289}
290
291status_t AudioFlinger::TrackHandle::start() {
292    return mTrack->start();
293}
294
295void AudioFlinger::TrackHandle::stop() {
296    mTrack->stop();
297}
298
299void AudioFlinger::TrackHandle::flush() {
300    mTrack->flush();
301}
302
303void AudioFlinger::TrackHandle::pause() {
304    mTrack->pause();
305}
306
307status_t AudioFlinger::TrackHandle::attachAuxEffect(int EffectId)
308{
309    return mTrack->attachAuxEffect(EffectId);
310}
311
312status_t AudioFlinger::TrackHandle::setParameters(const String8& keyValuePairs) {
313    return mTrack->setParameters(keyValuePairs);
314}
315
316status_t AudioFlinger::TrackHandle::getTimestamp(AudioTimestamp& timestamp)
317{
318    return mTrack->getTimestamp(timestamp);
319}
320
321
322void AudioFlinger::TrackHandle::signal()
323{
324    return mTrack->signal();
325}
326
327status_t AudioFlinger::TrackHandle::onTransact(
328    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
329{
330    return BnAudioTrack::onTransact(code, data, reply, flags);
331}
332
333// ----------------------------------------------------------------------------
334
335// Track constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
336AudioFlinger::PlaybackThread::Track::Track(
337            PlaybackThread *thread,
338            const sp<Client>& client,
339            audio_stream_type_t streamType,
340            uint32_t sampleRate,
341            audio_format_t format,
342            audio_channel_mask_t channelMask,
343            size_t frameCount,
344            void *buffer,
345            const sp<IMemory>& sharedBuffer,
346            int sessionId,
347            int uid,
348            IAudioFlinger::track_flags_t flags,
349            track_type type)
350    :   TrackBase(thread, client, sampleRate, format, channelMask, frameCount,
351                  (sharedBuffer != 0) ? sharedBuffer->pointer() : buffer,
352                  sessionId, uid, flags, true /*isOut*/,
353                  (type == TYPE_PATCH) ? ( buffer == NULL ? ALLOC_LOCAL : ALLOC_NONE) : ALLOC_CBLK,
354                  type),
355    mFillingUpStatus(FS_INVALID),
356    // mRetryCount initialized later when needed
357    mSharedBuffer(sharedBuffer),
358    mStreamType(streamType),
359    mName(-1),  // see note below
360    mMainBuffer(thread->mixBuffer()),
361    mAuxBuffer(NULL),
362    mAuxEffectId(0), mHasVolumeController(false),
363    mPresentationCompleteFrames(0),
364    mFrameMap(16 /* sink-frame-to-track-frame map memory */),
365    // mSinkTimestamp
366    mFastIndex(-1),
367    mCachedVolume(1.0),
368    mIsInvalid(false),
369    mAudioTrackServerProxy(NULL),
370    mResumeToStopping(false),
371    mFlushHwPending(false)
372{
373    // client == 0 implies sharedBuffer == 0
374    ALOG_ASSERT(!(client == 0 && sharedBuffer != 0));
375
376    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
377            sharedBuffer->size());
378
379    if (mCblk == NULL) {
380        return;
381    }
382
383    if (sharedBuffer == 0) {
384        mAudioTrackServerProxy = new AudioTrackServerProxy(mCblk, mBuffer, frameCount,
385                mFrameSize, !isExternalTrack(), sampleRate);
386    } else {
387        mAudioTrackServerProxy = new StaticAudioTrackServerProxy(mCblk, mBuffer, frameCount,
388                mFrameSize);
389    }
390    mServerProxy = mAudioTrackServerProxy;
391
392    mName = thread->getTrackName_l(channelMask, format, sessionId);
393    if (mName < 0) {
394        ALOGE("no more track names available");
395        return;
396    }
397    // only allocate a fast track index if we were able to allocate a normal track name
398    if (flags & IAudioFlinger::TRACK_FAST) {
399        // FIXME: Not calling framesReadyIsCalledByMultipleThreads() exposes a potential
400        // race with setSyncEvent(). However, if we call it, we cannot properly start
401        // static fast tracks (SoundPool) immediately after stopping.
402        //mAudioTrackServerProxy->framesReadyIsCalledByMultipleThreads();
403        ALOG_ASSERT(thread->mFastTrackAvailMask != 0);
404        int i = __builtin_ctz(thread->mFastTrackAvailMask);
405        ALOG_ASSERT(0 < i && i < (int)FastMixerState::kMaxFastTracks);
406        // FIXME This is too eager.  We allocate a fast track index before the
407        //       fast track becomes active.  Since fast tracks are a scarce resource,
408        //       this means we are potentially denying other more important fast tracks from
409        //       being created.  It would be better to allocate the index dynamically.
410        mFastIndex = i;
411        thread->mFastTrackAvailMask &= ~(1 << i);
412    }
413}
414
415AudioFlinger::PlaybackThread::Track::~Track()
416{
417    ALOGV("PlaybackThread::Track destructor");
418
419    // The destructor would clear mSharedBuffer,
420    // but it will not push the decremented reference count,
421    // leaving the client's IMemory dangling indefinitely.
422    // This prevents that leak.
423    if (mSharedBuffer != 0) {
424        mSharedBuffer.clear();
425    }
426}
427
428status_t AudioFlinger::PlaybackThread::Track::initCheck() const
429{
430    status_t status = TrackBase::initCheck();
431    if (status == NO_ERROR && mName < 0) {
432        status = NO_MEMORY;
433    }
434    return status;
435}
436
437void AudioFlinger::PlaybackThread::Track::destroy()
438{
439    // NOTE: destroyTrack_l() can remove a strong reference to this Track
440    // by removing it from mTracks vector, so there is a risk that this Tracks's
441    // destructor is called. As the destructor needs to lock mLock,
442    // we must acquire a strong reference on this Track before locking mLock
443    // here so that the destructor is called only when exiting this function.
444    // On the other hand, as long as Track::destroy() is only called by
445    // TrackHandle destructor, the TrackHandle still holds a strong ref on
446    // this Track with its member mTrack.
447    sp<Track> keep(this);
448    { // scope for mLock
449        bool wasActive = false;
450        sp<ThreadBase> thread = mThread.promote();
451        if (thread != 0) {
452            Mutex::Autolock _l(thread->mLock);
453            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
454            wasActive = playbackThread->destroyTrack_l(this);
455        }
456        if (isExternalTrack() && !wasActive) {
457            AudioSystem::releaseOutput(mThreadIoHandle, mStreamType, (audio_session_t)mSessionId);
458        }
459    }
460}
461
462/*static*/ void AudioFlinger::PlaybackThread::Track::appendDumpHeader(String8& result)
463{
464    result.append("    Name Active Client Type      Fmt Chn mask Session fCount S F SRate  "
465                  "L dB  R dB    Server Main buf  Aux Buf Flags UndFrmCnt\n");
466}
467
468void AudioFlinger::PlaybackThread::Track::dump(char* buffer, size_t size, bool active)
469{
470    gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
471    if (isFastTrack()) {
472        sprintf(buffer, "    F %2d", mFastIndex);
473    } else if (mName >= AudioMixer::TRACK0) {
474        sprintf(buffer, "    %4d", mName - AudioMixer::TRACK0);
475    } else {
476        sprintf(buffer, "    none");
477    }
478    track_state state = mState;
479    char stateChar;
480    if (isTerminated()) {
481        stateChar = 'T';
482    } else {
483        switch (state) {
484        case IDLE:
485            stateChar = 'I';
486            break;
487        case STOPPING_1:
488            stateChar = 's';
489            break;
490        case STOPPING_2:
491            stateChar = '5';
492            break;
493        case STOPPED:
494            stateChar = 'S';
495            break;
496        case RESUMING:
497            stateChar = 'R';
498            break;
499        case ACTIVE:
500            stateChar = 'A';
501            break;
502        case PAUSING:
503            stateChar = 'p';
504            break;
505        case PAUSED:
506            stateChar = 'P';
507            break;
508        case FLUSHED:
509            stateChar = 'F';
510            break;
511        default:
512            stateChar = '?';
513            break;
514        }
515    }
516    char nowInUnderrun;
517    switch (mObservedUnderruns.mBitFields.mMostRecent) {
518    case UNDERRUN_FULL:
519        nowInUnderrun = ' ';
520        break;
521    case UNDERRUN_PARTIAL:
522        nowInUnderrun = '<';
523        break;
524    case UNDERRUN_EMPTY:
525        nowInUnderrun = '*';
526        break;
527    default:
528        nowInUnderrun = '?';
529        break;
530    }
531    snprintf(&buffer[8], size-8, " %6s %6u %4u %08X %08X %7u %6zu %1c %1d %5u %5.2g %5.2g  "
532                                 "%08X %p %p 0x%03X %9u%c\n",
533            active ? "yes" : "no",
534            (mClient == 0) ? getpid_cached : mClient->pid(),
535            mStreamType,
536            mFormat,
537            mChannelMask,
538            mSessionId,
539            mFrameCount,
540            stateChar,
541            mFillingUpStatus,
542            mAudioTrackServerProxy->getSampleRate(),
543            20.0 * log10(float_from_gain(gain_minifloat_unpack_left(vlr))),
544            20.0 * log10(float_from_gain(gain_minifloat_unpack_right(vlr))),
545            mCblk->mServer,
546            mMainBuffer,
547            mAuxBuffer,
548            mCblk->mFlags,
549            mAudioTrackServerProxy->getUnderrunFrames(),
550            nowInUnderrun);
551}
552
553uint32_t AudioFlinger::PlaybackThread::Track::sampleRate() const {
554    return mAudioTrackServerProxy->getSampleRate();
555}
556
557// AudioBufferProvider interface
558status_t AudioFlinger::PlaybackThread::Track::getNextBuffer(
559        AudioBufferProvider::Buffer* buffer)
560{
561    ServerProxy::Buffer buf;
562    size_t desiredFrames = buffer->frameCount;
563    buf.mFrameCount = desiredFrames;
564    status_t status = mServerProxy->obtainBuffer(&buf);
565    buffer->frameCount = buf.mFrameCount;
566    buffer->raw = buf.mRaw;
567    if (buf.mFrameCount == 0) {
568        mAudioTrackServerProxy->tallyUnderrunFrames(desiredFrames);
569    } else {
570        mAudioTrackServerProxy->tallyUnderrunFrames(0);
571    }
572
573    return status;
574}
575
576// releaseBuffer() is not overridden
577
578// ExtendedAudioBufferProvider interface
579
580// framesReady() may return an approximation of the number of frames if called
581// from a different thread than the one calling Proxy->obtainBuffer() and
582// Proxy->releaseBuffer(). Also note there is no mutual exclusion in the
583// AudioTrackServerProxy so be especially careful calling with FastTracks.
584size_t AudioFlinger::PlaybackThread::Track::framesReady() const {
585    if (mSharedBuffer != 0 && (isStopped() || isStopping())) {
586        // Static tracks return zero frames immediately upon stopping (for FastTracks).
587        // The remainder of the buffer is not drained.
588        return 0;
589    }
590    return mAudioTrackServerProxy->framesReady();
591}
592
593int64_t AudioFlinger::PlaybackThread::Track::framesReleased() const
594{
595    return mAudioTrackServerProxy->framesReleased();
596}
597
598void AudioFlinger::PlaybackThread::Track::onTimestamp(const ExtendedTimestamp &timestamp)
599{
600    // This call comes from a FastTrack and should be kept lockless.
601    // The server side frames are already translated to client frames.
602    mAudioTrackServerProxy->setTimestamp(timestamp);
603
604    // We do not set drained here, as FastTrack timestamp may not go to very last frame.
605}
606
607// Don't call for fast tracks; the framesReady() could result in priority inversion
608bool AudioFlinger::PlaybackThread::Track::isReady() const {
609    if (mFillingUpStatus != FS_FILLING || isStopped() || isPausing()) {
610        return true;
611    }
612
613    if (isStopping()) {
614        if (framesReady() > 0) {
615            mFillingUpStatus = FS_FILLED;
616        }
617        return true;
618    }
619
620    if (framesReady() >= mFrameCount ||
621            (mCblk->mFlags & CBLK_FORCEREADY)) {
622        mFillingUpStatus = FS_FILLED;
623        android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
624        return true;
625    }
626    return false;
627}
628
629status_t AudioFlinger::PlaybackThread::Track::start(AudioSystem::sync_event_t event __unused,
630                                                    int triggerSession __unused)
631{
632    status_t status = NO_ERROR;
633    ALOGV("start(%d), calling pid %d session %d",
634            mName, IPCThreadState::self()->getCallingPid(), mSessionId);
635
636    sp<ThreadBase> thread = mThread.promote();
637    if (thread != 0) {
638        if (isOffloaded()) {
639            Mutex::Autolock _laf(thread->mAudioFlinger->mLock);
640            Mutex::Autolock _lth(thread->mLock);
641            sp<EffectChain> ec = thread->getEffectChain_l(mSessionId);
642            if (thread->mAudioFlinger->isNonOffloadableGlobalEffectEnabled_l() ||
643                    (ec != 0 && ec->isNonOffloadableEnabled())) {
644                invalidate();
645                return PERMISSION_DENIED;
646            }
647        }
648        Mutex::Autolock _lth(thread->mLock);
649        track_state state = mState;
650        // here the track could be either new, or restarted
651        // in both cases "unstop" the track
652
653        // initial state-stopping. next state-pausing.
654        // What if resume is called ?
655
656        if (state == PAUSED || state == PAUSING) {
657            if (mResumeToStopping) {
658                // happened we need to resume to STOPPING_1
659                mState = TrackBase::STOPPING_1;
660                ALOGV("PAUSED => STOPPING_1 (%d) on thread %p", mName, this);
661            } else {
662                mState = TrackBase::RESUMING;
663                ALOGV("PAUSED => RESUMING (%d) on thread %p", mName, this);
664            }
665        } else {
666            mState = TrackBase::ACTIVE;
667            ALOGV("? => ACTIVE (%d) on thread %p", mName, this);
668        }
669
670        // states to reset position info for non-offloaded/direct tracks
671        if (!isOffloaded() && !isDirect()
672                && (state == IDLE || state == STOPPED || state == FLUSHED)) {
673            mFrameMap.reset();
674        }
675        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
676        if (isFastTrack()) {
677            // refresh fast track underruns on start because that field is never cleared
678            // by the fast mixer; furthermore, the same track can be recycled, i.e. start
679            // after stop.
680            mObservedUnderruns = playbackThread->getFastTrackUnderruns(mFastIndex);
681        }
682        status = playbackThread->addTrack_l(this);
683        if (status == INVALID_OPERATION || status == PERMISSION_DENIED) {
684            triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
685            //  restore previous state if start was rejected by policy manager
686            if (status == PERMISSION_DENIED) {
687                mState = state;
688            }
689        }
690        // track was already in the active list, not a problem
691        if (status == ALREADY_EXISTS) {
692            status = NO_ERROR;
693        } else {
694            // Acknowledge any pending flush(), so that subsequent new data isn't discarded.
695            // It is usually unsafe to access the server proxy from a binder thread.
696            // But in this case we know the mixer thread (whether normal mixer or fast mixer)
697            // isn't looking at this track yet:  we still hold the normal mixer thread lock,
698            // and for fast tracks the track is not yet in the fast mixer thread's active set.
699            // For static tracks, this is used to acknowledge change in position or loop.
700            ServerProxy::Buffer buffer;
701            buffer.mFrameCount = 1;
702            (void) mAudioTrackServerProxy->obtainBuffer(&buffer, true /*ackFlush*/);
703        }
704    } else {
705        status = BAD_VALUE;
706    }
707    return status;
708}
709
710void AudioFlinger::PlaybackThread::Track::stop()
711{
712    ALOGV("stop(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
713    sp<ThreadBase> thread = mThread.promote();
714    if (thread != 0) {
715        Mutex::Autolock _l(thread->mLock);
716        track_state state = mState;
717        if (state == RESUMING || state == ACTIVE || state == PAUSING || state == PAUSED) {
718            // If the track is not active (PAUSED and buffers full), flush buffers
719            PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
720            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
721                reset();
722                mState = STOPPED;
723            } else if (!isFastTrack() && !isOffloaded() && !isDirect()) {
724                mState = STOPPED;
725            } else {
726                // For fast tracks prepareTracks_l() will set state to STOPPING_2
727                // presentation is complete
728                // For an offloaded track this starts a drain and state will
729                // move to STOPPING_2 when drain completes and then STOPPED
730                mState = STOPPING_1;
731            }
732            playbackThread->broadcast_l();
733            ALOGV("not stopping/stopped => stopping/stopped (%d) on thread %p", mName,
734                    playbackThread);
735        }
736    }
737}
738
739void AudioFlinger::PlaybackThread::Track::pause()
740{
741    ALOGV("pause(%d), calling pid %d", mName, IPCThreadState::self()->getCallingPid());
742    sp<ThreadBase> thread = mThread.promote();
743    if (thread != 0) {
744        Mutex::Autolock _l(thread->mLock);
745        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
746        switch (mState) {
747        case STOPPING_1:
748        case STOPPING_2:
749            if (!isOffloaded()) {
750                /* nothing to do if track is not offloaded */
751                break;
752            }
753
754            // Offloaded track was draining, we need to carry on draining when resumed
755            mResumeToStopping = true;
756            // fall through...
757        case ACTIVE:
758        case RESUMING:
759            mState = PAUSING;
760            ALOGV("ACTIVE/RESUMING => PAUSING (%d) on thread %p", mName, thread.get());
761            playbackThread->broadcast_l();
762            break;
763
764        default:
765            break;
766        }
767    }
768}
769
770void AudioFlinger::PlaybackThread::Track::flush()
771{
772    ALOGV("flush(%d)", mName);
773    sp<ThreadBase> thread = mThread.promote();
774    if (thread != 0) {
775        Mutex::Autolock _l(thread->mLock);
776        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
777
778        if (isOffloaded()) {
779            // If offloaded we allow flush during any state except terminated
780            // and keep the track active to avoid problems if user is seeking
781            // rapidly and underlying hardware has a significant delay handling
782            // a pause
783            if (isTerminated()) {
784                return;
785            }
786
787            ALOGV("flush: offload flush");
788            reset();
789
790            if (mState == STOPPING_1 || mState == STOPPING_2) {
791                ALOGV("flushed in STOPPING_1 or 2 state, change state to ACTIVE");
792                mState = ACTIVE;
793            }
794
795            mFlushHwPending = true;
796            mResumeToStopping = false;
797        } else {
798            if (mState != STOPPING_1 && mState != STOPPING_2 && mState != STOPPED &&
799                    mState != PAUSED && mState != PAUSING && mState != IDLE && mState != FLUSHED) {
800                return;
801            }
802            // No point remaining in PAUSED state after a flush => go to
803            // FLUSHED state
804            mState = FLUSHED;
805            // do not reset the track if it is still in the process of being stopped or paused.
806            // this will be done by prepareTracks_l() when the track is stopped.
807            // prepareTracks_l() will see mState == FLUSHED, then
808            // remove from active track list, reset(), and trigger presentation complete
809            if (isDirect()) {
810                mFlushHwPending = true;
811            }
812            if (playbackThread->mActiveTracks.indexOf(this) < 0) {
813                reset();
814            }
815        }
816        // Prevent flush being lost if the track is flushed and then resumed
817        // before mixer thread can run. This is important when offloading
818        // because the hardware buffer could hold a large amount of audio
819        playbackThread->broadcast_l();
820    }
821}
822
823// must be called with thread lock held
824void AudioFlinger::PlaybackThread::Track::flushAck()
825{
826    if (!isOffloaded() && !isDirect())
827        return;
828
829    mFlushHwPending = false;
830}
831
832void AudioFlinger::PlaybackThread::Track::reset()
833{
834    // Do not reset twice to avoid discarding data written just after a flush and before
835    // the audioflinger thread detects the track is stopped.
836    if (!mResetDone) {
837        // Force underrun condition to avoid false underrun callback until first data is
838        // written to buffer
839        android_atomic_and(~CBLK_FORCEREADY, &mCblk->mFlags);
840        mFillingUpStatus = FS_FILLING;
841        mResetDone = true;
842        if (mState == FLUSHED) {
843            mState = IDLE;
844        }
845    }
846}
847
848status_t AudioFlinger::PlaybackThread::Track::setParameters(const String8& keyValuePairs)
849{
850    sp<ThreadBase> thread = mThread.promote();
851    if (thread == 0) {
852        ALOGE("thread is dead");
853        return FAILED_TRANSACTION;
854    } else if ((thread->type() == ThreadBase::DIRECT) ||
855                    (thread->type() == ThreadBase::OFFLOAD)) {
856        return thread->setParameters(keyValuePairs);
857    } else {
858        return PERMISSION_DENIED;
859    }
860}
861
862status_t AudioFlinger::PlaybackThread::Track::getTimestamp(AudioTimestamp& timestamp)
863{
864    if (!isOffloaded() && !isDirect()) {
865        return INVALID_OPERATION; // normal tracks handled through SSQ
866    }
867    sp<ThreadBase> thread = mThread.promote();
868    if (thread == 0) {
869        return INVALID_OPERATION;
870    }
871
872    Mutex::Autolock _l(thread->mLock);
873    PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
874    return playbackThread->getTimestamp_l(timestamp);
875}
876
877status_t AudioFlinger::PlaybackThread::Track::attachAuxEffect(int EffectId)
878{
879    status_t status = DEAD_OBJECT;
880    sp<ThreadBase> thread = mThread.promote();
881    if (thread != 0) {
882        PlaybackThread *playbackThread = (PlaybackThread *)thread.get();
883        sp<AudioFlinger> af = mClient->audioFlinger();
884
885        Mutex::Autolock _l(af->mLock);
886
887        sp<PlaybackThread> srcThread = af->getEffectThread_l(AUDIO_SESSION_OUTPUT_MIX, EffectId);
888
889        if (EffectId != 0 && srcThread != 0 && playbackThread != srcThread.get()) {
890            Mutex::Autolock _dl(playbackThread->mLock);
891            Mutex::Autolock _sl(srcThread->mLock);
892            sp<EffectChain> chain = srcThread->getEffectChain_l(AUDIO_SESSION_OUTPUT_MIX);
893            if (chain == 0) {
894                return INVALID_OPERATION;
895            }
896
897            sp<EffectModule> effect = chain->getEffectFromId_l(EffectId);
898            if (effect == 0) {
899                return INVALID_OPERATION;
900            }
901            srcThread->removeEffect_l(effect);
902            status = playbackThread->addEffect_l(effect);
903            if (status != NO_ERROR) {
904                srcThread->addEffect_l(effect);
905                return INVALID_OPERATION;
906            }
907            // removeEffect_l() has stopped the effect if it was active so it must be restarted
908            if (effect->state() == EffectModule::ACTIVE ||
909                    effect->state() == EffectModule::STOPPING) {
910                effect->start();
911            }
912
913            sp<EffectChain> dstChain = effect->chain().promote();
914            if (dstChain == 0) {
915                srcThread->addEffect_l(effect);
916                return INVALID_OPERATION;
917            }
918            AudioSystem::unregisterEffect(effect->id());
919            AudioSystem::registerEffect(&effect->desc(),
920                                        srcThread->id(),
921                                        dstChain->strategy(),
922                                        AUDIO_SESSION_OUTPUT_MIX,
923                                        effect->id());
924            AudioSystem::setEffectEnabled(effect->id(), effect->isEnabled());
925        }
926        status = playbackThread->attachAuxEffect(this, EffectId);
927    }
928    return status;
929}
930
931void AudioFlinger::PlaybackThread::Track::setAuxBuffer(int EffectId, int32_t *buffer)
932{
933    mAuxEffectId = EffectId;
934    mAuxBuffer = buffer;
935}
936
937bool AudioFlinger::PlaybackThread::Track::presentationComplete(
938        int64_t framesWritten, size_t audioHalFrames)
939{
940    // TODO: improve this based on FrameMap if it exists, to ensure full drain.
941    // This assists in proper timestamp computation as well as wakelock management.
942
943    // a track is considered presented when the total number of frames written to audio HAL
944    // corresponds to the number of frames written when presentationComplete() is called for the
945    // first time (mPresentationCompleteFrames == 0) plus the buffer filling status at that time.
946    // For an offloaded track the HAL+h/w delay is variable so a HAL drain() is used
947    // to detect when all frames have been played. In this case framesWritten isn't
948    // useful because it doesn't always reflect whether there is data in the h/w
949    // buffers, particularly if a track has been paused and resumed during draining
950    ALOGV("presentationComplete() mPresentationCompleteFrames %lld framesWritten %lld",
951            (long long)mPresentationCompleteFrames, (long long)framesWritten);
952    if (mPresentationCompleteFrames == 0) {
953        mPresentationCompleteFrames = framesWritten + audioHalFrames;
954        ALOGV("presentationComplete() reset: mPresentationCompleteFrames %lld audioHalFrames %zu",
955                (long long)mPresentationCompleteFrames, audioHalFrames);
956    }
957
958    bool complete;
959    if (isOffloaded()) {
960        complete = true;
961    } else if (isDirect() || isFastTrack()) { // these do not go through linear map
962        complete = framesWritten >= mPresentationCompleteFrames;
963    } else {  // Normal tracks, OutputTracks, and PatchTracks
964        complete = framesWritten >= mPresentationCompleteFrames
965                && mAudioTrackServerProxy->isDrained();
966    }
967
968    if (complete) {
969        triggerEvents(AudioSystem::SYNC_EVENT_PRESENTATION_COMPLETE);
970        mAudioTrackServerProxy->setStreamEndDone();
971        return true;
972    }
973    return false;
974}
975
976void AudioFlinger::PlaybackThread::Track::triggerEvents(AudioSystem::sync_event_t type)
977{
978    for (size_t i = 0; i < mSyncEvents.size(); i++) {
979        if (mSyncEvents[i]->type() == type) {
980            mSyncEvents[i]->trigger();
981            mSyncEvents.removeAt(i);
982            i--;
983        }
984    }
985}
986
987// implement VolumeBufferProvider interface
988
989gain_minifloat_packed_t AudioFlinger::PlaybackThread::Track::getVolumeLR()
990{
991    // called by FastMixer, so not allowed to take any locks, block, or do I/O including logs
992    ALOG_ASSERT(isFastTrack() && (mCblk != NULL));
993    gain_minifloat_packed_t vlr = mAudioTrackServerProxy->getVolumeLR();
994    float vl = float_from_gain(gain_minifloat_unpack_left(vlr));
995    float vr = float_from_gain(gain_minifloat_unpack_right(vlr));
996    // track volumes come from shared memory, so can't be trusted and must be clamped
997    if (vl > GAIN_FLOAT_UNITY) {
998        vl = GAIN_FLOAT_UNITY;
999    }
1000    if (vr > GAIN_FLOAT_UNITY) {
1001        vr = GAIN_FLOAT_UNITY;
1002    }
1003    // now apply the cached master volume and stream type volume;
1004    // this is trusted but lacks any synchronization or barrier so may be stale
1005    float v = mCachedVolume;
1006    vl *= v;
1007    vr *= v;
1008    // re-combine into packed minifloat
1009    vlr = gain_minifloat_pack(gain_from_float(vl), gain_from_float(vr));
1010    // FIXME look at mute, pause, and stop flags
1011    return vlr;
1012}
1013
1014status_t AudioFlinger::PlaybackThread::Track::setSyncEvent(const sp<SyncEvent>& event)
1015{
1016    if (isTerminated() || mState == PAUSED ||
1017            ((framesReady() == 0) && ((mSharedBuffer != 0) ||
1018                                      (mState == STOPPED)))) {
1019        ALOGW("Track::setSyncEvent() in invalid state %d on session %d %s mode, framesReady %d ",
1020              mState, mSessionId, (mSharedBuffer != 0) ? "static" : "stream", framesReady());
1021        event->cancel();
1022        return INVALID_OPERATION;
1023    }
1024    (void) TrackBase::setSyncEvent(event);
1025    return NO_ERROR;
1026}
1027
1028void AudioFlinger::PlaybackThread::Track::invalidate()
1029{
1030    // FIXME should use proxy, and needs work
1031    audio_track_cblk_t* cblk = mCblk;
1032    android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1033    android_atomic_release_store(0x40000000, &cblk->mFutex);
1034    // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1035    (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
1036    mIsInvalid = true;
1037}
1038
1039void AudioFlinger::PlaybackThread::Track::signal()
1040{
1041    sp<ThreadBase> thread = mThread.promote();
1042    if (thread != 0) {
1043        PlaybackThread *t = (PlaybackThread *)thread.get();
1044        Mutex::Autolock _l(t->mLock);
1045        t->broadcast_l();
1046    }
1047}
1048
1049//To be called with thread lock held
1050bool AudioFlinger::PlaybackThread::Track::isResumePending() {
1051
1052    if (mState == RESUMING)
1053        return true;
1054    /* Resume is pending if track was stopping before pause was called */
1055    if (mState == STOPPING_1 &&
1056        mResumeToStopping)
1057        return true;
1058
1059    return false;
1060}
1061
1062//To be called with thread lock held
1063void AudioFlinger::PlaybackThread::Track::resumeAck() {
1064
1065
1066    if (mState == RESUMING)
1067        mState = ACTIVE;
1068
1069    // Other possibility of  pending resume is stopping_1 state
1070    // Do not update the state from stopping as this prevents
1071    // drain being called.
1072    if (mState == STOPPING_1) {
1073        mResumeToStopping = false;
1074    }
1075}
1076
1077//To be called with thread lock held
1078void AudioFlinger::PlaybackThread::Track::updateTrackFrameInfo(
1079        int64_t trackFramesReleased, int64_t sinkFramesWritten,
1080        const ExtendedTimestamp &timeStamp) {
1081    //update frame map
1082    mFrameMap.push(trackFramesReleased, sinkFramesWritten);
1083
1084    // adjust server times and set drained state.
1085    //
1086    // Our timestamps are only updated when the track is on the Thread active list.
1087    // We need to ensure that tracks are not removed before full drain.
1088    ExtendedTimestamp local = timeStamp;
1089    bool checked = false;
1090    for (int i = ExtendedTimestamp::LOCATION_MAX - 1;
1091            i >= ExtendedTimestamp::LOCATION_SERVER; --i) {
1092        // Lookup the track frame corresponding to the sink frame position.
1093        if (local.mTimeNs[i] > 0) {
1094            local.mPosition[i] = mFrameMap.findX(local.mPosition[i]);
1095            // check drain state from the latest stage in the pipeline.
1096            if (!checked) {
1097                mAudioTrackServerProxy->setDrained(
1098                        local.mPosition[i] >= mAudioTrackServerProxy->framesReleased());
1099                checked = true;
1100            }
1101        }
1102    }
1103    if (!checked) { // no server info, assume drained.
1104        mAudioTrackServerProxy->setDrained(true);
1105    }
1106    mServerProxy->setTimestamp(local);
1107}
1108
1109// ----------------------------------------------------------------------------
1110
1111AudioFlinger::PlaybackThread::OutputTrack::OutputTrack(
1112            PlaybackThread *playbackThread,
1113            DuplicatingThread *sourceThread,
1114            uint32_t sampleRate,
1115            audio_format_t format,
1116            audio_channel_mask_t channelMask,
1117            size_t frameCount,
1118            int uid)
1119    :   Track(playbackThread, NULL, AUDIO_STREAM_PATCH,
1120              sampleRate, format, channelMask, frameCount,
1121              NULL, 0, 0, uid, IAudioFlinger::TRACK_DEFAULT, TYPE_OUTPUT),
1122    mActive(false), mSourceThread(sourceThread), mClientProxy(NULL)
1123{
1124
1125    if (mCblk != NULL) {
1126        mOutBuffer.frameCount = 0;
1127        playbackThread->mTracks.add(this);
1128        ALOGV("OutputTrack constructor mCblk %p, mBuffer %p, "
1129                "frameCount %u, mChannelMask 0x%08x",
1130                mCblk, mBuffer,
1131                frameCount, mChannelMask);
1132        // since client and server are in the same process,
1133        // the buffer has the same virtual address on both sides
1134        mClientProxy = new AudioTrackClientProxy(mCblk, mBuffer, mFrameCount, mFrameSize,
1135                true /*clientInServer*/);
1136        mClientProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
1137        mClientProxy->setSendLevel(0.0);
1138        mClientProxy->setSampleRate(sampleRate);
1139    } else {
1140        ALOGW("Error creating output track on thread %p", playbackThread);
1141    }
1142}
1143
1144AudioFlinger::PlaybackThread::OutputTrack::~OutputTrack()
1145{
1146    clearBufferQueue();
1147    delete mClientProxy;
1148    // superclass destructor will now delete the server proxy and shared memory both refer to
1149}
1150
1151status_t AudioFlinger::PlaybackThread::OutputTrack::start(AudioSystem::sync_event_t event,
1152                                                          int triggerSession)
1153{
1154    status_t status = Track::start(event, triggerSession);
1155    if (status != NO_ERROR) {
1156        return status;
1157    }
1158
1159    mActive = true;
1160    mRetryCount = 127;
1161    return status;
1162}
1163
1164void AudioFlinger::PlaybackThread::OutputTrack::stop()
1165{
1166    Track::stop();
1167    clearBufferQueue();
1168    mOutBuffer.frameCount = 0;
1169    mActive = false;
1170}
1171
1172bool AudioFlinger::PlaybackThread::OutputTrack::write(void* data, uint32_t frames)
1173{
1174    Buffer *pInBuffer;
1175    Buffer inBuffer;
1176    bool outputBufferFull = false;
1177    inBuffer.frameCount = frames;
1178    inBuffer.raw = data;
1179
1180    uint32_t waitTimeLeftMs = mSourceThread->waitTimeMs();
1181
1182    if (!mActive && frames != 0) {
1183        (void) start();
1184    }
1185
1186    while (waitTimeLeftMs) {
1187        // First write pending buffers, then new data
1188        if (mBufferQueue.size()) {
1189            pInBuffer = mBufferQueue.itemAt(0);
1190        } else {
1191            pInBuffer = &inBuffer;
1192        }
1193
1194        if (pInBuffer->frameCount == 0) {
1195            break;
1196        }
1197
1198        if (mOutBuffer.frameCount == 0) {
1199            mOutBuffer.frameCount = pInBuffer->frameCount;
1200            nsecs_t startTime = systemTime();
1201            status_t status = obtainBuffer(&mOutBuffer, waitTimeLeftMs);
1202            if (status != NO_ERROR) {
1203                ALOGV("OutputTrack::write() %p thread %p no more output buffers; status %d", this,
1204                        mThread.unsafe_get(), status);
1205                outputBufferFull = true;
1206                break;
1207            }
1208            uint32_t waitTimeMs = (uint32_t)ns2ms(systemTime() - startTime);
1209            if (waitTimeLeftMs >= waitTimeMs) {
1210                waitTimeLeftMs -= waitTimeMs;
1211            } else {
1212                waitTimeLeftMs = 0;
1213            }
1214        }
1215
1216        uint32_t outFrames = pInBuffer->frameCount > mOutBuffer.frameCount ? mOutBuffer.frameCount :
1217                pInBuffer->frameCount;
1218        memcpy(mOutBuffer.raw, pInBuffer->raw, outFrames * mFrameSize);
1219        Proxy::Buffer buf;
1220        buf.mFrameCount = outFrames;
1221        buf.mRaw = NULL;
1222        mClientProxy->releaseBuffer(&buf);
1223        pInBuffer->frameCount -= outFrames;
1224        pInBuffer->raw = (int8_t *)pInBuffer->raw + outFrames * mFrameSize;
1225        mOutBuffer.frameCount -= outFrames;
1226        mOutBuffer.raw = (int8_t *)mOutBuffer.raw + outFrames * mFrameSize;
1227
1228        if (pInBuffer->frameCount == 0) {
1229            if (mBufferQueue.size()) {
1230                mBufferQueue.removeAt(0);
1231                free(pInBuffer->mBuffer);
1232                delete pInBuffer;
1233                ALOGV("OutputTrack::write() %p thread %p released overflow buffer %d", this,
1234                        mThread.unsafe_get(), mBufferQueue.size());
1235            } else {
1236                break;
1237            }
1238        }
1239    }
1240
1241    // If we could not write all frames, allocate a buffer and queue it for next time.
1242    if (inBuffer.frameCount) {
1243        sp<ThreadBase> thread = mThread.promote();
1244        if (thread != 0 && !thread->standby()) {
1245            if (mBufferQueue.size() < kMaxOverFlowBuffers) {
1246                pInBuffer = new Buffer;
1247                pInBuffer->mBuffer = malloc(inBuffer.frameCount * mFrameSize);
1248                pInBuffer->frameCount = inBuffer.frameCount;
1249                pInBuffer->raw = pInBuffer->mBuffer;
1250                memcpy(pInBuffer->raw, inBuffer.raw, inBuffer.frameCount * mFrameSize);
1251                mBufferQueue.add(pInBuffer);
1252                ALOGV("OutputTrack::write() %p thread %p adding overflow buffer %d", this,
1253                        mThread.unsafe_get(), mBufferQueue.size());
1254            } else {
1255                ALOGW("OutputTrack::write() %p thread %p no more overflow buffers",
1256                        mThread.unsafe_get(), this);
1257            }
1258        }
1259    }
1260
1261    // Calling write() with a 0 length buffer means that no more data will be written:
1262    // We rely on stop() to set the appropriate flags to allow the remaining frames to play out.
1263    if (frames == 0 && mBufferQueue.size() == 0 && mActive) {
1264        stop();
1265    }
1266
1267    return outputBufferFull;
1268}
1269
1270status_t AudioFlinger::PlaybackThread::OutputTrack::obtainBuffer(
1271        AudioBufferProvider::Buffer* buffer, uint32_t waitTimeMs)
1272{
1273    ClientProxy::Buffer buf;
1274    buf.mFrameCount = buffer->frameCount;
1275    struct timespec timeout;
1276    timeout.tv_sec = waitTimeMs / 1000;
1277    timeout.tv_nsec = (int) (waitTimeMs % 1000) * 1000000;
1278    status_t status = mClientProxy->obtainBuffer(&buf, &timeout);
1279    buffer->frameCount = buf.mFrameCount;
1280    buffer->raw = buf.mRaw;
1281    return status;
1282}
1283
1284void AudioFlinger::PlaybackThread::OutputTrack::clearBufferQueue()
1285{
1286    size_t size = mBufferQueue.size();
1287
1288    for (size_t i = 0; i < size; i++) {
1289        Buffer *pBuffer = mBufferQueue.itemAt(i);
1290        free(pBuffer->mBuffer);
1291        delete pBuffer;
1292    }
1293    mBufferQueue.clear();
1294}
1295
1296
1297AudioFlinger::PlaybackThread::PatchTrack::PatchTrack(PlaybackThread *playbackThread,
1298                                                     audio_stream_type_t streamType,
1299                                                     uint32_t sampleRate,
1300                                                     audio_channel_mask_t channelMask,
1301                                                     audio_format_t format,
1302                                                     size_t frameCount,
1303                                                     void *buffer,
1304                                                     IAudioFlinger::track_flags_t flags)
1305    :   Track(playbackThread, NULL, streamType,
1306              sampleRate, format, channelMask, frameCount,
1307              buffer, 0, 0, getuid(), flags, TYPE_PATCH),
1308              mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, true, true))
1309{
1310    uint64_t mixBufferNs = ((uint64_t)2 * playbackThread->frameCount() * 1000000000) /
1311                                                                    playbackThread->sampleRate();
1312    mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1313    mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1314
1315    ALOGV("PatchTrack %p sampleRate %d mPeerTimeout %d.%03d sec",
1316                                      this, sampleRate,
1317                                      (int)mPeerTimeout.tv_sec,
1318                                      (int)(mPeerTimeout.tv_nsec / 1000000));
1319}
1320
1321AudioFlinger::PlaybackThread::PatchTrack::~PatchTrack()
1322{
1323}
1324
1325// AudioBufferProvider interface
1326status_t AudioFlinger::PlaybackThread::PatchTrack::getNextBuffer(
1327        AudioBufferProvider::Buffer* buffer)
1328{
1329    ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::getNextBuffer() called without peer proxy");
1330    Proxy::Buffer buf;
1331    buf.mFrameCount = buffer->frameCount;
1332    status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1333    ALOGV_IF(status != NO_ERROR, "PatchTrack() %p getNextBuffer status %d", this, status);
1334    buffer->frameCount = buf.mFrameCount;
1335    if (buf.mFrameCount == 0) {
1336        return WOULD_BLOCK;
1337    }
1338    status = Track::getNextBuffer(buffer);
1339    return status;
1340}
1341
1342void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1343{
1344    ALOG_ASSERT(mPeerProxy != 0, "PatchTrack::releaseBuffer() called without peer proxy");
1345    Proxy::Buffer buf;
1346    buf.mFrameCount = buffer->frameCount;
1347    buf.mRaw = buffer->raw;
1348    mPeerProxy->releaseBuffer(&buf);
1349    TrackBase::releaseBuffer(buffer);
1350}
1351
1352status_t AudioFlinger::PlaybackThread::PatchTrack::obtainBuffer(Proxy::Buffer* buffer,
1353                                                                const struct timespec *timeOut)
1354{
1355    return mProxy->obtainBuffer(buffer, timeOut);
1356}
1357
1358void AudioFlinger::PlaybackThread::PatchTrack::releaseBuffer(Proxy::Buffer* buffer)
1359{
1360    mProxy->releaseBuffer(buffer);
1361    if (android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags) & CBLK_DISABLED) {
1362        ALOGW("PatchTrack::releaseBuffer() disabled due to previous underrun, restarting");
1363        start();
1364    }
1365    android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1366}
1367
1368// ----------------------------------------------------------------------------
1369//      Record
1370// ----------------------------------------------------------------------------
1371
1372AudioFlinger::RecordHandle::RecordHandle(
1373        const sp<AudioFlinger::RecordThread::RecordTrack>& recordTrack)
1374    : BnAudioRecord(),
1375    mRecordTrack(recordTrack)
1376{
1377}
1378
1379AudioFlinger::RecordHandle::~RecordHandle() {
1380    stop_nonvirtual();
1381    mRecordTrack->destroy();
1382}
1383
1384status_t AudioFlinger::RecordHandle::start(int /*AudioSystem::sync_event_t*/ event,
1385        int triggerSession) {
1386    ALOGV("RecordHandle::start()");
1387    return mRecordTrack->start((AudioSystem::sync_event_t)event, triggerSession);
1388}
1389
1390void AudioFlinger::RecordHandle::stop() {
1391    stop_nonvirtual();
1392}
1393
1394void AudioFlinger::RecordHandle::stop_nonvirtual() {
1395    ALOGV("RecordHandle::stop()");
1396    mRecordTrack->stop();
1397}
1398
1399status_t AudioFlinger::RecordHandle::onTransact(
1400    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1401{
1402    return BnAudioRecord::onTransact(code, data, reply, flags);
1403}
1404
1405// ----------------------------------------------------------------------------
1406
1407// RecordTrack constructor must be called with AudioFlinger::mLock and ThreadBase::mLock held
1408AudioFlinger::RecordThread::RecordTrack::RecordTrack(
1409            RecordThread *thread,
1410            const sp<Client>& client,
1411            uint32_t sampleRate,
1412            audio_format_t format,
1413            audio_channel_mask_t channelMask,
1414            size_t frameCount,
1415            void *buffer,
1416            int sessionId,
1417            int uid,
1418            IAudioFlinger::track_flags_t flags,
1419            track_type type)
1420    :   TrackBase(thread, client, sampleRate, format,
1421                  channelMask, frameCount, buffer, sessionId, uid,
1422                  flags, false /*isOut*/,
1423                  (type == TYPE_DEFAULT) ?
1424                          ((flags & IAudioFlinger::TRACK_FAST) ? ALLOC_PIPE : ALLOC_CBLK) :
1425                          ((buffer == NULL) ? ALLOC_LOCAL : ALLOC_NONE),
1426                  type),
1427        mOverflow(false),
1428        mFramesToDrop(0),
1429        mResamplerBufferProvider(NULL), // initialize in case of early constructor exit
1430        mRecordBufferConverter(NULL)
1431{
1432    if (mCblk == NULL) {
1433        return;
1434    }
1435
1436    mRecordBufferConverter = new RecordBufferConverter(
1437            thread->mChannelMask, thread->mFormat, thread->mSampleRate,
1438            channelMask, format, sampleRate);
1439    // Check if the RecordBufferConverter construction was successful.
1440    // If not, don't continue with construction.
1441    //
1442    // NOTE: It would be extremely rare that the record track cannot be created
1443    // for the current device, but a pending or future device change would make
1444    // the record track configuration valid.
1445    if (mRecordBufferConverter->initCheck() != NO_ERROR) {
1446        ALOGE("RecordTrack unable to create record buffer converter");
1447        return;
1448    }
1449
1450    mServerProxy = new AudioRecordServerProxy(mCblk, mBuffer, frameCount,
1451            mFrameSize, !isExternalTrack());
1452
1453    mResamplerBufferProvider = new ResamplerBufferProvider(this);
1454
1455    if (flags & IAudioFlinger::TRACK_FAST) {
1456        ALOG_ASSERT(thread->mFastTrackAvail);
1457        thread->mFastTrackAvail = false;
1458    }
1459}
1460
1461AudioFlinger::RecordThread::RecordTrack::~RecordTrack()
1462{
1463    ALOGV("%s", __func__);
1464    delete mRecordBufferConverter;
1465    delete mResamplerBufferProvider;
1466}
1467
1468status_t AudioFlinger::RecordThread::RecordTrack::initCheck() const
1469{
1470    status_t status = TrackBase::initCheck();
1471    if (status == NO_ERROR && mServerProxy == 0) {
1472        status = BAD_VALUE;
1473    }
1474    return status;
1475}
1476
1477// AudioBufferProvider interface
1478status_t AudioFlinger::RecordThread::RecordTrack::getNextBuffer(AudioBufferProvider::Buffer* buffer)
1479{
1480    ServerProxy::Buffer buf;
1481    buf.mFrameCount = buffer->frameCount;
1482    status_t status = mServerProxy->obtainBuffer(&buf);
1483    buffer->frameCount = buf.mFrameCount;
1484    buffer->raw = buf.mRaw;
1485    if (buf.mFrameCount == 0) {
1486        // FIXME also wake futex so that overrun is noticed more quickly
1487        (void) android_atomic_or(CBLK_OVERRUN, &mCblk->mFlags);
1488    }
1489    return status;
1490}
1491
1492status_t AudioFlinger::RecordThread::RecordTrack::start(AudioSystem::sync_event_t event,
1493                                                        int triggerSession)
1494{
1495    sp<ThreadBase> thread = mThread.promote();
1496    if (thread != 0) {
1497        RecordThread *recordThread = (RecordThread *)thread.get();
1498        return recordThread->start(this, event, triggerSession);
1499    } else {
1500        return BAD_VALUE;
1501    }
1502}
1503
1504void AudioFlinger::RecordThread::RecordTrack::stop()
1505{
1506    sp<ThreadBase> thread = mThread.promote();
1507    if (thread != 0) {
1508        RecordThread *recordThread = (RecordThread *)thread.get();
1509        if (recordThread->stop(this) && isExternalTrack()) {
1510            AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
1511        }
1512    }
1513}
1514
1515void AudioFlinger::RecordThread::RecordTrack::destroy()
1516{
1517    // see comments at AudioFlinger::PlaybackThread::Track::destroy()
1518    sp<RecordTrack> keep(this);
1519    {
1520        if (isExternalTrack()) {
1521            if (mState == ACTIVE || mState == RESUMING) {
1522                AudioSystem::stopInput(mThreadIoHandle, (audio_session_t)mSessionId);
1523            }
1524            AudioSystem::releaseInput(mThreadIoHandle, (audio_session_t)mSessionId);
1525        }
1526        sp<ThreadBase> thread = mThread.promote();
1527        if (thread != 0) {
1528            Mutex::Autolock _l(thread->mLock);
1529            RecordThread *recordThread = (RecordThread *) thread.get();
1530            recordThread->destroyTrack_l(this);
1531        }
1532    }
1533}
1534
1535void AudioFlinger::RecordThread::RecordTrack::invalidate()
1536{
1537    // FIXME should use proxy, and needs work
1538    audio_track_cblk_t* cblk = mCblk;
1539    android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1540    android_atomic_release_store(0x40000000, &cblk->mFutex);
1541    // client is not in server, so FUTEX_WAKE is needed instead of FUTEX_WAKE_PRIVATE
1542    (void) syscall(__NR_futex, &cblk->mFutex, FUTEX_WAKE, INT_MAX);
1543}
1544
1545
1546/*static*/ void AudioFlinger::RecordThread::RecordTrack::appendDumpHeader(String8& result)
1547{
1548    result.append("    Active Client Fmt Chn mask Session S   Server fCount SRate\n");
1549}
1550
1551void AudioFlinger::RecordThread::RecordTrack::dump(char* buffer, size_t size, bool active)
1552{
1553    snprintf(buffer, size, "    %6s %6u %3u %08X %7u %1d %08X %6zu %5u\n",
1554            active ? "yes" : "no",
1555            (mClient == 0) ? getpid_cached : mClient->pid(),
1556            mFormat,
1557            mChannelMask,
1558            mSessionId,
1559            mState,
1560            mCblk->mServer,
1561            mFrameCount,
1562            mSampleRate);
1563
1564}
1565
1566void AudioFlinger::RecordThread::RecordTrack::handleSyncStartEvent(const sp<SyncEvent>& event)
1567{
1568    if (event == mSyncStartEvent) {
1569        ssize_t framesToDrop = 0;
1570        sp<ThreadBase> threadBase = mThread.promote();
1571        if (threadBase != 0) {
1572            // TODO: use actual buffer filling status instead of 2 buffers when info is available
1573            // from audio HAL
1574            framesToDrop = threadBase->mFrameCount * 2;
1575        }
1576        mFramesToDrop = framesToDrop;
1577    }
1578}
1579
1580void AudioFlinger::RecordThread::RecordTrack::clearSyncStartEvent()
1581{
1582    if (mSyncStartEvent != 0) {
1583        mSyncStartEvent->cancel();
1584        mSyncStartEvent.clear();
1585    }
1586    mFramesToDrop = 0;
1587}
1588
1589void AudioFlinger::RecordThread::RecordTrack::updateTrackFrameInfo(
1590        int64_t trackFramesReleased, int64_t sourceFramesRead,
1591        uint32_t halSampleRate, const ExtendedTimestamp &timestamp)
1592{
1593    ExtendedTimestamp local = timestamp;
1594
1595    // Convert HAL frames to server-side track frames at track sample rate.
1596    // We use trackFramesReleased and sourceFramesRead as an anchor point.
1597    for (int i = ExtendedTimestamp::LOCATION_SERVER; i < ExtendedTimestamp::LOCATION_MAX; ++i) {
1598        if (local.mTimeNs[i] != 0) {
1599            const int64_t relativeServerFrames = local.mPosition[i] - sourceFramesRead;
1600            const int64_t relativeTrackFrames = relativeServerFrames
1601                    * mSampleRate / halSampleRate; // TODO: potential computation overflow
1602            local.mPosition[i] = relativeTrackFrames + trackFramesReleased;
1603        }
1604    }
1605    mServerProxy->setTimestamp(local);
1606}
1607
1608AudioFlinger::RecordThread::PatchRecord::PatchRecord(RecordThread *recordThread,
1609                                                     uint32_t sampleRate,
1610                                                     audio_channel_mask_t channelMask,
1611                                                     audio_format_t format,
1612                                                     size_t frameCount,
1613                                                     void *buffer,
1614                                                     IAudioFlinger::track_flags_t flags)
1615    :   RecordTrack(recordThread, NULL, sampleRate, format, channelMask, frameCount,
1616                buffer, 0, getuid(), flags, TYPE_PATCH),
1617                mProxy(new ClientProxy(mCblk, mBuffer, frameCount, mFrameSize, false, true))
1618{
1619    uint64_t mixBufferNs = ((uint64_t)2 * recordThread->frameCount() * 1000000000) /
1620                                                                recordThread->sampleRate();
1621    mPeerTimeout.tv_sec = mixBufferNs / 1000000000;
1622    mPeerTimeout.tv_nsec = (int) (mixBufferNs % 1000000000);
1623
1624    ALOGV("PatchRecord %p sampleRate %d mPeerTimeout %d.%03d sec",
1625                                      this, sampleRate,
1626                                      (int)mPeerTimeout.tv_sec,
1627                                      (int)(mPeerTimeout.tv_nsec / 1000000));
1628}
1629
1630AudioFlinger::RecordThread::PatchRecord::~PatchRecord()
1631{
1632}
1633
1634// AudioBufferProvider interface
1635status_t AudioFlinger::RecordThread::PatchRecord::getNextBuffer(
1636                                                  AudioBufferProvider::Buffer* buffer)
1637{
1638    ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::getNextBuffer() called without peer proxy");
1639    Proxy::Buffer buf;
1640    buf.mFrameCount = buffer->frameCount;
1641    status_t status = mPeerProxy->obtainBuffer(&buf, &mPeerTimeout);
1642    ALOGV_IF(status != NO_ERROR,
1643             "PatchRecord() %p mPeerProxy->obtainBuffer status %d", this, status);
1644    buffer->frameCount = buf.mFrameCount;
1645    if (buf.mFrameCount == 0) {
1646        return WOULD_BLOCK;
1647    }
1648    status = RecordTrack::getNextBuffer(buffer);
1649    return status;
1650}
1651
1652void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(AudioBufferProvider::Buffer* buffer)
1653{
1654    ALOG_ASSERT(mPeerProxy != 0, "PatchRecord::releaseBuffer() called without peer proxy");
1655    Proxy::Buffer buf;
1656    buf.mFrameCount = buffer->frameCount;
1657    buf.mRaw = buffer->raw;
1658    mPeerProxy->releaseBuffer(&buf);
1659    TrackBase::releaseBuffer(buffer);
1660}
1661
1662status_t AudioFlinger::RecordThread::PatchRecord::obtainBuffer(Proxy::Buffer* buffer,
1663                                                               const struct timespec *timeOut)
1664{
1665    return mProxy->obtainBuffer(buffer, timeOut);
1666}
1667
1668void AudioFlinger::RecordThread::PatchRecord::releaseBuffer(Proxy::Buffer* buffer)
1669{
1670    mProxy->releaseBuffer(buffer);
1671}
1672
1673} // namespace android
1674