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