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