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