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