AudioTrack.cpp revision 164d6539e0620d08b0395efcdd0e4aaf437daf54
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 <stdint.h>
23#include <sys/types.h>
24#include <limits.h>
25
26#include <sched.h>
27#include <sys/resource.h>
28
29#include <private/media/AudioTrackShared.h>
30
31#include <media/AudioSystem.h>
32#include <media/AudioTrack.h>
33
34#include <utils/Log.h>
35#include <binder/Parcel.h>
36#include <binder/IPCThreadState.h>
37#include <utils/Timers.h>
38#include <utils/Atomic.h>
39
40#include <cutils/bitops.h>
41#include <cutils/compiler.h>
42
43#include <system/audio.h>
44#include <system/audio_policy.h>
45
46#include <audio_utils/primitives.h>
47
48namespace android {
49// ---------------------------------------------------------------------------
50
51// static
52status_t AudioTrack::getMinFrameCount(
53        int* frameCount,
54        audio_stream_type_t streamType,
55        uint32_t sampleRate)
56{
57    if (frameCount == NULL) return BAD_VALUE;
58
59    // default to 0 in case of error
60    *frameCount = 0;
61
62    // FIXME merge with similar code in createTrack_l(), except we're missing
63    //       some information here that is available in createTrack_l():
64    //          audio_io_handle_t output
65    //          audio_format_t format
66    //          audio_channel_mask_t channelMask
67    //          audio_output_flags_t flags
68    int afSampleRate;
69    if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
70        return NO_INIT;
71    }
72    int afFrameCount;
73    if (AudioSystem::getOutputFrameCount(&afFrameCount, streamType) != NO_ERROR) {
74        return NO_INIT;
75    }
76    uint32_t afLatency;
77    if (AudioSystem::getOutputLatency(&afLatency, streamType) != NO_ERROR) {
78        return NO_INIT;
79    }
80
81    // Ensure that buffer depth covers at least audio hardware latency
82    uint32_t minBufCount = afLatency / ((1000 * afFrameCount) / afSampleRate);
83    if (minBufCount < 2) minBufCount = 2;
84
85    *frameCount = (sampleRate == 0) ? afFrameCount * minBufCount :
86            afFrameCount * minBufCount * sampleRate / afSampleRate;
87    ALOGV("getMinFrameCount=%d: afFrameCount=%d, minBufCount=%d, afSampleRate=%d, afLatency=%d",
88            *frameCount, afFrameCount, minBufCount, afSampleRate, afLatency);
89    return NO_ERROR;
90}
91
92// ---------------------------------------------------------------------------
93
94AudioTrack::AudioTrack()
95    : mStatus(NO_INIT),
96      mIsTimed(false),
97      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
98      mPreviousSchedulingGroup(SP_DEFAULT)
99{
100}
101
102AudioTrack::AudioTrack(
103        audio_stream_type_t streamType,
104        uint32_t sampleRate,
105        audio_format_t format,
106        audio_channel_mask_t channelMask,
107        int frameCount,
108        audio_output_flags_t flags,
109        callback_t cbf,
110        void* user,
111        int notificationFrames,
112        int sessionId)
113    : mStatus(NO_INIT),
114      mIsTimed(false),
115      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
116      mPreviousSchedulingGroup(SP_DEFAULT)
117{
118    mStatus = set(streamType, sampleRate, format, channelMask,
119            frameCount, flags, cbf, user, notificationFrames,
120            0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId);
121}
122
123// DEPRECATED
124AudioTrack::AudioTrack(
125        int streamType,
126        uint32_t sampleRate,
127        int format,
128        int channelMask,
129        int frameCount,
130        uint32_t flags,
131        callback_t cbf,
132        void* user,
133        int notificationFrames,
134        int sessionId)
135    : mStatus(NO_INIT),
136      mIsTimed(false),
137      mPreviousPriority(ANDROID_PRIORITY_NORMAL), mPreviousSchedulingGroup(SP_DEFAULT)
138{
139    mStatus = set((audio_stream_type_t)streamType, sampleRate, (audio_format_t)format,
140            (audio_channel_mask_t) channelMask,
141            frameCount, (audio_output_flags_t)flags, cbf, user, notificationFrames,
142            0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId);
143}
144
145AudioTrack::AudioTrack(
146        audio_stream_type_t streamType,
147        uint32_t sampleRate,
148        audio_format_t format,
149        audio_channel_mask_t channelMask,
150        const sp<IMemory>& sharedBuffer,
151        audio_output_flags_t flags,
152        callback_t cbf,
153        void* user,
154        int notificationFrames,
155        int sessionId)
156    : mStatus(NO_INIT),
157      mIsTimed(false),
158      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
159      mPreviousSchedulingGroup(SP_DEFAULT)
160{
161    mStatus = set(streamType, sampleRate, format, channelMask,
162            0 /*frameCount*/, flags, cbf, user, notificationFrames,
163            sharedBuffer, false /*threadCanCallJava*/, sessionId);
164}
165
166AudioTrack::~AudioTrack()
167{
168    ALOGV_IF(mSharedBuffer != 0, "Destructor sharedBuffer: %p", mSharedBuffer->pointer());
169
170    if (mStatus == NO_ERROR) {
171        // Make sure that callback function exits in the case where
172        // it is looping on buffer full condition in obtainBuffer().
173        // Otherwise the callback thread will never exit.
174        stop();
175        if (mAudioTrackThread != 0) {
176            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
177            mAudioTrackThread->requestExitAndWait();
178            mAudioTrackThread.clear();
179        }
180        mAudioTrack.clear();
181        IPCThreadState::self()->flushCommands();
182        AudioSystem::releaseAudioSessionId(mSessionId);
183    }
184}
185
186status_t AudioTrack::set(
187        audio_stream_type_t streamType,
188        uint32_t sampleRate,
189        audio_format_t format,
190        audio_channel_mask_t channelMask,
191        int frameCount,
192        audio_output_flags_t flags,
193        callback_t cbf,
194        void* user,
195        int notificationFrames,
196        const sp<IMemory>& sharedBuffer,
197        bool threadCanCallJava,
198        int sessionId)
199{
200
201    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
202            sharedBuffer->size());
203
204    ALOGV("set() streamType %d frameCount %d flags %04x", streamType, frameCount, flags);
205
206    AutoMutex lock(mLock);
207    if (mAudioTrack != 0) {
208        ALOGE("Track already in use");
209        return INVALID_OPERATION;
210    }
211
212    // handle default values first.
213    if (streamType == AUDIO_STREAM_DEFAULT) {
214        streamType = AUDIO_STREAM_MUSIC;
215    }
216
217    if (sampleRate == 0) {
218        int afSampleRate;
219        if (AudioSystem::getOutputSamplingRate(&afSampleRate, streamType) != NO_ERROR) {
220            return NO_INIT;
221        }
222        sampleRate = afSampleRate;
223    }
224
225    // these below should probably come from the audioFlinger too...
226    if (format == AUDIO_FORMAT_DEFAULT) {
227        format = AUDIO_FORMAT_PCM_16_BIT;
228    }
229    if (channelMask == 0) {
230        channelMask = AUDIO_CHANNEL_OUT_STEREO;
231    }
232
233    // validate parameters
234    if (!audio_is_valid_format(format)) {
235        ALOGE("Invalid format");
236        return BAD_VALUE;
237    }
238
239    // AudioFlinger does not currently support 8-bit data in shared memory
240    if (format == AUDIO_FORMAT_PCM_8_BIT && sharedBuffer != 0) {
241        ALOGE("8-bit data in shared memory is not supported");
242        return BAD_VALUE;
243    }
244
245    // force direct flag if format is not linear PCM
246    if (!audio_is_linear_pcm(format)) {
247        flags = (audio_output_flags_t)
248                // FIXME why can't we allow direct AND fast?
249                ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
250    }
251    // only allow deep buffering for music stream type
252    if (streamType != AUDIO_STREAM_MUSIC) {
253        flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
254    }
255
256    if (!audio_is_output_channel(channelMask)) {
257        ALOGE("Invalid channel mask %#x", channelMask);
258        return BAD_VALUE;
259    }
260    uint32_t channelCount = popcount(channelMask);
261
262    audio_io_handle_t output = AudioSystem::getOutput(
263                                    streamType,
264                                    sampleRate, format, channelMask,
265                                    flags);
266
267    if (output == 0) {
268        ALOGE("Could not get audio output for stream type %d", streamType);
269        return BAD_VALUE;
270    }
271
272    mVolume[LEFT] = 1.0f;
273    mVolume[RIGHT] = 1.0f;
274    mSendLevel = 0.0f;
275    mFrameCount = frameCount;
276    mNotificationFramesReq = notificationFrames;
277    mSessionId = sessionId;
278    mAuxEffectId = 0;
279    mFlags = flags;
280    mCbf = cbf;
281
282    if (cbf != NULL) {
283        mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
284        mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
285    }
286
287    // create the IAudioTrack
288    status_t status = createTrack_l(streamType,
289                                  sampleRate,
290                                  format,
291                                  channelMask,
292                                  frameCount,
293                                  flags,
294                                  sharedBuffer,
295                                  output);
296
297    if (status != NO_ERROR) {
298        if (mAudioTrackThread != 0) {
299            mAudioTrackThread->requestExit();
300            mAudioTrackThread.clear();
301        }
302        return status;
303    }
304
305    mStatus = NO_ERROR;
306
307    mStreamType = streamType;
308    mFormat = format;
309    mChannelMask = channelMask;
310    mChannelCount = channelCount;
311    mSharedBuffer = sharedBuffer;
312    mMuted = false;
313    mActive = false;
314    mUserData = user;
315    mLoopCount = 0;
316    mMarkerPosition = 0;
317    mMarkerReached = false;
318    mNewPosition = 0;
319    mUpdatePeriod = 0;
320    mFlushed = false;
321    AudioSystem::acquireAudioSessionId(mSessionId);
322    mRestoreStatus = NO_ERROR;
323    return NO_ERROR;
324}
325
326status_t AudioTrack::initCheck() const
327{
328    return mStatus;
329}
330
331// -------------------------------------------------------------------------
332
333uint32_t AudioTrack::latency() const
334{
335    return mLatency;
336}
337
338audio_stream_type_t AudioTrack::streamType() const
339{
340    return mStreamType;
341}
342
343audio_format_t AudioTrack::format() const
344{
345    return mFormat;
346}
347
348int AudioTrack::channelCount() const
349{
350    return mChannelCount;
351}
352
353uint32_t AudioTrack::frameCount() const
354{
355    return mCblk->frameCount;
356}
357
358size_t AudioTrack::frameSize() const
359{
360    if (audio_is_linear_pcm(mFormat)) {
361        return channelCount()*audio_bytes_per_sample(mFormat);
362    } else {
363        return sizeof(uint8_t);
364    }
365}
366
367sp<IMemory>& AudioTrack::sharedBuffer()
368{
369    return mSharedBuffer;
370}
371
372// -------------------------------------------------------------------------
373
374void AudioTrack::start()
375{
376    sp<AudioTrackThread> t = mAudioTrackThread;
377
378    ALOGV("start %p", this);
379
380    AutoMutex lock(mLock);
381    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
382    // while we are accessing the cblk
383    sp<IAudioTrack> audioTrack = mAudioTrack;
384    sp<IMemory> iMem = mCblkMemory;
385    audio_track_cblk_t* cblk = mCblk;
386
387    if (!mActive) {
388        mFlushed = false;
389        mActive = true;
390        mNewPosition = cblk->server + mUpdatePeriod;
391        cblk->lock.lock();
392        cblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
393        cblk->waitTimeMs = 0;
394        android_atomic_and(~CBLK_DISABLED_ON, &cblk->flags);
395        if (t != 0) {
396            t->resume();
397        } else {
398            mPreviousPriority = getpriority(PRIO_PROCESS, 0);
399            get_sched_policy(0, &mPreviousSchedulingGroup);
400            androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
401        }
402
403        ALOGV("start %p before lock cblk %p", this, mCblk);
404        status_t status = NO_ERROR;
405        if (!(cblk->flags & CBLK_INVALID_MSK)) {
406            cblk->lock.unlock();
407            ALOGV("mAudioTrack->start()");
408            status = mAudioTrack->start();
409            cblk->lock.lock();
410            if (status == DEAD_OBJECT) {
411                android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
412            }
413        }
414        if (cblk->flags & CBLK_INVALID_MSK) {
415            status = restoreTrack_l(cblk, true);
416        }
417        cblk->lock.unlock();
418        if (status != NO_ERROR) {
419            ALOGV("start() failed");
420            mActive = false;
421            if (t != 0) {
422                t->pause();
423            } else {
424                setpriority(PRIO_PROCESS, 0, mPreviousPriority);
425                set_sched_policy(0, mPreviousSchedulingGroup);
426            }
427        }
428    }
429
430}
431
432void AudioTrack::stop()
433{
434    sp<AudioTrackThread> t = mAudioTrackThread;
435
436    ALOGV("stop %p", this);
437
438    AutoMutex lock(mLock);
439    if (mActive) {
440        mActive = false;
441        mCblk->cv.signal();
442        mAudioTrack->stop();
443        // Cancel loops (If we are in the middle of a loop, playback
444        // would not stop until loopCount reaches 0).
445        setLoop_l(0, 0, 0);
446        // the playback head position will reset to 0, so if a marker is set, we need
447        // to activate it again
448        mMarkerReached = false;
449        // Force flush if a shared buffer is used otherwise audioflinger
450        // will not stop before end of buffer is reached.
451        if (mSharedBuffer != 0) {
452            flush_l();
453        }
454        if (t != 0) {
455            t->pause();
456        } else {
457            setpriority(PRIO_PROCESS, 0, mPreviousPriority);
458            set_sched_policy(0, mPreviousSchedulingGroup);
459        }
460    }
461
462}
463
464bool AudioTrack::stopped() const
465{
466    AutoMutex lock(mLock);
467    return stopped_l();
468}
469
470void AudioTrack::flush()
471{
472    AutoMutex lock(mLock);
473    flush_l();
474}
475
476// must be called with mLock held
477void AudioTrack::flush_l()
478{
479    ALOGV("flush");
480
481    // clear playback marker and periodic update counter
482    mMarkerPosition = 0;
483    mMarkerReached = false;
484    mUpdatePeriod = 0;
485
486    if (!mActive) {
487        mFlushed = true;
488        mAudioTrack->flush();
489        // Release AudioTrack callback thread in case it was waiting for new buffers
490        // in AudioTrack::obtainBuffer()
491        mCblk->cv.signal();
492    }
493}
494
495void AudioTrack::pause()
496{
497    ALOGV("pause");
498    AutoMutex lock(mLock);
499    if (mActive) {
500        mActive = false;
501        mCblk->cv.signal();
502        mAudioTrack->pause();
503    }
504}
505
506void AudioTrack::mute(bool e)
507{
508    mAudioTrack->mute(e);
509    mMuted = e;
510}
511
512bool AudioTrack::muted() const
513{
514    return mMuted;
515}
516
517status_t AudioTrack::setVolume(float left, float right)
518{
519    if (left < 0.0f || left > 1.0f || right < 0.0f || right > 1.0f) {
520        return BAD_VALUE;
521    }
522
523    AutoMutex lock(mLock);
524    mVolume[LEFT] = left;
525    mVolume[RIGHT] = right;
526
527    mCblk->setVolumeLR((uint32_t(uint16_t(right * 0x1000)) << 16) | uint16_t(left * 0x1000));
528
529    return NO_ERROR;
530}
531
532status_t AudioTrack::setVolume(float volume)
533{
534    return setVolume(volume, volume);
535}
536
537status_t AudioTrack::setAuxEffectSendLevel(float level)
538{
539    ALOGV("setAuxEffectSendLevel(%f)", level);
540    if (level < 0.0f || level > 1.0f) {
541        return BAD_VALUE;
542    }
543    AutoMutex lock(mLock);
544
545    mSendLevel = level;
546
547    mCblk->setSendLevel(level);
548
549    return NO_ERROR;
550}
551
552void AudioTrack::getAuxEffectSendLevel(float* level) const
553{
554    if (level != NULL) {
555        *level  = mSendLevel;
556    }
557}
558
559status_t AudioTrack::setSampleRate(int rate)
560{
561    int afSamplingRate;
562
563    if (mIsTimed) {
564        return INVALID_OPERATION;
565    }
566
567    if (AudioSystem::getOutputSamplingRate(&afSamplingRate, mStreamType) != NO_ERROR) {
568        return NO_INIT;
569    }
570    // Resampler implementation limits input sampling rate to 2 x output sampling rate.
571    if (rate <= 0 || rate > afSamplingRate*2 ) return BAD_VALUE;
572
573    AutoMutex lock(mLock);
574    mCblk->sampleRate = rate;
575    return NO_ERROR;
576}
577
578uint32_t AudioTrack::getSampleRate() const
579{
580    if (mIsTimed) {
581        return INVALID_OPERATION;
582    }
583
584    AutoMutex lock(mLock);
585    return mCblk->sampleRate;
586}
587
588status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
589{
590    AutoMutex lock(mLock);
591    return setLoop_l(loopStart, loopEnd, loopCount);
592}
593
594// must be called with mLock held
595status_t AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
596{
597    audio_track_cblk_t* cblk = mCblk;
598
599    Mutex::Autolock _l(cblk->lock);
600
601    if (loopCount == 0) {
602        cblk->loopStart = UINT_MAX;
603        cblk->loopEnd = UINT_MAX;
604        cblk->loopCount = 0;
605        mLoopCount = 0;
606        return NO_ERROR;
607    }
608
609    if (mIsTimed) {
610        return INVALID_OPERATION;
611    }
612
613    if (loopStart >= loopEnd ||
614        loopEnd - loopStart > cblk->frameCount ||
615        cblk->server > loopStart) {
616        ALOGE("setLoop invalid value: loopStart %d, loopEnd %d, loopCount %d, framecount %d, "
617              "user %d", loopStart, loopEnd, loopCount, cblk->frameCount, cblk->user);
618        return BAD_VALUE;
619    }
620
621    if ((mSharedBuffer != 0) && (loopEnd > cblk->frameCount)) {
622        ALOGE("setLoop invalid value: loop markers beyond data: loopStart %d, loopEnd %d, "
623            "framecount %d",
624            loopStart, loopEnd, cblk->frameCount);
625        return BAD_VALUE;
626    }
627
628    cblk->loopStart = loopStart;
629    cblk->loopEnd = loopEnd;
630    cblk->loopCount = loopCount;
631    mLoopCount = loopCount;
632
633    return NO_ERROR;
634}
635
636status_t AudioTrack::setMarkerPosition(uint32_t marker)
637{
638    if (mCbf == NULL) return INVALID_OPERATION;
639
640    mMarkerPosition = marker;
641    mMarkerReached = false;
642
643    return NO_ERROR;
644}
645
646status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
647{
648    if (marker == NULL) return BAD_VALUE;
649
650    *marker = mMarkerPosition;
651
652    return NO_ERROR;
653}
654
655status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
656{
657    if (mCbf == NULL) return INVALID_OPERATION;
658
659    uint32_t curPosition;
660    getPosition(&curPosition);
661    mNewPosition = curPosition + updatePeriod;
662    mUpdatePeriod = updatePeriod;
663
664    return NO_ERROR;
665}
666
667status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
668{
669    if (updatePeriod == NULL) return BAD_VALUE;
670
671    *updatePeriod = mUpdatePeriod;
672
673    return NO_ERROR;
674}
675
676status_t AudioTrack::setPosition(uint32_t position)
677{
678    if (mIsTimed) return INVALID_OPERATION;
679
680    AutoMutex lock(mLock);
681
682    if (!stopped_l()) return INVALID_OPERATION;
683
684    Mutex::Autolock _l(mCblk->lock);
685
686    if (position > mCblk->user) return BAD_VALUE;
687
688    mCblk->server = position;
689    android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
690
691    return NO_ERROR;
692}
693
694status_t AudioTrack::getPosition(uint32_t *position)
695{
696    if (position == NULL) return BAD_VALUE;
697    AutoMutex lock(mLock);
698    *position = mFlushed ? 0 : mCblk->server;
699
700    return NO_ERROR;
701}
702
703status_t AudioTrack::reload()
704{
705    AutoMutex lock(mLock);
706
707    if (!stopped_l()) return INVALID_OPERATION;
708
709    flush_l();
710
711    mCblk->stepUser(mCblk->frameCount);
712
713    return NO_ERROR;
714}
715
716audio_io_handle_t AudioTrack::getOutput()
717{
718    AutoMutex lock(mLock);
719    return getOutput_l();
720}
721
722// must be called with mLock held
723audio_io_handle_t AudioTrack::getOutput_l()
724{
725    return AudioSystem::getOutput(mStreamType,
726            mCblk->sampleRate, mFormat, mChannelMask, mFlags);
727}
728
729int AudioTrack::getSessionId() const
730{
731    return mSessionId;
732}
733
734status_t AudioTrack::attachAuxEffect(int effectId)
735{
736    ALOGV("attachAuxEffect(%d)", effectId);
737    status_t status = mAudioTrack->attachAuxEffect(effectId);
738    if (status == NO_ERROR) {
739        mAuxEffectId = effectId;
740    }
741    return status;
742}
743
744// -------------------------------------------------------------------------
745
746// must be called with mLock held
747status_t AudioTrack::createTrack_l(
748        audio_stream_type_t streamType,
749        uint32_t sampleRate,
750        audio_format_t format,
751        audio_channel_mask_t channelMask,
752        int frameCount,
753        audio_output_flags_t flags,
754        const sp<IMemory>& sharedBuffer,
755        audio_io_handle_t output)
756{
757    status_t status;
758    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
759    if (audioFlinger == 0) {
760        ALOGE("Could not get audioflinger");
761        return NO_INIT;
762    }
763
764    uint32_t afLatency;
765    if (AudioSystem::getLatency(output, streamType, &afLatency) != NO_ERROR) {
766        return NO_INIT;
767    }
768
769    // Client decides whether the track is TIMED (see below), but can only express a preference
770    // for FAST.  Server will perform additional tests.
771    if ((flags & AUDIO_OUTPUT_FLAG_FAST) && !(
772            // either of these use cases:
773            // use case 1: shared buffer
774            (sharedBuffer != 0) ||
775            // use case 2: callback handler
776            (mCbf != NULL))) {
777        ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client");
778        // once denied, do not request again if IAudioTrack is re-created
779        flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
780        mFlags = flags;
781    }
782    ALOGV("createTrack_l() output %d afLatency %d", output, afLatency);
783
784    mNotificationFramesAct = mNotificationFramesReq;
785
786    if (!audio_is_linear_pcm(format)) {
787
788        if (sharedBuffer != 0) {
789            // Same comment as below about ignoring frameCount parameter for set()
790            frameCount = sharedBuffer->size();
791        } else if (frameCount == 0) {
792            int afFrameCount;
793            if (AudioSystem::getFrameCount(output, streamType, &afFrameCount) != NO_ERROR) {
794                return NO_INIT;
795            }
796            frameCount = afFrameCount;
797        }
798
799    } else if (sharedBuffer != 0) {
800
801        // Ensure that buffer alignment matches channelCount
802        int channelCount = popcount(channelMask);
803        // 8-bit data in shared memory is not currently supported by AudioFlinger
804        size_t alignment = /* format == AUDIO_FORMAT_PCM_8_BIT ? 1 : */ 2;
805        if (channelCount > 1) {
806            // More than 2 channels does not require stronger alignment than stereo
807            alignment <<= 1;
808        }
809        if (((uint32_t)sharedBuffer->pointer() & (alignment - 1)) != 0) {
810            ALOGE("Invalid buffer alignment: address %p, channelCount %d",
811                    sharedBuffer->pointer(), channelCount);
812            return BAD_VALUE;
813        }
814
815        // When initializing a shared buffer AudioTrack via constructors,
816        // there's no frameCount parameter.
817        // But when initializing a shared buffer AudioTrack via set(),
818        // there _is_ a frameCount parameter.  We silently ignore it.
819        frameCount = sharedBuffer->size()/channelCount/sizeof(int16_t);
820
821    } else if (!(flags & AUDIO_OUTPUT_FLAG_FAST)) {
822
823        // FIXME move these calculations and associated checks to server
824        int afSampleRate;
825        if (AudioSystem::getSamplingRate(output, streamType, &afSampleRate) != NO_ERROR) {
826            return NO_INIT;
827        }
828        int afFrameCount;
829        if (AudioSystem::getFrameCount(output, streamType, &afFrameCount) != NO_ERROR) {
830            return NO_INIT;
831        }
832
833        // Ensure that buffer depth covers at least audio hardware latency
834        uint32_t minBufCount = afLatency / ((1000 * afFrameCount)/afSampleRate);
835        if (minBufCount < 2) minBufCount = 2;
836
837        int minFrameCount = (afFrameCount*sampleRate*minBufCount)/afSampleRate;
838        ALOGV("minFrameCount: %d, afFrameCount=%d, minBufCount=%d, sampleRate=%d, afSampleRate=%d"
839                ", afLatency=%d",
840                minFrameCount, afFrameCount, minBufCount, sampleRate, afSampleRate, afLatency);
841
842        if (frameCount == 0) {
843            frameCount = minFrameCount;
844        }
845        if (mNotificationFramesAct == 0) {
846            mNotificationFramesAct = frameCount/2;
847        }
848        // Make sure that application is notified with sufficient margin
849        // before underrun
850        if (mNotificationFramesAct > (uint32_t)frameCount/2) {
851            mNotificationFramesAct = frameCount/2;
852        }
853        if (frameCount < minFrameCount) {
854            // not ALOGW because it happens all the time when playing key clicks over A2DP
855            ALOGV("Minimum buffer size corrected from %d to %d",
856                     frameCount, minFrameCount);
857            frameCount = minFrameCount;
858        }
859
860    } else {
861        // For fast tracks, the frame count calculations and checks are done by server
862    }
863
864    IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
865    if (mIsTimed) {
866        trackFlags |= IAudioFlinger::TRACK_TIMED;
867    }
868
869    pid_t tid = -1;
870    if (flags & AUDIO_OUTPUT_FLAG_FAST) {
871        trackFlags |= IAudioFlinger::TRACK_FAST;
872        if (mAudioTrackThread != 0) {
873            tid = mAudioTrackThread->getTid();
874        }
875    }
876
877    sp<IAudioTrack> track = audioFlinger->createTrack(getpid(),
878                                                      streamType,
879                                                      sampleRate,
880                                                      format,
881                                                      channelMask,
882                                                      frameCount,
883                                                      trackFlags,
884                                                      sharedBuffer,
885                                                      output,
886                                                      tid,
887                                                      &mSessionId,
888                                                      &status);
889
890    if (track == 0) {
891        ALOGE("AudioFlinger could not create track, status: %d", status);
892        return status;
893    }
894    sp<IMemory> cblk = track->getCblk();
895    if (cblk == 0) {
896        ALOGE("Could not get control block");
897        return NO_INIT;
898    }
899    mAudioTrack = track;
900    mCblkMemory = cblk;
901    mCblk = static_cast<audio_track_cblk_t*>(cblk->pointer());
902    // old has the previous value of mCblk->flags before the "or" operation
903    int32_t old = android_atomic_or(CBLK_DIRECTION_OUT, &mCblk->flags);
904    if (flags & AUDIO_OUTPUT_FLAG_FAST) {
905        if (old & CBLK_FAST) {
906            ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %u", mCblk->frameCount);
907        } else {
908            ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %u", mCblk->frameCount);
909            // once denied, do not request again if IAudioTrack is re-created
910            flags = (audio_output_flags_t) (flags & ~AUDIO_OUTPUT_FLAG_FAST);
911            mFlags = flags;
912        }
913        if (sharedBuffer == 0) {
914            mNotificationFramesAct = mCblk->frameCount/2;
915        }
916    }
917    if (sharedBuffer == 0) {
918        mCblk->buffers = (char*)mCblk + sizeof(audio_track_cblk_t);
919    } else {
920        mCblk->buffers = sharedBuffer->pointer();
921        // Force buffer full condition as data is already present in shared memory
922        mCblk->stepUser(mCblk->frameCount);
923    }
924
925    mCblk->setVolumeLR((uint32_t(uint16_t(mVolume[RIGHT] * 0x1000)) << 16) |
926            uint16_t(mVolume[LEFT] * 0x1000));
927    mCblk->setSendLevel(mSendLevel);
928    mAudioTrack->attachAuxEffect(mAuxEffectId);
929    mCblk->bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS;
930    mCblk->waitTimeMs = 0;
931    mRemainingFrames = mNotificationFramesAct;
932    // FIXME don't believe this lie
933    mLatency = afLatency + (1000*mCblk->frameCount) / sampleRate;
934    // If IAudioTrack is re-created, don't let the requested frameCount
935    // decrease.  This can confuse clients that cache frameCount().
936    if (mCblk->frameCount > mFrameCount) {
937        mFrameCount = mCblk->frameCount;
938    }
939    return NO_ERROR;
940}
941
942status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
943{
944    AutoMutex lock(mLock);
945    bool active;
946    status_t result = NO_ERROR;
947    audio_track_cblk_t* cblk = mCblk;
948    uint32_t framesReq = audioBuffer->frameCount;
949    uint32_t waitTimeMs = (waitCount < 0) ? cblk->bufferTimeoutMs : WAIT_PERIOD_MS;
950
951    audioBuffer->frameCount  = 0;
952    audioBuffer->size = 0;
953
954    uint32_t framesAvail = cblk->framesAvailable();
955
956    cblk->lock.lock();
957    if (cblk->flags & CBLK_INVALID_MSK) {
958        goto create_new_track;
959    }
960    cblk->lock.unlock();
961
962    if (framesAvail == 0) {
963        cblk->lock.lock();
964        goto start_loop_here;
965        while (framesAvail == 0) {
966            active = mActive;
967            if (CC_UNLIKELY(!active)) {
968                ALOGV("Not active and NO_MORE_BUFFERS");
969                cblk->lock.unlock();
970                return NO_MORE_BUFFERS;
971            }
972            if (CC_UNLIKELY(!waitCount)) {
973                cblk->lock.unlock();
974                return WOULD_BLOCK;
975            }
976            if (!(cblk->flags & CBLK_INVALID_MSK)) {
977                mLock.unlock();
978                result = cblk->cv.waitRelative(cblk->lock, milliseconds(waitTimeMs));
979                cblk->lock.unlock();
980                mLock.lock();
981                if (!mActive) {
982                    return status_t(STOPPED);
983                }
984                cblk->lock.lock();
985            }
986
987            if (cblk->flags & CBLK_INVALID_MSK) {
988                goto create_new_track;
989            }
990            if (CC_UNLIKELY(result != NO_ERROR)) {
991                cblk->waitTimeMs += waitTimeMs;
992                if (cblk->waitTimeMs >= cblk->bufferTimeoutMs) {
993                    // timing out when a loop has been set and we have already written upto loop end
994                    // is a normal condition: no need to wake AudioFlinger up.
995                    if (cblk->user < cblk->loopEnd) {
996                        ALOGW("obtainBuffer timed out (is the CPU pegged?) %p name=%#x user=%08x, "
997                              "server=%08x", this, cblk->mName, cblk->user, cblk->server);
998                        //unlock cblk mutex before calling mAudioTrack->start() (see issue #1617140)
999                        cblk->lock.unlock();
1000                        result = mAudioTrack->start();
1001                        cblk->lock.lock();
1002                        if (result == DEAD_OBJECT) {
1003                            android_atomic_or(CBLK_INVALID_ON, &cblk->flags);
1004create_new_track:
1005                            result = restoreTrack_l(cblk, false);
1006                        }
1007                        if (result != NO_ERROR) {
1008                            ALOGW("obtainBuffer create Track error %d", result);
1009                            cblk->lock.unlock();
1010                            return result;
1011                        }
1012                    }
1013                    cblk->waitTimeMs = 0;
1014                }
1015
1016                if (--waitCount == 0) {
1017                    cblk->lock.unlock();
1018                    return TIMED_OUT;
1019                }
1020            }
1021            // read the server count again
1022        start_loop_here:
1023            framesAvail = cblk->framesAvailable_l();
1024        }
1025        cblk->lock.unlock();
1026    }
1027
1028    cblk->waitTimeMs = 0;
1029
1030    if (framesReq > framesAvail) {
1031        framesReq = framesAvail;
1032    }
1033
1034    uint32_t u = cblk->user;
1035    uint32_t bufferEnd = cblk->userBase + cblk->frameCount;
1036
1037    if (framesReq > bufferEnd - u) {
1038        framesReq = bufferEnd - u;
1039    }
1040
1041    audioBuffer->flags = mMuted ? Buffer::MUTE : 0;
1042    audioBuffer->channelCount = mChannelCount;
1043    audioBuffer->frameCount = framesReq;
1044    audioBuffer->size = framesReq * cblk->frameSize;
1045    if (audio_is_linear_pcm(mFormat)) {
1046        audioBuffer->format = AUDIO_FORMAT_PCM_16_BIT;
1047    } else {
1048        audioBuffer->format = mFormat;
1049    }
1050    audioBuffer->raw = (int8_t *)cblk->buffer(u);
1051    active = mActive;
1052    return active ? status_t(NO_ERROR) : status_t(STOPPED);
1053}
1054
1055void AudioTrack::releaseBuffer(Buffer* audioBuffer)
1056{
1057    AutoMutex lock(mLock);
1058    mCblk->stepUser(audioBuffer->frameCount);
1059    if (audioBuffer->frameCount > 0) {
1060        // restart track if it was disabled by audioflinger due to previous underrun
1061        if (mActive && (mCblk->flags & CBLK_DISABLED_MSK)) {
1062            android_atomic_and(~CBLK_DISABLED_ON, &mCblk->flags);
1063            ALOGW("releaseBuffer() track %p name=%#x disabled, restarting", this, mCblk->mName);
1064            mAudioTrack->start();
1065        }
1066    }
1067}
1068
1069// -------------------------------------------------------------------------
1070
1071ssize_t AudioTrack::write(const void* buffer, size_t userSize)
1072{
1073
1074    if (mSharedBuffer != 0) return INVALID_OPERATION;
1075    if (mIsTimed) return INVALID_OPERATION;
1076
1077    if (ssize_t(userSize) < 0) {
1078        // Sanity-check: user is most-likely passing an error code, and it would
1079        // make the return value ambiguous (actualSize vs error).
1080        ALOGE("AudioTrack::write(buffer=%p, size=%u (%d)",
1081                buffer, userSize, userSize);
1082        return BAD_VALUE;
1083    }
1084
1085    ALOGV("write %p: %d bytes, mActive=%d", this, userSize, mActive);
1086
1087    if (userSize == 0) {
1088        return 0;
1089    }
1090
1091    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1092    // while we are accessing the cblk
1093    mLock.lock();
1094    sp<IAudioTrack> audioTrack = mAudioTrack;
1095    sp<IMemory> iMem = mCblkMemory;
1096    mLock.unlock();
1097
1098    ssize_t written = 0;
1099    const int8_t *src = (const int8_t *)buffer;
1100    Buffer audioBuffer;
1101    size_t frameSz = frameSize();
1102
1103    do {
1104        audioBuffer.frameCount = userSize/frameSz;
1105
1106        status_t err = obtainBuffer(&audioBuffer, -1);
1107        if (err < 0) {
1108            // out of buffers, return #bytes written
1109            if (err == status_t(NO_MORE_BUFFERS))
1110                break;
1111            return ssize_t(err);
1112        }
1113
1114        size_t toWrite;
1115
1116        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1117            // Divide capacity by 2 to take expansion into account
1118            toWrite = audioBuffer.size>>1;
1119            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) src, toWrite);
1120        } else {
1121            toWrite = audioBuffer.size;
1122            memcpy(audioBuffer.i8, src, toWrite);
1123            src += toWrite;
1124        }
1125        userSize -= toWrite;
1126        written += toWrite;
1127
1128        releaseBuffer(&audioBuffer);
1129    } while (userSize >= frameSz);
1130
1131    return written;
1132}
1133
1134// -------------------------------------------------------------------------
1135
1136TimedAudioTrack::TimedAudioTrack() {
1137    mIsTimed = true;
1138}
1139
1140status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1141{
1142    status_t result = UNKNOWN_ERROR;
1143
1144    // If the track is not invalid already, try to allocate a buffer.  alloc
1145    // fails indicating that the server is dead, flag the track as invalid so
1146    // we can attempt to restore in just a bit.
1147    if (!(mCblk->flags & CBLK_INVALID_MSK)) {
1148        result = mAudioTrack->allocateTimedBuffer(size, buffer);
1149        if (result == DEAD_OBJECT) {
1150            android_atomic_or(CBLK_INVALID_ON, &mCblk->flags);
1151        }
1152    }
1153
1154    // If the track is invalid at this point, attempt to restore it. and try the
1155    // allocation one more time.
1156    if (mCblk->flags & CBLK_INVALID_MSK) {
1157        mCblk->lock.lock();
1158        result = restoreTrack_l(mCblk, false);
1159        mCblk->lock.unlock();
1160
1161        if (result == OK)
1162            result = mAudioTrack->allocateTimedBuffer(size, buffer);
1163    }
1164
1165    return result;
1166}
1167
1168status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1169                                           int64_t pts)
1170{
1171    status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1172    {
1173        AutoMutex lock(mLock);
1174        // restart track if it was disabled by audioflinger due to previous underrun
1175        if (buffer->size() != 0 && status == NO_ERROR &&
1176                mActive && (mCblk->flags & CBLK_DISABLED_MSK)) {
1177            android_atomic_and(~CBLK_DISABLED_ON, &mCblk->flags);
1178            ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
1179            mAudioTrack->start();
1180        }
1181    }
1182    return status;
1183}
1184
1185status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1186                                                TargetTimeline target)
1187{
1188    return mAudioTrack->setMediaTimeTransform(xform, target);
1189}
1190
1191// -------------------------------------------------------------------------
1192
1193bool AudioTrack::processAudioBuffer(const sp<AudioTrackThread>& thread)
1194{
1195    Buffer audioBuffer;
1196    uint32_t frames;
1197    size_t writtenSize;
1198
1199    mLock.lock();
1200    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1201    // while we are accessing the cblk
1202    sp<IAudioTrack> audioTrack = mAudioTrack;
1203    sp<IMemory> iMem = mCblkMemory;
1204    audio_track_cblk_t* cblk = mCblk;
1205    bool active = mActive;
1206    mLock.unlock();
1207
1208    // Manage underrun callback
1209    if (active && (cblk->framesAvailable() == cblk->frameCount)) {
1210        ALOGV("Underrun user: %x, server: %x, flags %04x", cblk->user, cblk->server, cblk->flags);
1211        if (!(android_atomic_or(CBLK_UNDERRUN_ON, &cblk->flags) & CBLK_UNDERRUN_MSK)) {
1212            mCbf(EVENT_UNDERRUN, mUserData, 0);
1213            if (cblk->server == cblk->frameCount) {
1214                mCbf(EVENT_BUFFER_END, mUserData, 0);
1215            }
1216            if (mSharedBuffer != 0) return false;
1217        }
1218    }
1219
1220    // Manage loop end callback
1221    while (mLoopCount > cblk->loopCount) {
1222        int loopCount = -1;
1223        mLoopCount--;
1224        if (mLoopCount >= 0) loopCount = mLoopCount;
1225
1226        mCbf(EVENT_LOOP_END, mUserData, (void *)&loopCount);
1227    }
1228
1229    // Manage marker callback
1230    if (!mMarkerReached && (mMarkerPosition > 0)) {
1231        if (cblk->server >= mMarkerPosition) {
1232            mCbf(EVENT_MARKER, mUserData, (void *)&mMarkerPosition);
1233            mMarkerReached = true;
1234        }
1235    }
1236
1237    // Manage new position callback
1238    if (mUpdatePeriod > 0) {
1239        while (cblk->server >= mNewPosition) {
1240            mCbf(EVENT_NEW_POS, mUserData, (void *)&mNewPosition);
1241            mNewPosition += mUpdatePeriod;
1242        }
1243    }
1244
1245    // If Shared buffer is used, no data is requested from client.
1246    if (mSharedBuffer != 0) {
1247        frames = 0;
1248    } else {
1249        frames = mRemainingFrames;
1250    }
1251
1252    // See description of waitCount parameter at declaration of obtainBuffer().
1253    // The logic below prevents us from being stuck below at obtainBuffer()
1254    // not being able to handle timed events (position, markers, loops).
1255    int32_t waitCount = -1;
1256    if (mUpdatePeriod || (!mMarkerReached && mMarkerPosition) || mLoopCount) {
1257        waitCount = 1;
1258    }
1259
1260    do {
1261
1262        audioBuffer.frameCount = frames;
1263
1264        status_t err = obtainBuffer(&audioBuffer, waitCount);
1265        if (err < NO_ERROR) {
1266            if (err != TIMED_OUT) {
1267                ALOGE_IF(err != status_t(NO_MORE_BUFFERS),
1268                        "Error obtaining an audio buffer, giving up.");
1269                return false;
1270            }
1271            break;
1272        }
1273        if (err == status_t(STOPPED)) return false;
1274
1275        // Divide buffer size by 2 to take into account the expansion
1276        // due to 8 to 16 bit conversion: the callback must fill only half
1277        // of the destination buffer
1278        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1279            audioBuffer.size >>= 1;
1280        }
1281
1282        size_t reqSize = audioBuffer.size;
1283        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1284        writtenSize = audioBuffer.size;
1285
1286        // Sanity check on returned size
1287        if (ssize_t(writtenSize) <= 0) {
1288            // The callback is done filling buffers
1289            // Keep this thread going to handle timed events and
1290            // still try to get more data in intervals of WAIT_PERIOD_MS
1291            // but don't just loop and block the CPU, so wait
1292            usleep(WAIT_PERIOD_MS*1000);
1293            break;
1294        }
1295
1296        if (writtenSize > reqSize) writtenSize = reqSize;
1297
1298        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1299            // 8 to 16 bit conversion, note that source and destination are the same address
1300            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
1301            writtenSize <<= 1;
1302        }
1303
1304        audioBuffer.size = writtenSize;
1305        // NOTE: mCblk->frameSize is not equal to AudioTrack::frameSize() for
1306        // 8 bit PCM data: in this case,  mCblk->frameSize is based on a sample size of
1307        // 16 bit.
1308        audioBuffer.frameCount = writtenSize/mCblk->frameSize;
1309
1310        frames -= audioBuffer.frameCount;
1311
1312        releaseBuffer(&audioBuffer);
1313    }
1314    while (frames);
1315
1316    if (frames == 0) {
1317        mRemainingFrames = mNotificationFramesAct;
1318    } else {
1319        mRemainingFrames = frames;
1320    }
1321    return true;
1322}
1323
1324// must be called with mLock and cblk.lock held. Callers must also hold strong references on
1325// the IAudioTrack and IMemory in case they are recreated here.
1326// If the IAudioTrack is successfully restored, the cblk pointer is updated
1327status_t AudioTrack::restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart)
1328{
1329    status_t result;
1330
1331    if (!(android_atomic_or(CBLK_RESTORING_ON, &cblk->flags) & CBLK_RESTORING_MSK)) {
1332        ALOGW("dead IAudioTrack, creating a new one from %s TID %d",
1333            fromStart ? "start()" : "obtainBuffer()", gettid());
1334
1335        // signal old cblk condition so that other threads waiting for available buffers stop
1336        // waiting now
1337        cblk->cv.broadcast();
1338        cblk->lock.unlock();
1339
1340        // refresh the audio configuration cache in this process to make sure we get new
1341        // output parameters in getOutput_l() and createTrack_l()
1342        AudioSystem::clearAudioConfigCache();
1343
1344        // if the new IAudioTrack is created, createTrack_l() will modify the
1345        // following member variables: mAudioTrack, mCblkMemory and mCblk.
1346        // It will also delete the strong references on previous IAudioTrack and IMemory
1347        result = createTrack_l(mStreamType,
1348                               cblk->sampleRate,
1349                               mFormat,
1350                               mChannelMask,
1351                               mFrameCount,
1352                               mFlags,
1353                               mSharedBuffer,
1354                               getOutput_l());
1355
1356        if (result == NO_ERROR) {
1357            uint32_t user = cblk->user;
1358            uint32_t server = cblk->server;
1359            // restore write index and set other indexes to reflect empty buffer status
1360            mCblk->user = user;
1361            mCblk->server = user;
1362            mCblk->userBase = user;
1363            mCblk->serverBase = user;
1364            // restore loop: this is not guaranteed to succeed if new frame count is not
1365            // compatible with loop length
1366            setLoop_l(cblk->loopStart, cblk->loopEnd, cblk->loopCount);
1367            if (!fromStart) {
1368                mCblk->bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1369                // Make sure that a client relying on callback events indicating underrun or
1370                // the actual amount of audio frames played (e.g SoundPool) receives them.
1371                if (mSharedBuffer == 0) {
1372                    uint32_t frames = 0;
1373                    if (user > server) {
1374                        frames = ((user - server) > mCblk->frameCount) ?
1375                                mCblk->frameCount : (user - server);
1376                        memset(mCblk->buffers, 0, frames * mCblk->frameSize);
1377                    }
1378                    // restart playback even if buffer is not completely filled.
1379                    android_atomic_or(CBLK_FORCEREADY_ON, &mCblk->flags);
1380                    // stepUser() clears CBLK_UNDERRUN_ON flag enabling underrun callbacks to
1381                    // the client
1382                    mCblk->stepUser(frames);
1383                }
1384            }
1385            if (mSharedBuffer != 0) {
1386                mCblk->stepUser(mCblk->frameCount);
1387            }
1388            if (mActive) {
1389                result = mAudioTrack->start();
1390                ALOGW_IF(result != NO_ERROR, "restoreTrack_l() start() failed status %d", result);
1391            }
1392            if (fromStart && result == NO_ERROR) {
1393                mNewPosition = mCblk->server + mUpdatePeriod;
1394            }
1395        }
1396        if (result != NO_ERROR) {
1397            android_atomic_and(~CBLK_RESTORING_ON, &cblk->flags);
1398            ALOGW_IF(result != NO_ERROR, "restoreTrack_l() failed status %d", result);
1399        }
1400        mRestoreStatus = result;
1401        // signal old cblk condition for other threads waiting for restore completion
1402        android_atomic_or(CBLK_RESTORED_ON, &cblk->flags);
1403        cblk->cv.broadcast();
1404    } else {
1405        bool haveLogged = false;
1406        for (;;) {
1407            if (cblk->flags & CBLK_RESTORED_MSK) {
1408                ALOGW("dead IAudioTrack restored");
1409                result = mRestoreStatus;
1410                cblk->lock.unlock();
1411                break;
1412            }
1413            if (!haveLogged) {
1414                ALOGW("dead IAudioTrack, waiting for a new one");
1415                haveLogged = true;
1416            }
1417            mLock.unlock();
1418            result = cblk->cv.waitRelative(cblk->lock, milliseconds(RESTORE_TIMEOUT_MS));
1419            cblk->lock.unlock();
1420            mLock.lock();
1421            if (result != NO_ERROR) {
1422                ALOGW("timed out");
1423                break;
1424            }
1425            cblk->lock.lock();
1426        }
1427    }
1428    ALOGV("restoreTrack_l() status %d mActive %d cblk %p, old cblk %p flags %08x old flags %08x",
1429        result, mActive, mCblk, cblk, mCblk->flags, cblk->flags);
1430
1431    if (result == NO_ERROR) {
1432        // from now on we switch to the newly created cblk
1433        cblk = mCblk;
1434    }
1435    cblk->lock.lock();
1436
1437    ALOGW_IF(result != NO_ERROR, "restoreTrack_l() error %d TID %d", result, gettid());
1438
1439    return result;
1440}
1441
1442status_t AudioTrack::dump(int fd, const Vector<String16>& args) const
1443{
1444
1445    const size_t SIZE = 256;
1446    char buffer[SIZE];
1447    String8 result;
1448
1449    result.append(" AudioTrack::dump\n");
1450    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1451            mVolume[0], mVolume[1]);
1452    result.append(buffer);
1453    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%d)\n", mFormat,
1454            mChannelCount, mCblk->frameCount);
1455    result.append(buffer);
1456    snprintf(buffer, 255, "  sample rate(%d), status(%d), muted(%d)\n",
1457            (mCblk == 0) ? 0 : mCblk->sampleRate, mStatus, mMuted);
1458    result.append(buffer);
1459    snprintf(buffer, 255, "  active(%d), latency (%d)\n", mActive, mLatency);
1460    result.append(buffer);
1461    ::write(fd, result.string(), result.size());
1462    return NO_ERROR;
1463}
1464
1465// =========================================================================
1466
1467AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1468    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true)
1469{
1470}
1471
1472AudioTrack::AudioTrackThread::~AudioTrackThread()
1473{
1474}
1475
1476bool AudioTrack::AudioTrackThread::threadLoop()
1477{
1478    {
1479        AutoMutex _l(mMyLock);
1480        if (mPaused) {
1481            mMyCond.wait(mMyLock);
1482            // caller will check for exitPending()
1483            return true;
1484        }
1485    }
1486    if (!mReceiver.processAudioBuffer(this)) {
1487        pause();
1488    }
1489    return true;
1490}
1491
1492void AudioTrack::AudioTrackThread::requestExit()
1493{
1494    // must be in this order to avoid a race condition
1495    Thread::requestExit();
1496    resume();
1497}
1498
1499void AudioTrack::AudioTrackThread::pause()
1500{
1501    AutoMutex _l(mMyLock);
1502    mPaused = true;
1503}
1504
1505void AudioTrack::AudioTrackThread::resume()
1506{
1507    AutoMutex _l(mMyLock);
1508    if (mPaused) {
1509        mPaused = false;
1510        mMyCond.signal();
1511    }
1512}
1513
1514// =========================================================================
1515
1516
1517audio_track_cblk_t::audio_track_cblk_t()
1518    : lock(Mutex::SHARED), cv(Condition::SHARED), user(0), server(0),
1519    userBase(0), serverBase(0), buffers(NULL), frameCount(0),
1520    loopStart(UINT_MAX), loopEnd(UINT_MAX), loopCount(0), mVolumeLR(0x10001000),
1521    mSendLevel(0), flags(0)
1522{
1523}
1524
1525uint32_t audio_track_cblk_t::stepUser(uint32_t frameCount)
1526{
1527    ALOGV("stepuser %08x %08x %d", user, server, frameCount);
1528
1529    uint32_t u = user;
1530    u += frameCount;
1531    // Ensure that user is never ahead of server for AudioRecord
1532    if (flags & CBLK_DIRECTION_MSK) {
1533        // If stepServer() has been called once, switch to normal obtainBuffer() timeout period
1534        if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS-1) {
1535            bufferTimeoutMs = MAX_RUN_TIMEOUT_MS;
1536        }
1537    } else if (u > server) {
1538        ALOGW("stepUser occurred after track reset");
1539        u = server;
1540    }
1541
1542    uint32_t fc = this->frameCount;
1543    if (u >= fc) {
1544        // common case, user didn't just wrap
1545        if (u - fc >= userBase ) {
1546            userBase += fc;
1547        }
1548    } else if (u >= userBase + fc) {
1549        // user just wrapped
1550        userBase += fc;
1551    }
1552
1553    user = u;
1554
1555    // Clear flow control error condition as new data has been written/read to/from buffer.
1556    if (flags & CBLK_UNDERRUN_MSK) {
1557        android_atomic_and(~CBLK_UNDERRUN_MSK, &flags);
1558    }
1559
1560    return u;
1561}
1562
1563bool audio_track_cblk_t::stepServer(uint32_t frameCount)
1564{
1565    ALOGV("stepserver %08x %08x %d", user, server, frameCount);
1566
1567    if (!tryLock()) {
1568        ALOGW("stepServer() could not lock cblk");
1569        return false;
1570    }
1571
1572    uint32_t s = server;
1573    bool flushed = (s == user);
1574
1575    s += frameCount;
1576    if (flags & CBLK_DIRECTION_MSK) {
1577        // Mark that we have read the first buffer so that next time stepUser() is called
1578        // we switch to normal obtainBuffer() timeout period
1579        if (bufferTimeoutMs == MAX_STARTUP_TIMEOUT_MS) {
1580            bufferTimeoutMs = MAX_STARTUP_TIMEOUT_MS - 1;
1581        }
1582        // It is possible that we receive a flush()
1583        // while the mixer is processing a block: in this case,
1584        // stepServer() is called After the flush() has reset u & s and
1585        // we have s > u
1586        if (flushed) {
1587            ALOGW("stepServer occurred after track reset");
1588            s = user;
1589        }
1590    }
1591
1592    if (s >= loopEnd) {
1593        ALOGW_IF(s > loopEnd, "stepServer: s %u > loopEnd %u", s, loopEnd);
1594        s = loopStart;
1595        if (--loopCount == 0) {
1596            loopEnd = UINT_MAX;
1597            loopStart = UINT_MAX;
1598        }
1599    }
1600
1601    uint32_t fc = this->frameCount;
1602    if (s >= fc) {
1603        // common case, server didn't just wrap
1604        if (s - fc >= serverBase ) {
1605            serverBase += fc;
1606        }
1607    } else if (s >= serverBase + fc) {
1608        // server just wrapped
1609        serverBase += fc;
1610    }
1611
1612    server = s;
1613
1614    if (!(flags & CBLK_INVALID_MSK)) {
1615        cv.signal();
1616    }
1617    lock.unlock();
1618    return true;
1619}
1620
1621void* audio_track_cblk_t::buffer(uint32_t offset) const
1622{
1623    return (int8_t *)buffers + (offset - userBase) * frameSize;
1624}
1625
1626uint32_t audio_track_cblk_t::framesAvailable()
1627{
1628    Mutex::Autolock _l(lock);
1629    return framesAvailable_l();
1630}
1631
1632uint32_t audio_track_cblk_t::framesAvailable_l()
1633{
1634    uint32_t u = user;
1635    uint32_t s = server;
1636
1637    if (flags & CBLK_DIRECTION_MSK) {
1638        uint32_t limit = (s < loopStart) ? s : loopStart;
1639        return limit + frameCount - u;
1640    } else {
1641        return frameCount + u - s;
1642    }
1643}
1644
1645uint32_t audio_track_cblk_t::framesReady()
1646{
1647    uint32_t u = user;
1648    uint32_t s = server;
1649
1650    if (flags & CBLK_DIRECTION_MSK) {
1651        if (u < loopEnd) {
1652            return u - s;
1653        } else {
1654            // do not block on mutex shared with client on AudioFlinger side
1655            if (!tryLock()) {
1656                ALOGW("framesReady() could not lock cblk");
1657                return 0;
1658            }
1659            uint32_t frames = UINT_MAX;
1660            if (loopCount >= 0) {
1661                frames = (loopEnd - loopStart)*loopCount + u - s;
1662            }
1663            lock.unlock();
1664            return frames;
1665        }
1666    } else {
1667        return s - u;
1668    }
1669}
1670
1671bool audio_track_cblk_t::tryLock()
1672{
1673    // the code below simulates lock-with-timeout
1674    // we MUST do this to protect the AudioFlinger server
1675    // as this lock is shared with the client.
1676    status_t err;
1677
1678    err = lock.tryLock();
1679    if (err == -EBUSY) { // just wait a bit
1680        usleep(1000);
1681        err = lock.tryLock();
1682    }
1683    if (err != NO_ERROR) {
1684        // probably, the client just died.
1685        return false;
1686    }
1687    return true;
1688}
1689
1690// -------------------------------------------------------------------------
1691
1692}; // namespace android
1693