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