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