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