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