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