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