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