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