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