AudioTrack.cpp revision cd04484f4837b8ca0041d118286ab6a98e84fc75
1/*
2**
3** Copyright 2007, 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//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
21#include <inttypes.h>
22#include <math.h>
23#include <sys/resource.h>
24
25#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
29#include <private/media/AudioTrackShared.h>
30#include <media/IAudioFlinger.h>
31#include <media/AudioResamplerPublic.h>
32
33#define WAIT_PERIOD_MS                  10
34#define WAIT_STREAM_END_TIMEOUT_SEC     120
35
36
37namespace android {
38// ---------------------------------------------------------------------------
39
40// static
41status_t AudioTrack::getMinFrameCount(
42        size_t* frameCount,
43        audio_stream_type_t streamType,
44        uint32_t sampleRate)
45{
46    if (frameCount == NULL) {
47        return BAD_VALUE;
48    }
49
50    // FIXME merge with similar code in createTrack_l(), except we're missing
51    //       some information here that is available in createTrack_l():
52    //          audio_io_handle_t output
53    //          audio_format_t format
54    //          audio_channel_mask_t channelMask
55    //          audio_output_flags_t flags
56    uint32_t afSampleRate;
57    status_t status;
58    status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
59    if (status != NO_ERROR) {
60        ALOGE("Unable to query output sample rate for stream type %d; status %d",
61                streamType, status);
62        return status;
63    }
64    size_t afFrameCount;
65    status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
66    if (status != NO_ERROR) {
67        ALOGE("Unable to query output frame count for stream type %d; status %d",
68                streamType, status);
69        return status;
70    }
71    uint32_t afLatency;
72    status = AudioSystem::getOutputLatency(&afLatency, streamType);
73    if (status != NO_ERROR) {
74        ALOGE("Unable to query output latency for stream type %d; status %d",
75                streamType, status);
76        return status;
77    }
78
79    // Ensure that buffer depth covers at least audio hardware latency
80    uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
81    if (minBufCount < 2) {
82        minBufCount = 2;
83    }
84
85    *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
86            afFrameCount * minBufCount * uint64_t(sampleRate) / afSampleRate;
87    // The formula above should always produce a non-zero value, but return an error
88    // in the unlikely event that it does not, as that's part of the API contract.
89    if (*frameCount == 0) {
90        ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %d",
91                streamType, sampleRate);
92        return BAD_VALUE;
93    }
94    ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, minBufCount=%d, afSampleRate=%d, afLatency=%d",
95            *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
96    return NO_ERROR;
97}
98
99// ---------------------------------------------------------------------------
100
101AudioTrack::AudioTrack()
102    : mStatus(NO_INIT),
103      mIsTimed(false),
104      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
105      mPreviousSchedulingGroup(SP_DEFAULT),
106      mPausedPosition(0)
107{
108    mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
109    mAttributes.usage = AUDIO_USAGE_UNKNOWN;
110    mAttributes.flags = 0x0;
111    strcpy(mAttributes.tags, "");
112}
113
114AudioTrack::AudioTrack(
115        audio_stream_type_t streamType,
116        uint32_t sampleRate,
117        audio_format_t format,
118        audio_channel_mask_t channelMask,
119        size_t frameCount,
120        audio_output_flags_t flags,
121        callback_t cbf,
122        void* user,
123        uint32_t notificationFrames,
124        int sessionId,
125        transfer_type transferType,
126        const audio_offload_info_t *offloadInfo,
127        int uid,
128        pid_t pid,
129        const audio_attributes_t* pAttributes)
130    : mStatus(NO_INIT),
131      mIsTimed(false),
132      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
133      mPreviousSchedulingGroup(SP_DEFAULT),
134      mPausedPosition(0)
135{
136    mStatus = set(streamType, sampleRate, format, channelMask,
137            frameCount, flags, cbf, user, notificationFrames,
138            0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
139            offloadInfo, uid, pid, pAttributes);
140}
141
142AudioTrack::AudioTrack(
143        audio_stream_type_t streamType,
144        uint32_t sampleRate,
145        audio_format_t format,
146        audio_channel_mask_t channelMask,
147        const sp<IMemory>& sharedBuffer,
148        audio_output_flags_t flags,
149        callback_t cbf,
150        void* user,
151        uint32_t notificationFrames,
152        int sessionId,
153        transfer_type transferType,
154        const audio_offload_info_t *offloadInfo,
155        int uid,
156        pid_t pid,
157        const audio_attributes_t* pAttributes)
158    : mStatus(NO_INIT),
159      mIsTimed(false),
160      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
161      mPreviousSchedulingGroup(SP_DEFAULT),
162      mPausedPosition(0)
163{
164    mStatus = set(streamType, sampleRate, format, channelMask,
165            0 /*frameCount*/, flags, cbf, user, notificationFrames,
166            sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
167            uid, pid, pAttributes);
168}
169
170AudioTrack::~AudioTrack()
171{
172    if (mStatus == NO_ERROR) {
173        // Make sure that callback function exits in the case where
174        // it is looping on buffer full condition in obtainBuffer().
175        // Otherwise the callback thread will never exit.
176        stop();
177        if (mAudioTrackThread != 0) {
178            mProxy->interrupt();
179            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
180            mAudioTrackThread->requestExitAndWait();
181            mAudioTrackThread.clear();
182        }
183        mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
184        mAudioTrack.clear();
185        mCblkMemory.clear();
186        mSharedBuffer.clear();
187        IPCThreadState::self()->flushCommands();
188        ALOGV("~AudioTrack, releasing session id from %d on behalf of %d",
189                IPCThreadState::self()->getCallingPid(), mClientPid);
190        AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
191    }
192}
193
194status_t AudioTrack::set(
195        audio_stream_type_t streamType,
196        uint32_t sampleRate,
197        audio_format_t format,
198        audio_channel_mask_t channelMask,
199        size_t frameCount,
200        audio_output_flags_t flags,
201        callback_t cbf,
202        void* user,
203        uint32_t notificationFrames,
204        const sp<IMemory>& sharedBuffer,
205        bool threadCanCallJava,
206        int sessionId,
207        transfer_type transferType,
208        const audio_offload_info_t *offloadInfo,
209        int uid,
210        pid_t pid,
211        const audio_attributes_t* pAttributes)
212{
213    ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
214          "flags #%x, notificationFrames %u, sessionId %d, transferType %d",
215          streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
216          sessionId, transferType);
217
218    switch (transferType) {
219    case TRANSFER_DEFAULT:
220        if (sharedBuffer != 0) {
221            transferType = TRANSFER_SHARED;
222        } else if (cbf == NULL || threadCanCallJava) {
223            transferType = TRANSFER_SYNC;
224        } else {
225            transferType = TRANSFER_CALLBACK;
226        }
227        break;
228    case TRANSFER_CALLBACK:
229        if (cbf == NULL || sharedBuffer != 0) {
230            ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
231            return BAD_VALUE;
232        }
233        break;
234    case TRANSFER_OBTAIN:
235    case TRANSFER_SYNC:
236        if (sharedBuffer != 0) {
237            ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
238            return BAD_VALUE;
239        }
240        break;
241    case TRANSFER_SHARED:
242        if (sharedBuffer == 0) {
243            ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
244            return BAD_VALUE;
245        }
246        break;
247    default:
248        ALOGE("Invalid transfer type %d", transferType);
249        return BAD_VALUE;
250    }
251    mSharedBuffer = sharedBuffer;
252    mTransfer = transferType;
253
254    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
255            sharedBuffer->size());
256
257    ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
258
259    AutoMutex lock(mLock);
260
261    // invariant that mAudioTrack != 0 is true only after set() returns successfully
262    if (mAudioTrack != 0) {
263        ALOGE("Track already in use");
264        return INVALID_OPERATION;
265    }
266
267    // handle default values first.
268    if (streamType == AUDIO_STREAM_DEFAULT) {
269        streamType = AUDIO_STREAM_MUSIC;
270    }
271
272    if (pAttributes == NULL) {
273        if (uint32_t(streamType) >= AUDIO_STREAM_CNT) {
274            ALOGE("Invalid stream type %d", streamType);
275            return BAD_VALUE;
276        }
277        setAttributesFromStreamType(streamType);
278        mStreamType = streamType;
279    } else {
280        if (!isValidAttributes(pAttributes)) {
281            ALOGE("Invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
282                pAttributes->usage, pAttributes->content_type, pAttributes->flags,
283                pAttributes->tags);
284        }
285        // stream type shouldn't be looked at, this track has audio attributes
286        memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
287        setStreamTypeFromAttributes(mAttributes);
288        ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
289                mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
290    }
291
292    status_t status;
293    if (sampleRate == 0) {
294        status = AudioSystem::getOutputSamplingRateForAttr(&sampleRate, &mAttributes);
295        if (status != NO_ERROR) {
296            ALOGE("Could not get output sample rate for stream type %d; status %d",
297                    mStreamType, status);
298            return status;
299        }
300    }
301    mSampleRate = sampleRate;
302
303    // these below should probably come from the audioFlinger too...
304    if (format == AUDIO_FORMAT_DEFAULT) {
305        format = AUDIO_FORMAT_PCM_16_BIT;
306    }
307
308    // validate parameters
309    if (!audio_is_valid_format(format)) {
310        ALOGE("Invalid format %#x", format);
311        return BAD_VALUE;
312    }
313    mFormat = format;
314
315    if (!audio_is_output_channel(channelMask)) {
316        ALOGE("Invalid channel mask %#x", channelMask);
317        return BAD_VALUE;
318    }
319    mChannelMask = channelMask;
320    uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
321    mChannelCount = channelCount;
322
323    // AudioFlinger does not currently support 8-bit data in shared memory
324    if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
325        ALOGE("8-bit data in shared memory is not supported");
326        return BAD_VALUE;
327    }
328
329    // force direct flag if format is not linear PCM
330    // or offload was requested
331    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
332            || !audio_is_linear_pcm(format)) {
333        ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
334                    ? "Offload request, forcing to Direct Output"
335                    : "Not linear PCM, forcing to Direct Output");
336        flags = (audio_output_flags_t)
337                // FIXME why can't we allow direct AND fast?
338                ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
339    }
340    // only allow deep buffering for music stream type
341    if (mStreamType != AUDIO_STREAM_MUSIC) {
342        flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
343    }
344
345    if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
346        if (audio_is_linear_pcm(format)) {
347            mFrameSize = channelCount * audio_bytes_per_sample(format);
348        } else {
349            mFrameSize = sizeof(uint8_t);
350        }
351        mFrameSizeAF = mFrameSize;
352    } else {
353        ALOG_ASSERT(audio_is_linear_pcm(format));
354        mFrameSize = channelCount * audio_bytes_per_sample(format);
355        mFrameSizeAF = channelCount * audio_bytes_per_sample(
356                format == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : format);
357        // createTrack will return an error if PCM format is not supported by server,
358        // so no need to check for specific PCM formats here
359    }
360
361    // Make copy of input parameter offloadInfo so that in the future:
362    //  (a) createTrack_l doesn't need it as an input parameter
363    //  (b) we can support re-creation of offloaded tracks
364    if (offloadInfo != NULL) {
365        mOffloadInfoCopy = *offloadInfo;
366        mOffloadInfo = &mOffloadInfoCopy;
367    } else {
368        mOffloadInfo = NULL;
369    }
370
371    mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
372    mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
373    mSendLevel = 0.0f;
374    // mFrameCount is initialized in createTrack_l
375    mReqFrameCount = frameCount;
376    mNotificationFramesReq = notificationFrames;
377    mNotificationFramesAct = 0;
378    mSessionId = sessionId;
379    int callingpid = IPCThreadState::self()->getCallingPid();
380    int mypid = getpid();
381    if (uid == -1 || (callingpid != mypid)) {
382        mClientUid = IPCThreadState::self()->getCallingUid();
383    } else {
384        mClientUid = uid;
385    }
386    if (pid == -1 || (callingpid != mypid)) {
387        mClientPid = callingpid;
388    } else {
389        mClientPid = pid;
390    }
391    mAuxEffectId = 0;
392    mFlags = flags;
393    mCbf = cbf;
394
395    if (cbf != NULL) {
396        mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
397        mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
398    }
399
400    // create the IAudioTrack
401    status = createTrack_l(0 /*epoch*/);
402
403    if (status != NO_ERROR) {
404        if (mAudioTrackThread != 0) {
405            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
406            mAudioTrackThread->requestExitAndWait();
407            mAudioTrackThread.clear();
408        }
409        return status;
410    }
411
412    mStatus = NO_ERROR;
413    mState = STATE_STOPPED;
414    mUserData = user;
415    mLoopPeriod = 0;
416    mMarkerPosition = 0;
417    mMarkerReached = false;
418    mNewPosition = 0;
419    mUpdatePeriod = 0;
420    AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
421    mSequence = 1;
422    mObservedSequence = mSequence;
423    mInUnderrun = false;
424
425    return NO_ERROR;
426}
427
428// -------------------------------------------------------------------------
429
430status_t AudioTrack::start()
431{
432    AutoMutex lock(mLock);
433
434    if (mState == STATE_ACTIVE) {
435        return INVALID_OPERATION;
436    }
437
438    mInUnderrun = true;
439
440    State previousState = mState;
441    if (previousState == STATE_PAUSED_STOPPING) {
442        mState = STATE_STOPPING;
443    } else {
444        mState = STATE_ACTIVE;
445    }
446    if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
447        // reset current position as seen by client to 0
448        mProxy->setEpoch(mProxy->getEpoch() - mProxy->getPosition());
449        // force refresh of remaining frames by processAudioBuffer() as last
450        // write before stop could be partial.
451        mRefreshRemaining = true;
452    }
453    mNewPosition = mProxy->getPosition() + mUpdatePeriod;
454    int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
455
456    sp<AudioTrackThread> t = mAudioTrackThread;
457    if (t != 0) {
458        if (previousState == STATE_STOPPING) {
459            mProxy->interrupt();
460        } else {
461            t->resume();
462        }
463    } else {
464        mPreviousPriority = getpriority(PRIO_PROCESS, 0);
465        get_sched_policy(0, &mPreviousSchedulingGroup);
466        androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
467    }
468
469    status_t status = NO_ERROR;
470    if (!(flags & CBLK_INVALID)) {
471        status = mAudioTrack->start();
472        if (status == DEAD_OBJECT) {
473            flags |= CBLK_INVALID;
474        }
475    }
476    if (flags & CBLK_INVALID) {
477        status = restoreTrack_l("start");
478    }
479
480    if (status != NO_ERROR) {
481        ALOGE("start() status %d", status);
482        mState = previousState;
483        if (t != 0) {
484            if (previousState != STATE_STOPPING) {
485                t->pause();
486            }
487        } else {
488            setpriority(PRIO_PROCESS, 0, mPreviousPriority);
489            set_sched_policy(0, mPreviousSchedulingGroup);
490        }
491    }
492
493    return status;
494}
495
496void AudioTrack::stop()
497{
498    AutoMutex lock(mLock);
499    if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
500        return;
501    }
502
503    if (isOffloaded_l()) {
504        mState = STATE_STOPPING;
505    } else {
506        mState = STATE_STOPPED;
507    }
508
509    mProxy->interrupt();
510    mAudioTrack->stop();
511    // the playback head position will reset to 0, so if a marker is set, we need
512    // to activate it again
513    mMarkerReached = false;
514#if 0
515    // Force flush if a shared buffer is used otherwise audioflinger
516    // will not stop before end of buffer is reached.
517    // It may be needed to make sure that we stop playback, likely in case looping is on.
518    if (mSharedBuffer != 0) {
519        flush_l();
520    }
521#endif
522
523    sp<AudioTrackThread> t = mAudioTrackThread;
524    if (t != 0) {
525        if (!isOffloaded_l()) {
526            t->pause();
527        }
528    } else {
529        setpriority(PRIO_PROCESS, 0, mPreviousPriority);
530        set_sched_policy(0, mPreviousSchedulingGroup);
531    }
532}
533
534bool AudioTrack::stopped() const
535{
536    AutoMutex lock(mLock);
537    return mState != STATE_ACTIVE;
538}
539
540void AudioTrack::flush()
541{
542    if (mSharedBuffer != 0) {
543        return;
544    }
545    AutoMutex lock(mLock);
546    if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
547        return;
548    }
549    flush_l();
550}
551
552void AudioTrack::flush_l()
553{
554    ALOG_ASSERT(mState != STATE_ACTIVE);
555
556    // clear playback marker and periodic update counter
557    mMarkerPosition = 0;
558    mMarkerReached = false;
559    mUpdatePeriod = 0;
560    mRefreshRemaining = true;
561
562    mState = STATE_FLUSHED;
563    if (isOffloaded_l()) {
564        mProxy->interrupt();
565    }
566    mProxy->flush();
567    mAudioTrack->flush();
568}
569
570void AudioTrack::pause()
571{
572    AutoMutex lock(mLock);
573    if (mState == STATE_ACTIVE) {
574        mState = STATE_PAUSED;
575    } else if (mState == STATE_STOPPING) {
576        mState = STATE_PAUSED_STOPPING;
577    } else {
578        return;
579    }
580    mProxy->interrupt();
581    mAudioTrack->pause();
582
583    if (isOffloaded_l()) {
584        if (mOutput != AUDIO_IO_HANDLE_NONE) {
585            uint32_t halFrames;
586            // OffloadThread sends HAL pause in its threadLoop.. time saved
587            // here can be slightly off
588            AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
589            ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
590        }
591    }
592}
593
594status_t AudioTrack::setVolume(float left, float right)
595{
596    // This duplicates a test by AudioTrack JNI, but that is not the only caller
597    if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
598            isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
599        return BAD_VALUE;
600    }
601
602    AutoMutex lock(mLock);
603    mVolume[AUDIO_INTERLEAVE_LEFT] = left;
604    mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
605
606    mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
607
608    if (isOffloaded_l()) {
609        mAudioTrack->signal();
610    }
611    return NO_ERROR;
612}
613
614status_t AudioTrack::setVolume(float volume)
615{
616    return setVolume(volume, volume);
617}
618
619status_t AudioTrack::setAuxEffectSendLevel(float level)
620{
621    // This duplicates a test by AudioTrack JNI, but that is not the only caller
622    if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
623        return BAD_VALUE;
624    }
625
626    AutoMutex lock(mLock);
627    mSendLevel = level;
628    mProxy->setSendLevel(level);
629
630    return NO_ERROR;
631}
632
633void AudioTrack::getAuxEffectSendLevel(float* level) const
634{
635    if (level != NULL) {
636        *level = mSendLevel;
637    }
638}
639
640status_t AudioTrack::setSampleRate(uint32_t rate)
641{
642    if (mIsTimed || isOffloadedOrDirect()) {
643        return INVALID_OPERATION;
644    }
645
646    uint32_t afSamplingRate;
647    if (AudioSystem::getOutputSamplingRateForAttr(&afSamplingRate, &mAttributes) != NO_ERROR) {
648        return NO_INIT;
649    }
650    if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
651        return BAD_VALUE;
652    }
653
654    AutoMutex lock(mLock);
655    mSampleRate = rate;
656    mProxy->setSampleRate(rate);
657
658    return NO_ERROR;
659}
660
661uint32_t AudioTrack::getSampleRate() const
662{
663    if (mIsTimed) {
664        return 0;
665    }
666
667    AutoMutex lock(mLock);
668
669    // sample rate can be updated during playback by the offloaded decoder so we need to
670    // query the HAL and update if needed.
671// FIXME use Proxy return channel to update the rate from server and avoid polling here
672    if (isOffloadedOrDirect_l()) {
673        if (mOutput != AUDIO_IO_HANDLE_NONE) {
674            uint32_t sampleRate = 0;
675            status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
676            if (status == NO_ERROR) {
677                mSampleRate = sampleRate;
678            }
679        }
680    }
681    return mSampleRate;
682}
683
684status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
685{
686    if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
687        return INVALID_OPERATION;
688    }
689
690    if (loopCount == 0) {
691        ;
692    } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
693            loopEnd - loopStart >= MIN_LOOP) {
694        ;
695    } else {
696        return BAD_VALUE;
697    }
698
699    AutoMutex lock(mLock);
700    // See setPosition() regarding setting parameters such as loop points or position while active
701    if (mState == STATE_ACTIVE) {
702        return INVALID_OPERATION;
703    }
704    setLoop_l(loopStart, loopEnd, loopCount);
705    return NO_ERROR;
706}
707
708void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
709{
710    // FIXME If setting a loop also sets position to start of loop, then
711    //       this is correct.  Otherwise it should be removed.
712    mNewPosition = mProxy->getPosition() + mUpdatePeriod;
713    mLoopPeriod = loopCount != 0 ? loopEnd - loopStart : 0;
714    mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
715}
716
717status_t AudioTrack::setMarkerPosition(uint32_t marker)
718{
719    // The only purpose of setting marker position is to get a callback
720    if (mCbf == NULL || isOffloadedOrDirect()) {
721        return INVALID_OPERATION;
722    }
723
724    AutoMutex lock(mLock);
725    mMarkerPosition = marker;
726    mMarkerReached = false;
727
728    return NO_ERROR;
729}
730
731status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
732{
733    if (isOffloadedOrDirect()) {
734        return INVALID_OPERATION;
735    }
736    if (marker == NULL) {
737        return BAD_VALUE;
738    }
739
740    AutoMutex lock(mLock);
741    *marker = mMarkerPosition;
742
743    return NO_ERROR;
744}
745
746status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
747{
748    // The only purpose of setting position update period is to get a callback
749    if (mCbf == NULL || isOffloadedOrDirect()) {
750        return INVALID_OPERATION;
751    }
752
753    AutoMutex lock(mLock);
754    mNewPosition = mProxy->getPosition() + updatePeriod;
755    mUpdatePeriod = updatePeriod;
756
757    return NO_ERROR;
758}
759
760status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
761{
762    if (isOffloadedOrDirect()) {
763        return INVALID_OPERATION;
764    }
765    if (updatePeriod == NULL) {
766        return BAD_VALUE;
767    }
768
769    AutoMutex lock(mLock);
770    *updatePeriod = mUpdatePeriod;
771
772    return NO_ERROR;
773}
774
775status_t AudioTrack::setPosition(uint32_t position)
776{
777    if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
778        return INVALID_OPERATION;
779    }
780    if (position > mFrameCount) {
781        return BAD_VALUE;
782    }
783
784    AutoMutex lock(mLock);
785    // Currently we require that the player is inactive before setting parameters such as position
786    // or loop points.  Otherwise, there could be a race condition: the application could read the
787    // current position, compute a new position or loop parameters, and then set that position or
788    // loop parameters but it would do the "wrong" thing since the position has continued to advance
789    // in the mean time.  If we ever provide a sequencer in server, we could allow a way for the app
790    // to specify how it wants to handle such scenarios.
791    if (mState == STATE_ACTIVE) {
792        return INVALID_OPERATION;
793    }
794    mNewPosition = mProxy->getPosition() + mUpdatePeriod;
795    mLoopPeriod = 0;
796    // FIXME Check whether loops and setting position are incompatible in old code.
797    // If we use setLoop for both purposes we lose the capability to set the position while looping.
798    mStaticProxy->setLoop(position, mFrameCount, 0);
799
800    return NO_ERROR;
801}
802
803status_t AudioTrack::getPosition(uint32_t *position) const
804{
805    if (position == NULL) {
806        return BAD_VALUE;
807    }
808
809    AutoMutex lock(mLock);
810    if (isOffloadedOrDirect_l()) {
811        uint32_t dspFrames = 0;
812
813        if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
814            ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
815            *position = mPausedPosition;
816            return NO_ERROR;
817        }
818
819        if (mOutput != AUDIO_IO_HANDLE_NONE) {
820            uint32_t halFrames;
821            AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
822        }
823        *position = dspFrames;
824    } else {
825        // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
826        *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ? 0 :
827                mProxy->getPosition();
828    }
829    return NO_ERROR;
830}
831
832status_t AudioTrack::getBufferPosition(uint32_t *position)
833{
834    if (mSharedBuffer == 0 || mIsTimed) {
835        return INVALID_OPERATION;
836    }
837    if (position == NULL) {
838        return BAD_VALUE;
839    }
840
841    AutoMutex lock(mLock);
842    *position = mStaticProxy->getBufferPosition();
843    return NO_ERROR;
844}
845
846status_t AudioTrack::reload()
847{
848    if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
849        return INVALID_OPERATION;
850    }
851
852    AutoMutex lock(mLock);
853    // See setPosition() regarding setting parameters such as loop points or position while active
854    if (mState == STATE_ACTIVE) {
855        return INVALID_OPERATION;
856    }
857    mNewPosition = mUpdatePeriod;
858    mLoopPeriod = 0;
859    // FIXME The new code cannot reload while keeping a loop specified.
860    // Need to check how the old code handled this, and whether it's a significant change.
861    mStaticProxy->setLoop(0, mFrameCount, 0);
862    return NO_ERROR;
863}
864
865audio_io_handle_t AudioTrack::getOutput() const
866{
867    AutoMutex lock(mLock);
868    return mOutput;
869}
870
871status_t AudioTrack::attachAuxEffect(int effectId)
872{
873    AutoMutex lock(mLock);
874    status_t status = mAudioTrack->attachAuxEffect(effectId);
875    if (status == NO_ERROR) {
876        mAuxEffectId = effectId;
877    }
878    return status;
879}
880
881// -------------------------------------------------------------------------
882
883// must be called with mLock held
884status_t AudioTrack::createTrack_l(size_t epoch)
885{
886    status_t status;
887    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
888    if (audioFlinger == 0) {
889        ALOGE("Could not get audioflinger");
890        return NO_INIT;
891    }
892
893    audio_io_handle_t output = AudioSystem::getOutputForAttr(&mAttributes, mSampleRate, mFormat,
894            mChannelMask, mFlags, mOffloadInfo);
895    if (output == AUDIO_IO_HANDLE_NONE) {
896        ALOGE("Could not get audio output for stream type %d, usage %d, sample rate %u, format %#x,"
897              " channel mask %#x, flags %#x",
898              mStreamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
899        return BAD_VALUE;
900    }
901    {
902    // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
903    // we must release it ourselves if anything goes wrong.
904
905    // Not all of these values are needed under all conditions, but it is easier to get them all
906
907    uint32_t afLatency;
908    status = AudioSystem::getLatency(output, &afLatency);
909    if (status != NO_ERROR) {
910        ALOGE("getLatency(%d) failed status %d", output, status);
911        goto release;
912    }
913
914    size_t afFrameCount;
915    status = AudioSystem::getFrameCount(output, &afFrameCount);
916    if (status != NO_ERROR) {
917        ALOGE("getFrameCount(output=%d) status %d", output, status);
918        goto release;
919    }
920
921    uint32_t afSampleRate;
922    status = AudioSystem::getSamplingRate(output, &afSampleRate);
923    if (status != NO_ERROR) {
924        ALOGE("getSamplingRate(output=%d) status %d", output, status);
925        goto release;
926    }
927
928    // Client decides whether the track is TIMED (see below), but can only express a preference
929    // for FAST.  Server will perform additional tests.
930    if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
931            // either of these use cases:
932            // use case 1: shared buffer
933            (mSharedBuffer != 0) ||
934            // use case 2: callback transfer mode
935            (mTransfer == TRANSFER_CALLBACK)) &&
936            // matching sample rate
937            (mSampleRate == afSampleRate))) {
938        ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
939        // once denied, do not request again if IAudioTrack is re-created
940        mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
941    }
942    ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
943
944    // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
945    //  n = 1   fast track with single buffering; nBuffering is ignored
946    //  n = 2   fast track with double buffering
947    //  n = 2   normal track, no sample rate conversion
948    //  n = 3   normal track, with sample rate conversion
949    //          (pessimistic; some non-1:1 conversion ratios don't actually need triple-buffering)
950    //  n > 3   very high latency or very small notification interval; nBuffering is ignored
951    const uint32_t nBuffering = (mSampleRate == afSampleRate) ? 2 : 3;
952
953    mNotificationFramesAct = mNotificationFramesReq;
954
955    size_t frameCount = mReqFrameCount;
956    if (!audio_is_linear_pcm(mFormat)) {
957
958        if (mSharedBuffer != 0) {
959            // Same comment as below about ignoring frameCount parameter for set()
960            frameCount = mSharedBuffer->size();
961        } else if (frameCount == 0) {
962            frameCount = afFrameCount;
963        }
964        if (mNotificationFramesAct != frameCount) {
965            mNotificationFramesAct = frameCount;
966        }
967    } else if (mSharedBuffer != 0) {
968
969        // Ensure that buffer alignment matches channel count
970        // 8-bit data in shared memory is not currently supported by AudioFlinger
971        size_t alignment = audio_bytes_per_sample(
972                mFormat == AUDIO_FORMAT_PCM_8_BIT ? AUDIO_FORMAT_PCM_16_BIT : mFormat);
973        if (alignment & 1) {
974            alignment = 1;
975        }
976        if (mChannelCount > 1) {
977            // More than 2 channels does not require stronger alignment than stereo
978            alignment <<= 1;
979        }
980        if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
981            ALOGE("Invalid buffer alignment: address %p, channel count %u",
982                    mSharedBuffer->pointer(), mChannelCount);
983            status = BAD_VALUE;
984            goto release;
985        }
986
987        // When initializing a shared buffer AudioTrack via constructors,
988        // there's no frameCount parameter.
989        // But when initializing a shared buffer AudioTrack via set(),
990        // there _is_ a frameCount parameter.  We silently ignore it.
991        frameCount = mSharedBuffer->size() / mFrameSizeAF;
992
993    } else if (!(mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
994
995        // FIXME move these calculations and associated checks to server
996
997        // Ensure that buffer depth covers at least audio hardware latency
998        uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
999        ALOGV("afFrameCount=%zu, minBufCount=%d, afSampleRate=%u, afLatency=%d",
1000                afFrameCount, minBufCount, afSampleRate, afLatency);
1001        if (minBufCount <= nBuffering) {
1002            minBufCount = nBuffering;
1003        }
1004
1005        size_t minFrameCount = afFrameCount * minBufCount * uint64_t(mSampleRate) / afSampleRate;
1006        ALOGV("minFrameCount: %zu, afFrameCount=%zu, minBufCount=%d, sampleRate=%u, afSampleRate=%u"
1007                ", afLatency=%d",
1008                minFrameCount, afFrameCount, minBufCount, mSampleRate, afSampleRate, afLatency);
1009
1010        if (frameCount == 0) {
1011            frameCount = minFrameCount;
1012        } else if (frameCount < minFrameCount) {
1013            // not ALOGW because it happens all the time when playing key clicks over A2DP
1014            ALOGV("Minimum buffer size corrected from %zu to %zu",
1015                     frameCount, minFrameCount);
1016            frameCount = minFrameCount;
1017        }
1018        // Make sure that application is notified with sufficient margin before underrun
1019        if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1020            mNotificationFramesAct = frameCount/nBuffering;
1021        }
1022
1023    } else {
1024        // For fast tracks, the frame count calculations and checks are done by server
1025    }
1026
1027    IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1028    if (mIsTimed) {
1029        trackFlags |= IAudioFlinger::TRACK_TIMED;
1030    }
1031
1032    pid_t tid = -1;
1033    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1034        trackFlags |= IAudioFlinger::TRACK_FAST;
1035        if (mAudioTrackThread != 0) {
1036            tid = mAudioTrackThread->getTid();
1037        }
1038    }
1039
1040    if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1041        trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1042    }
1043
1044    if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1045        trackFlags |= IAudioFlinger::TRACK_DIRECT;
1046    }
1047
1048    size_t temp = frameCount;   // temp may be replaced by a revised value of frameCount,
1049                                // but we will still need the original value also
1050    sp<IAudioTrack> track = audioFlinger->createTrack(mStreamType,
1051                                                      mSampleRate,
1052                                                      // AudioFlinger only sees 16-bit PCM
1053                                                      mFormat == AUDIO_FORMAT_PCM_8_BIT &&
1054                                                          !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ?
1055                                                              AUDIO_FORMAT_PCM_16_BIT : mFormat,
1056                                                      mChannelMask,
1057                                                      &temp,
1058                                                      &trackFlags,
1059                                                      mSharedBuffer,
1060                                                      output,
1061                                                      tid,
1062                                                      &mSessionId,
1063                                                      mClientUid,
1064                                                      &status);
1065
1066    if (status != NO_ERROR) {
1067        ALOGE("AudioFlinger could not create track, status: %d", status);
1068        goto release;
1069    }
1070    ALOG_ASSERT(track != 0);
1071
1072    // AudioFlinger now owns the reference to the I/O handle,
1073    // so we are no longer responsible for releasing it.
1074
1075    sp<IMemory> iMem = track->getCblk();
1076    if (iMem == 0) {
1077        ALOGE("Could not get control block");
1078        return NO_INIT;
1079    }
1080    void *iMemPointer = iMem->pointer();
1081    if (iMemPointer == NULL) {
1082        ALOGE("Could not get control block pointer");
1083        return NO_INIT;
1084    }
1085    // invariant that mAudioTrack != 0 is true only after set() returns successfully
1086    if (mAudioTrack != 0) {
1087        mAudioTrack->asBinder()->unlinkToDeath(mDeathNotifier, this);
1088        mDeathNotifier.clear();
1089    }
1090    mAudioTrack = track;
1091    mCblkMemory = iMem;
1092    IPCThreadState::self()->flushCommands();
1093
1094    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
1095    mCblk = cblk;
1096    // note that temp is the (possibly revised) value of frameCount
1097    if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1098        // In current design, AudioTrack client checks and ensures frame count validity before
1099        // passing it to AudioFlinger so AudioFlinger should not return a different value except
1100        // for fast track as it uses a special method of assigning frame count.
1101        ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
1102    }
1103    frameCount = temp;
1104
1105    mAwaitBoost = false;
1106    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1107        if (trackFlags & IAudioFlinger::TRACK_FAST) {
1108            ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
1109            mAwaitBoost = true;
1110            if (mSharedBuffer == 0) {
1111                // Theoretically double-buffering is not required for fast tracks,
1112                // due to tighter scheduling.  But in practice, to accommodate kernels with
1113                // scheduling jitter, and apps with computation jitter, we use double-buffering.
1114                if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1115                    mNotificationFramesAct = frameCount/nBuffering;
1116                }
1117            }
1118        } else {
1119            ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
1120            // once denied, do not request again if IAudioTrack is re-created
1121            mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1122            if (mSharedBuffer == 0) {
1123                if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount/nBuffering) {
1124                    mNotificationFramesAct = frameCount/nBuffering;
1125                }
1126            }
1127        }
1128    }
1129    if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1130        if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1131            ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1132        } else {
1133            ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
1134            mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1135            // FIXME This is a warning, not an error, so don't return error status
1136            //return NO_INIT;
1137        }
1138    }
1139    if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1140        if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1141            ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1142        } else {
1143            ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1144            mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1145            // FIXME This is a warning, not an error, so don't return error status
1146            //return NO_INIT;
1147        }
1148    }
1149
1150    // We retain a copy of the I/O handle, but don't own the reference
1151    mOutput = output;
1152    mRefreshRemaining = true;
1153
1154    // Starting address of buffers in shared memory.  If there is a shared buffer, buffers
1155    // is the value of pointer() for the shared buffer, otherwise buffers points
1156    // immediately after the control block.  This address is for the mapping within client
1157    // address space.  AudioFlinger::TrackBase::mBuffer is for the server address space.
1158    void* buffers;
1159    if (mSharedBuffer == 0) {
1160        buffers = (char*)cblk + sizeof(audio_track_cblk_t);
1161    } else {
1162        buffers = mSharedBuffer->pointer();
1163    }
1164
1165    mAudioTrack->attachAuxEffect(mAuxEffectId);
1166    // FIXME don't believe this lie
1167    mLatency = afLatency + (1000*frameCount) / mSampleRate;
1168
1169    mFrameCount = frameCount;
1170    // If IAudioTrack is re-created, don't let the requested frameCount
1171    // decrease.  This can confuse clients that cache frameCount().
1172    if (frameCount > mReqFrameCount) {
1173        mReqFrameCount = frameCount;
1174    }
1175
1176    // update proxy
1177    if (mSharedBuffer == 0) {
1178        mStaticProxy.clear();
1179        mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1180    } else {
1181        mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSizeAF);
1182        mProxy = mStaticProxy;
1183    }
1184    mProxy->setVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY);
1185    mProxy->setSendLevel(mSendLevel);
1186    mProxy->setSampleRate(mSampleRate);
1187    mProxy->setEpoch(epoch);
1188    mProxy->setMinimum(mNotificationFramesAct);
1189
1190    mDeathNotifier = new DeathNotifier(this);
1191    mAudioTrack->asBinder()->linkToDeath(mDeathNotifier, this);
1192
1193    return NO_ERROR;
1194    }
1195
1196release:
1197    AudioSystem::releaseOutput(output);
1198    if (status == NO_ERROR) {
1199        status = NO_INIT;
1200    }
1201    return status;
1202}
1203
1204status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
1205{
1206    if (audioBuffer == NULL) {
1207        return BAD_VALUE;
1208    }
1209    if (mTransfer != TRANSFER_OBTAIN) {
1210        audioBuffer->frameCount = 0;
1211        audioBuffer->size = 0;
1212        audioBuffer->raw = NULL;
1213        return INVALID_OPERATION;
1214    }
1215
1216    const struct timespec *requested;
1217    struct timespec timeout;
1218    if (waitCount == -1) {
1219        requested = &ClientProxy::kForever;
1220    } else if (waitCount == 0) {
1221        requested = &ClientProxy::kNonBlocking;
1222    } else if (waitCount > 0) {
1223        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1224        timeout.tv_sec = ms / 1000;
1225        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1226        requested = &timeout;
1227    } else {
1228        ALOGE("%s invalid waitCount %d", __func__, waitCount);
1229        requested = NULL;
1230    }
1231    return obtainBuffer(audioBuffer, requested);
1232}
1233
1234status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1235        struct timespec *elapsed, size_t *nonContig)
1236{
1237    // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1238    uint32_t oldSequence = 0;
1239    uint32_t newSequence;
1240
1241    Proxy::Buffer buffer;
1242    status_t status = NO_ERROR;
1243
1244    static const int32_t kMaxTries = 5;
1245    int32_t tryCounter = kMaxTries;
1246
1247    do {
1248        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1249        // keep them from going away if another thread re-creates the track during obtainBuffer()
1250        sp<AudioTrackClientProxy> proxy;
1251        sp<IMemory> iMem;
1252
1253        {   // start of lock scope
1254            AutoMutex lock(mLock);
1255
1256            newSequence = mSequence;
1257            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1258            if (status == DEAD_OBJECT) {
1259                // re-create track, unless someone else has already done so
1260                if (newSequence == oldSequence) {
1261                    status = restoreTrack_l("obtainBuffer");
1262                    if (status != NO_ERROR) {
1263                        buffer.mFrameCount = 0;
1264                        buffer.mRaw = NULL;
1265                        buffer.mNonContig = 0;
1266                        break;
1267                    }
1268                }
1269            }
1270            oldSequence = newSequence;
1271
1272            // Keep the extra references
1273            proxy = mProxy;
1274            iMem = mCblkMemory;
1275
1276            if (mState == STATE_STOPPING) {
1277                status = -EINTR;
1278                buffer.mFrameCount = 0;
1279                buffer.mRaw = NULL;
1280                buffer.mNonContig = 0;
1281                break;
1282            }
1283
1284            // Non-blocking if track is stopped or paused
1285            if (mState != STATE_ACTIVE) {
1286                requested = &ClientProxy::kNonBlocking;
1287            }
1288
1289        }   // end of lock scope
1290
1291        buffer.mFrameCount = audioBuffer->frameCount;
1292        // FIXME starts the requested timeout and elapsed over from scratch
1293        status = proxy->obtainBuffer(&buffer, requested, elapsed);
1294
1295    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1296
1297    audioBuffer->frameCount = buffer.mFrameCount;
1298    audioBuffer->size = buffer.mFrameCount * mFrameSizeAF;
1299    audioBuffer->raw = buffer.mRaw;
1300    if (nonContig != NULL) {
1301        *nonContig = buffer.mNonContig;
1302    }
1303    return status;
1304}
1305
1306void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1307{
1308    if (mTransfer == TRANSFER_SHARED) {
1309        return;
1310    }
1311
1312    size_t stepCount = audioBuffer->size / mFrameSizeAF;
1313    if (stepCount == 0) {
1314        return;
1315    }
1316
1317    Proxy::Buffer buffer;
1318    buffer.mFrameCount = stepCount;
1319    buffer.mRaw = audioBuffer->raw;
1320
1321    AutoMutex lock(mLock);
1322    mInUnderrun = false;
1323    mProxy->releaseBuffer(&buffer);
1324
1325    // restart track if it was disabled by audioflinger due to previous underrun
1326    if (mState == STATE_ACTIVE) {
1327        audio_track_cblk_t* cblk = mCblk;
1328        if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
1329            ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
1330            // FIXME ignoring status
1331            mAudioTrack->start();
1332        }
1333    }
1334}
1335
1336// -------------------------------------------------------------------------
1337
1338ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
1339{
1340    if (mTransfer != TRANSFER_SYNC || mIsTimed) {
1341        return INVALID_OPERATION;
1342    }
1343
1344    if (isDirect()) {
1345        AutoMutex lock(mLock);
1346        int32_t flags = android_atomic_and(
1347                            ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1348                            &mCblk->mFlags);
1349        if (flags & CBLK_INVALID) {
1350            return DEAD_OBJECT;
1351        }
1352    }
1353
1354    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
1355        // Sanity-check: user is most-likely passing an error code, and it would
1356        // make the return value ambiguous (actualSize vs error).
1357        ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
1358        return BAD_VALUE;
1359    }
1360
1361    size_t written = 0;
1362    Buffer audioBuffer;
1363
1364    while (userSize >= mFrameSize) {
1365        audioBuffer.frameCount = userSize / mFrameSize;
1366
1367        status_t err = obtainBuffer(&audioBuffer,
1368                blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
1369        if (err < 0) {
1370            if (written > 0) {
1371                break;
1372            }
1373            return ssize_t(err);
1374        }
1375
1376        size_t toWrite;
1377        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1378            // Divide capacity by 2 to take expansion into account
1379            toWrite = audioBuffer.size >> 1;
1380            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
1381        } else {
1382            toWrite = audioBuffer.size;
1383            memcpy(audioBuffer.i8, buffer, toWrite);
1384        }
1385        buffer = ((const char *) buffer) + toWrite;
1386        userSize -= toWrite;
1387        written += toWrite;
1388
1389        releaseBuffer(&audioBuffer);
1390    }
1391
1392    return written;
1393}
1394
1395// -------------------------------------------------------------------------
1396
1397TimedAudioTrack::TimedAudioTrack() {
1398    mIsTimed = true;
1399}
1400
1401status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1402{
1403    AutoMutex lock(mLock);
1404    status_t result = UNKNOWN_ERROR;
1405
1406#if 1
1407    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1408    // while we are accessing the cblk
1409    sp<IAudioTrack> audioTrack = mAudioTrack;
1410    sp<IMemory> iMem = mCblkMemory;
1411#endif
1412
1413    // If the track is not invalid already, try to allocate a buffer.  alloc
1414    // fails indicating that the server is dead, flag the track as invalid so
1415    // we can attempt to restore in just a bit.
1416    audio_track_cblk_t* cblk = mCblk;
1417    if (!(cblk->mFlags & CBLK_INVALID)) {
1418        result = mAudioTrack->allocateTimedBuffer(size, buffer);
1419        if (result == DEAD_OBJECT) {
1420            android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1421        }
1422    }
1423
1424    // If the track is invalid at this point, attempt to restore it. and try the
1425    // allocation one more time.
1426    if (cblk->mFlags & CBLK_INVALID) {
1427        result = restoreTrack_l("allocateTimedBuffer");
1428
1429        if (result == NO_ERROR) {
1430            result = mAudioTrack->allocateTimedBuffer(size, buffer);
1431        }
1432    }
1433
1434    return result;
1435}
1436
1437status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1438                                           int64_t pts)
1439{
1440    status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1441    {
1442        AutoMutex lock(mLock);
1443        audio_track_cblk_t* cblk = mCblk;
1444        // restart track if it was disabled by audioflinger due to previous underrun
1445        if (buffer->size() != 0 && status == NO_ERROR &&
1446                (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1447            android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
1448            ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
1449            // FIXME ignoring status
1450            mAudioTrack->start();
1451        }
1452    }
1453    return status;
1454}
1455
1456status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1457                                                TargetTimeline target)
1458{
1459    return mAudioTrack->setMediaTimeTransform(xform, target);
1460}
1461
1462// -------------------------------------------------------------------------
1463
1464nsecs_t AudioTrack::processAudioBuffer()
1465{
1466    // Currently the AudioTrack thread is not created if there are no callbacks.
1467    // Would it ever make sense to run the thread, even without callbacks?
1468    // If so, then replace this by checks at each use for mCbf != NULL.
1469    LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1470
1471    mLock.lock();
1472    if (mAwaitBoost) {
1473        mAwaitBoost = false;
1474        mLock.unlock();
1475        static const int32_t kMaxTries = 5;
1476        int32_t tryCounter = kMaxTries;
1477        uint32_t pollUs = 10000;
1478        do {
1479            int policy = sched_getscheduler(0);
1480            if (policy == SCHED_FIFO || policy == SCHED_RR) {
1481                break;
1482            }
1483            usleep(pollUs);
1484            pollUs <<= 1;
1485        } while (tryCounter-- > 0);
1486        if (tryCounter < 0) {
1487            ALOGE("did not receive expected priority boost on time");
1488        }
1489        // Run again immediately
1490        return 0;
1491    }
1492
1493    // Can only reference mCblk while locked
1494    int32_t flags = android_atomic_and(
1495        ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
1496
1497    // Check for track invalidation
1498    if (flags & CBLK_INVALID) {
1499        // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1500        // AudioSystem cache. We should not exit here but after calling the callback so
1501        // that the upper layers can recreate the track
1502        if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
1503            status_t status = restoreTrack_l("processAudioBuffer");
1504            mLock.unlock();
1505            // Run again immediately, but with a new IAudioTrack
1506            return 0;
1507        }
1508    }
1509
1510    bool waitStreamEnd = mState == STATE_STOPPING;
1511    bool active = mState == STATE_ACTIVE;
1512
1513    // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1514    bool newUnderrun = false;
1515    if (flags & CBLK_UNDERRUN) {
1516#if 0
1517        // Currently in shared buffer mode, when the server reaches the end of buffer,
1518        // the track stays active in continuous underrun state.  It's up to the application
1519        // to pause or stop the track, or set the position to a new offset within buffer.
1520        // This was some experimental code to auto-pause on underrun.   Keeping it here
1521        // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1522        if (mTransfer == TRANSFER_SHARED) {
1523            mState = STATE_PAUSED;
1524            active = false;
1525        }
1526#endif
1527        if (!mInUnderrun) {
1528            mInUnderrun = true;
1529            newUnderrun = true;
1530        }
1531    }
1532
1533    // Get current position of server
1534    size_t position = mProxy->getPosition();
1535
1536    // Manage marker callback
1537    bool markerReached = false;
1538    size_t markerPosition = mMarkerPosition;
1539    // FIXME fails for wraparound, need 64 bits
1540    if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1541        mMarkerReached = markerReached = true;
1542    }
1543
1544    // Determine number of new position callback(s) that will be needed, while locked
1545    size_t newPosCount = 0;
1546    size_t newPosition = mNewPosition;
1547    size_t updatePeriod = mUpdatePeriod;
1548    // FIXME fails for wraparound, need 64 bits
1549    if (updatePeriod > 0 && position >= newPosition) {
1550        newPosCount = ((position - newPosition) / updatePeriod) + 1;
1551        mNewPosition += updatePeriod * newPosCount;
1552    }
1553
1554    // Cache other fields that will be needed soon
1555    uint32_t loopPeriod = mLoopPeriod;
1556    uint32_t sampleRate = mSampleRate;
1557    uint32_t notificationFrames = mNotificationFramesAct;
1558    if (mRefreshRemaining) {
1559        mRefreshRemaining = false;
1560        mRemainingFrames = notificationFrames;
1561        mRetryOnPartialBuffer = false;
1562    }
1563    size_t misalignment = mProxy->getMisalignment();
1564    uint32_t sequence = mSequence;
1565    sp<AudioTrackClientProxy> proxy = mProxy;
1566
1567    // These fields don't need to be cached, because they are assigned only by set():
1568    //     mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1569    // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1570
1571    mLock.unlock();
1572
1573    if (waitStreamEnd) {
1574        struct timespec timeout;
1575        timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1576        timeout.tv_nsec = 0;
1577
1578        status_t status = proxy->waitStreamEndDone(&timeout);
1579        switch (status) {
1580        case NO_ERROR:
1581        case DEAD_OBJECT:
1582        case TIMED_OUT:
1583            mCbf(EVENT_STREAM_END, mUserData, NULL);
1584            {
1585                AutoMutex lock(mLock);
1586                // The previously assigned value of waitStreamEnd is no longer valid,
1587                // since the mutex has been unlocked and either the callback handler
1588                // or another thread could have re-started the AudioTrack during that time.
1589                waitStreamEnd = mState == STATE_STOPPING;
1590                if (waitStreamEnd) {
1591                    mState = STATE_STOPPED;
1592                }
1593            }
1594            if (waitStreamEnd && status != DEAD_OBJECT) {
1595               return NS_INACTIVE;
1596            }
1597            break;
1598        }
1599        return 0;
1600    }
1601
1602    // perform callbacks while unlocked
1603    if (newUnderrun) {
1604        mCbf(EVENT_UNDERRUN, mUserData, NULL);
1605    }
1606    // FIXME we will miss loops if loop cycle was signaled several times since last call
1607    //       to processAudioBuffer()
1608    if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1609        mCbf(EVENT_LOOP_END, mUserData, NULL);
1610    }
1611    if (flags & CBLK_BUFFER_END) {
1612        mCbf(EVENT_BUFFER_END, mUserData, NULL);
1613    }
1614    if (markerReached) {
1615        mCbf(EVENT_MARKER, mUserData, &markerPosition);
1616    }
1617    while (newPosCount > 0) {
1618        size_t temp = newPosition;
1619        mCbf(EVENT_NEW_POS, mUserData, &temp);
1620        newPosition += updatePeriod;
1621        newPosCount--;
1622    }
1623
1624    if (mObservedSequence != sequence) {
1625        mObservedSequence = sequence;
1626        mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
1627        // for offloaded tracks, just wait for the upper layers to recreate the track
1628        if (isOffloadedOrDirect()) {
1629            return NS_INACTIVE;
1630        }
1631    }
1632
1633    // if inactive, then don't run me again until re-started
1634    if (!active) {
1635        return NS_INACTIVE;
1636    }
1637
1638    // Compute the estimated time until the next timed event (position, markers, loops)
1639    // FIXME only for non-compressed audio
1640    uint32_t minFrames = ~0;
1641    if (!markerReached && position < markerPosition) {
1642        minFrames = markerPosition - position;
1643    }
1644    if (loopPeriod > 0 && loopPeriod < minFrames) {
1645        minFrames = loopPeriod;
1646    }
1647    if (updatePeriod > 0 && updatePeriod < minFrames) {
1648        minFrames = updatePeriod;
1649    }
1650
1651    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
1652    static const uint32_t kPoll = 0;
1653    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1654        minFrames = kPoll * notificationFrames;
1655    }
1656
1657    // Convert frame units to time units
1658    nsecs_t ns = NS_WHENEVER;
1659    if (minFrames != (uint32_t) ~0) {
1660        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1661        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1662        ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1663    }
1664
1665    // If not supplying data by EVENT_MORE_DATA, then we're done
1666    if (mTransfer != TRANSFER_CALLBACK) {
1667        return ns;
1668    }
1669
1670    struct timespec timeout;
1671    const struct timespec *requested = &ClientProxy::kForever;
1672    if (ns != NS_WHENEVER) {
1673        timeout.tv_sec = ns / 1000000000LL;
1674        timeout.tv_nsec = ns % 1000000000LL;
1675        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1676        requested = &timeout;
1677    }
1678
1679    while (mRemainingFrames > 0) {
1680
1681        Buffer audioBuffer;
1682        audioBuffer.frameCount = mRemainingFrames;
1683        size_t nonContig;
1684        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1685        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1686                "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
1687        requested = &ClientProxy::kNonBlocking;
1688        size_t avail = audioBuffer.frameCount + nonContig;
1689        ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
1690                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
1691        if (err != NO_ERROR) {
1692            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1693                    (isOffloaded() && (err == DEAD_OBJECT))) {
1694                return 0;
1695            }
1696            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1697            return NS_NEVER;
1698        }
1699
1700        if (mRetryOnPartialBuffer && !isOffloaded()) {
1701            mRetryOnPartialBuffer = false;
1702            if (avail < mRemainingFrames) {
1703                int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1704                if (ns < 0 || myns < ns) {
1705                    ns = myns;
1706                }
1707                return ns;
1708            }
1709        }
1710
1711        // Divide buffer size by 2 to take into account the expansion
1712        // due to 8 to 16 bit conversion: the callback must fill only half
1713        // of the destination buffer
1714        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1715            audioBuffer.size >>= 1;
1716        }
1717
1718        size_t reqSize = audioBuffer.size;
1719        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1720        size_t writtenSize = audioBuffer.size;
1721
1722        // Sanity check on returned size
1723        if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1724            ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1725                    reqSize, ssize_t(writtenSize));
1726            return NS_NEVER;
1727        }
1728
1729        if (writtenSize == 0) {
1730            // The callback is done filling buffers
1731            // Keep this thread going to handle timed events and
1732            // still try to get more data in intervals of WAIT_PERIOD_MS
1733            // but don't just loop and block the CPU, so wait
1734            return WAIT_PERIOD_MS * 1000000LL;
1735        }
1736
1737        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1738            // 8 to 16 bit conversion, note that source and destination are the same address
1739            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
1740            audioBuffer.size <<= 1;
1741        }
1742
1743        size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1744        audioBuffer.frameCount = releasedFrames;
1745        mRemainingFrames -= releasedFrames;
1746        if (misalignment >= releasedFrames) {
1747            misalignment -= releasedFrames;
1748        } else {
1749            misalignment = 0;
1750        }
1751
1752        releaseBuffer(&audioBuffer);
1753
1754        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1755        // if callback doesn't like to accept the full chunk
1756        if (writtenSize < reqSize) {
1757            continue;
1758        }
1759
1760        // There could be enough non-contiguous frames available to satisfy the remaining request
1761        if (mRemainingFrames <= nonContig) {
1762            continue;
1763        }
1764
1765#if 0
1766        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1767        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
1768        // that total to a sum == notificationFrames.
1769        if (0 < misalignment && misalignment <= mRemainingFrames) {
1770            mRemainingFrames = misalignment;
1771            return (mRemainingFrames * 1100000000LL) / sampleRate;
1772        }
1773#endif
1774
1775    }
1776    mRemainingFrames = notificationFrames;
1777    mRetryOnPartialBuffer = true;
1778
1779    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1780    return 0;
1781}
1782
1783status_t AudioTrack::restoreTrack_l(const char *from)
1784{
1785    ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
1786          isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
1787    ++mSequence;
1788    status_t result;
1789
1790    // refresh the audio configuration cache in this process to make sure we get new
1791    // output parameters in createTrack_l()
1792    AudioSystem::clearAudioConfigCache();
1793
1794    if (isOffloadedOrDirect_l()) {
1795        // FIXME re-creation of offloaded tracks is not yet implemented
1796        return DEAD_OBJECT;
1797    }
1798
1799    // if the new IAudioTrack is created, createTrack_l() will modify the
1800    // following member variables: mAudioTrack, mCblkMemory and mCblk.
1801    // It will also delete the strong references on previous IAudioTrack and IMemory
1802
1803    // take the frames that will be lost by track recreation into account in saved position
1804    size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
1805    size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
1806    result = createTrack_l(position /*epoch*/);
1807
1808    if (result == NO_ERROR) {
1809        // continue playback from last known position, but
1810        // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1811        if (mStaticProxy != NULL) {
1812            mLoopPeriod = 0;
1813            mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1814        }
1815        // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1816        //       track destruction have been played? This is critical for SoundPool implementation
1817        //       This must be broken, and needs to be tested/debugged.
1818#if 0
1819        // restore write index and set other indexes to reflect empty buffer status
1820        if (!strcmp(from, "start")) {
1821            // Make sure that a client relying on callback events indicating underrun or
1822            // the actual amount of audio frames played (e.g SoundPool) receives them.
1823            if (mSharedBuffer == 0) {
1824                // restart playback even if buffer is not completely filled.
1825                android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1826            }
1827        }
1828#endif
1829        if (mState == STATE_ACTIVE) {
1830            result = mAudioTrack->start();
1831        }
1832    }
1833    if (result != NO_ERROR) {
1834        ALOGW("restoreTrack_l() failed status %d", result);
1835        mState = STATE_STOPPED;
1836    }
1837
1838    return result;
1839}
1840
1841status_t AudioTrack::setParameters(const String8& keyValuePairs)
1842{
1843    AutoMutex lock(mLock);
1844    return mAudioTrack->setParameters(keyValuePairs);
1845}
1846
1847status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1848{
1849    AutoMutex lock(mLock);
1850    // FIXME not implemented for fast tracks; should use proxy and SSQ
1851    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1852        return INVALID_OPERATION;
1853    }
1854    if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1855        return INVALID_OPERATION;
1856    }
1857    status_t status = mAudioTrack->getTimestamp(timestamp);
1858    if (status == NO_ERROR) {
1859        timestamp.mPosition += mProxy->getEpoch();
1860    }
1861    return status;
1862}
1863
1864String8 AudioTrack::getParameters(const String8& keys)
1865{
1866    audio_io_handle_t output = getOutput();
1867    if (output != AUDIO_IO_HANDLE_NONE) {
1868        return AudioSystem::getParameters(output, keys);
1869    } else {
1870        return String8::empty();
1871    }
1872}
1873
1874bool AudioTrack::isOffloaded() const
1875{
1876    AutoMutex lock(mLock);
1877    return isOffloaded_l();
1878}
1879
1880bool AudioTrack::isDirect() const
1881{
1882    AutoMutex lock(mLock);
1883    return isDirect_l();
1884}
1885
1886bool AudioTrack::isOffloadedOrDirect() const
1887{
1888    AutoMutex lock(mLock);
1889    return isOffloadedOrDirect_l();
1890}
1891
1892
1893status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
1894{
1895
1896    const size_t SIZE = 256;
1897    char buffer[SIZE];
1898    String8 result;
1899
1900    result.append(" AudioTrack::dump\n");
1901    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1902            mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
1903    result.append(buffer);
1904    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%zu)\n", mFormat,
1905            mChannelCount, mFrameCount);
1906    result.append(buffer);
1907    snprintf(buffer, 255, "  sample rate(%u), status(%d)\n", mSampleRate, mStatus);
1908    result.append(buffer);
1909    snprintf(buffer, 255, "  state(%d), latency (%d)\n", mState, mLatency);
1910    result.append(buffer);
1911    ::write(fd, result.string(), result.size());
1912    return NO_ERROR;
1913}
1914
1915uint32_t AudioTrack::getUnderrunFrames() const
1916{
1917    AutoMutex lock(mLock);
1918    return mProxy->getUnderrunFrames();
1919}
1920
1921void AudioTrack::setAttributesFromStreamType(audio_stream_type_t streamType) {
1922    mAttributes.flags = 0x0;
1923
1924    switch(streamType) {
1925    case AUDIO_STREAM_DEFAULT:
1926    case AUDIO_STREAM_MUSIC:
1927        mAttributes.content_type = AUDIO_CONTENT_TYPE_MUSIC;
1928        mAttributes.usage = AUDIO_USAGE_MEDIA;
1929        break;
1930    case AUDIO_STREAM_VOICE_CALL:
1931        mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1932        mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1933        break;
1934    case AUDIO_STREAM_ENFORCED_AUDIBLE:
1935        mAttributes.flags  |= AUDIO_FLAG_AUDIBILITY_ENFORCED;
1936        // intended fall through, attributes in common with STREAM_SYSTEM
1937    case AUDIO_STREAM_SYSTEM:
1938        mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1939        mAttributes.usage = AUDIO_USAGE_ASSISTANCE_SONIFICATION;
1940        break;
1941    case AUDIO_STREAM_RING:
1942        mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1943        mAttributes.usage = AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE;
1944        break;
1945    case AUDIO_STREAM_ALARM:
1946        mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1947        mAttributes.usage = AUDIO_USAGE_ALARM;
1948        break;
1949    case AUDIO_STREAM_NOTIFICATION:
1950        mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1951        mAttributes.usage = AUDIO_USAGE_NOTIFICATION;
1952        break;
1953    case AUDIO_STREAM_BLUETOOTH_SCO:
1954        mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1955        mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION;
1956        mAttributes.flags |= AUDIO_FLAG_SCO;
1957        break;
1958    case AUDIO_STREAM_DTMF:
1959        mAttributes.content_type = AUDIO_CONTENT_TYPE_SONIFICATION;
1960        mAttributes.usage = AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
1961        break;
1962    case AUDIO_STREAM_TTS:
1963        mAttributes.content_type = AUDIO_CONTENT_TYPE_SPEECH;
1964        mAttributes.usage = AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
1965        break;
1966    default:
1967        ALOGE("invalid stream type %d when converting to attributes", streamType);
1968    }
1969}
1970
1971void AudioTrack::setStreamTypeFromAttributes(audio_attributes_t& aa) {
1972    // flags to stream type mapping
1973    if ((aa.flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
1974        mStreamType = AUDIO_STREAM_ENFORCED_AUDIBLE;
1975        return;
1976    }
1977    if ((aa.flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
1978        mStreamType = AUDIO_STREAM_BLUETOOTH_SCO;
1979        return;
1980    }
1981
1982    // usage to stream type mapping
1983    switch (aa.usage) {
1984    case AUDIO_USAGE_MEDIA:
1985    case AUDIO_USAGE_GAME:
1986    case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
1987    case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
1988        mStreamType = AUDIO_STREAM_MUSIC;
1989        return;
1990    case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
1991        mStreamType = AUDIO_STREAM_SYSTEM;
1992        return;
1993    case AUDIO_USAGE_VOICE_COMMUNICATION:
1994        mStreamType = AUDIO_STREAM_VOICE_CALL;
1995        return;
1996
1997    case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
1998        mStreamType = AUDIO_STREAM_DTMF;
1999        return;
2000
2001    case AUDIO_USAGE_ALARM:
2002        mStreamType = AUDIO_STREAM_ALARM;
2003        return;
2004    case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2005        mStreamType = AUDIO_STREAM_RING;
2006        return;
2007
2008    case AUDIO_USAGE_NOTIFICATION:
2009    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2010    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2011    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2012    case AUDIO_USAGE_NOTIFICATION_EVENT:
2013        mStreamType = AUDIO_STREAM_NOTIFICATION;
2014        return;
2015
2016    case AUDIO_USAGE_UNKNOWN:
2017    default:
2018        mStreamType = AUDIO_STREAM_MUSIC;
2019    }
2020}
2021
2022bool AudioTrack::isValidAttributes(const audio_attributes_t *paa) {
2023    // has flags that map to a strategy?
2024    if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO)) != 0) {
2025        return true;
2026    }
2027
2028    // has known usage?
2029    switch (paa->usage) {
2030    case AUDIO_USAGE_UNKNOWN:
2031    case AUDIO_USAGE_MEDIA:
2032    case AUDIO_USAGE_VOICE_COMMUNICATION:
2033    case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
2034    case AUDIO_USAGE_ALARM:
2035    case AUDIO_USAGE_NOTIFICATION:
2036    case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
2037    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
2038    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
2039    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
2040    case AUDIO_USAGE_NOTIFICATION_EVENT:
2041    case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
2042    case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
2043    case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
2044    case AUDIO_USAGE_GAME:
2045        break;
2046    default:
2047        return false;
2048    }
2049    return true;
2050}
2051// =========================================================================
2052
2053void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
2054{
2055    sp<AudioTrack> audioTrack = mAudioTrack.promote();
2056    if (audioTrack != 0) {
2057        AutoMutex lock(audioTrack->mLock);
2058        audioTrack->mProxy->binderDied();
2059    }
2060}
2061
2062// =========================================================================
2063
2064AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
2065    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2066      mIgnoreNextPausedInt(false)
2067{
2068}
2069
2070AudioTrack::AudioTrackThread::~AudioTrackThread()
2071{
2072}
2073
2074bool AudioTrack::AudioTrackThread::threadLoop()
2075{
2076    {
2077        AutoMutex _l(mMyLock);
2078        if (mPaused) {
2079            mMyCond.wait(mMyLock);
2080            // caller will check for exitPending()
2081            return true;
2082        }
2083        if (mIgnoreNextPausedInt) {
2084            mIgnoreNextPausedInt = false;
2085            mPausedInt = false;
2086        }
2087        if (mPausedInt) {
2088            if (mPausedNs > 0) {
2089                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2090            } else {
2091                mMyCond.wait(mMyLock);
2092            }
2093            mPausedInt = false;
2094            return true;
2095        }
2096    }
2097    nsecs_t ns = mReceiver.processAudioBuffer();
2098    switch (ns) {
2099    case 0:
2100        return true;
2101    case NS_INACTIVE:
2102        pauseInternal();
2103        return true;
2104    case NS_NEVER:
2105        return false;
2106    case NS_WHENEVER:
2107        // FIXME increase poll interval, or make event-driven
2108        ns = 1000000000LL;
2109        // fall through
2110    default:
2111        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
2112        pauseInternal(ns);
2113        return true;
2114    }
2115}
2116
2117void AudioTrack::AudioTrackThread::requestExit()
2118{
2119    // must be in this order to avoid a race condition
2120    Thread::requestExit();
2121    resume();
2122}
2123
2124void AudioTrack::AudioTrackThread::pause()
2125{
2126    AutoMutex _l(mMyLock);
2127    mPaused = true;
2128}
2129
2130void AudioTrack::AudioTrackThread::resume()
2131{
2132    AutoMutex _l(mMyLock);
2133    mIgnoreNextPausedInt = true;
2134    if (mPaused || mPausedInt) {
2135        mPaused = false;
2136        mPausedInt = false;
2137        mMyCond.signal();
2138    }
2139}
2140
2141void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2142{
2143    AutoMutex _l(mMyLock);
2144    mPausedInt = true;
2145    mPausedNs = ns;
2146}
2147
2148}; // namespace android
2149