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