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