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