AudioTrack.cpp revision 720ad9ddb2ac6b55b0dfbfcd2d8360151d8ac427
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, bool blocking)
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,
1293                blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
1294        if (err < 0) {
1295            if (written > 0) {
1296                break;
1297            }
1298            return ssize_t(err);
1299        }
1300
1301        size_t toWrite;
1302        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1303            // Divide capacity by 2 to take expansion into account
1304            toWrite = audioBuffer.size >> 1;
1305            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) buffer, toWrite);
1306        } else {
1307            toWrite = audioBuffer.size;
1308            memcpy(audioBuffer.i8, buffer, toWrite);
1309        }
1310        buffer = ((const char *) buffer) + toWrite;
1311        userSize -= toWrite;
1312        written += toWrite;
1313
1314        releaseBuffer(&audioBuffer);
1315    }
1316
1317    return written;
1318}
1319
1320// -------------------------------------------------------------------------
1321
1322TimedAudioTrack::TimedAudioTrack() {
1323    mIsTimed = true;
1324}
1325
1326status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1327{
1328    AutoMutex lock(mLock);
1329    status_t result = UNKNOWN_ERROR;
1330
1331#if 1
1332    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1333    // while we are accessing the cblk
1334    sp<IAudioTrack> audioTrack = mAudioTrack;
1335    sp<IMemory> iMem = mCblkMemory;
1336#endif
1337
1338    // If the track is not invalid already, try to allocate a buffer.  alloc
1339    // fails indicating that the server is dead, flag the track as invalid so
1340    // we can attempt to restore in just a bit.
1341    audio_track_cblk_t* cblk = mCblk;
1342    if (!(cblk->mFlags & CBLK_INVALID)) {
1343        result = mAudioTrack->allocateTimedBuffer(size, buffer);
1344        if (result == DEAD_OBJECT) {
1345            android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1346        }
1347    }
1348
1349    // If the track is invalid at this point, attempt to restore it. and try the
1350    // allocation one more time.
1351    if (cblk->mFlags & CBLK_INVALID) {
1352        result = restoreTrack_l("allocateTimedBuffer");
1353
1354        if (result == NO_ERROR) {
1355            result = mAudioTrack->allocateTimedBuffer(size, buffer);
1356        }
1357    }
1358
1359    return result;
1360}
1361
1362status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1363                                           int64_t pts)
1364{
1365    status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1366    {
1367        AutoMutex lock(mLock);
1368        audio_track_cblk_t* cblk = mCblk;
1369        // restart track if it was disabled by audioflinger due to previous underrun
1370        if (buffer->size() != 0 && status == NO_ERROR &&
1371                (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1372            android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
1373            ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
1374            // FIXME ignoring status
1375            mAudioTrack->start();
1376        }
1377    }
1378    return status;
1379}
1380
1381status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1382                                                TargetTimeline target)
1383{
1384    return mAudioTrack->setMediaTimeTransform(xform, target);
1385}
1386
1387// -------------------------------------------------------------------------
1388
1389nsecs_t AudioTrack::processAudioBuffer()
1390{
1391    // Currently the AudioTrack thread is not created if there are no callbacks.
1392    // Would it ever make sense to run the thread, even without callbacks?
1393    // If so, then replace this by checks at each use for mCbf != NULL.
1394    LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1395
1396    mLock.lock();
1397    if (mAwaitBoost) {
1398        mAwaitBoost = false;
1399        mLock.unlock();
1400        static const int32_t kMaxTries = 5;
1401        int32_t tryCounter = kMaxTries;
1402        uint32_t pollUs = 10000;
1403        do {
1404            int policy = sched_getscheduler(0);
1405            if (policy == SCHED_FIFO || policy == SCHED_RR) {
1406                break;
1407            }
1408            usleep(pollUs);
1409            pollUs <<= 1;
1410        } while (tryCounter-- > 0);
1411        if (tryCounter < 0) {
1412            ALOGE("did not receive expected priority boost on time");
1413        }
1414        // Run again immediately
1415        return 0;
1416    }
1417
1418    // Can only reference mCblk while locked
1419    int32_t flags = android_atomic_and(
1420        ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
1421
1422    // Check for track invalidation
1423    if (flags & CBLK_INVALID) {
1424        // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1425        // AudioSystem cache. We should not exit here but after calling the callback so
1426        // that the upper layers can recreate the track
1427        if (!isOffloaded_l() || (mSequence == mObservedSequence)) {
1428            status_t status = restoreTrack_l("processAudioBuffer");
1429            mLock.unlock();
1430            // Run again immediately, but with a new IAudioTrack
1431            return 0;
1432        }
1433    }
1434
1435    bool waitStreamEnd = mState == STATE_STOPPING;
1436    bool active = mState == STATE_ACTIVE;
1437
1438    // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1439    bool newUnderrun = false;
1440    if (flags & CBLK_UNDERRUN) {
1441#if 0
1442        // Currently in shared buffer mode, when the server reaches the end of buffer,
1443        // the track stays active in continuous underrun state.  It's up to the application
1444        // to pause or stop the track, or set the position to a new offset within buffer.
1445        // This was some experimental code to auto-pause on underrun.   Keeping it here
1446        // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1447        if (mTransfer == TRANSFER_SHARED) {
1448            mState = STATE_PAUSED;
1449            active = false;
1450        }
1451#endif
1452        if (!mInUnderrun) {
1453            mInUnderrun = true;
1454            newUnderrun = true;
1455        }
1456    }
1457
1458    // Get current position of server
1459    size_t position = mProxy->getPosition();
1460
1461    // Manage marker callback
1462    bool markerReached = false;
1463    size_t markerPosition = mMarkerPosition;
1464    // FIXME fails for wraparound, need 64 bits
1465    if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1466        mMarkerReached = markerReached = true;
1467    }
1468
1469    // Determine number of new position callback(s) that will be needed, while locked
1470    size_t newPosCount = 0;
1471    size_t newPosition = mNewPosition;
1472    size_t updatePeriod = mUpdatePeriod;
1473    // FIXME fails for wraparound, need 64 bits
1474    if (updatePeriod > 0 && position >= newPosition) {
1475        newPosCount = ((position - newPosition) / updatePeriod) + 1;
1476        mNewPosition += updatePeriod * newPosCount;
1477    }
1478
1479    // Cache other fields that will be needed soon
1480    uint32_t loopPeriod = mLoopPeriod;
1481    uint32_t sampleRate = mSampleRate;
1482    size_t notificationFrames = mNotificationFramesAct;
1483    if (mRefreshRemaining) {
1484        mRefreshRemaining = false;
1485        mRemainingFrames = notificationFrames;
1486        mRetryOnPartialBuffer = false;
1487    }
1488    size_t misalignment = mProxy->getMisalignment();
1489    uint32_t sequence = mSequence;
1490
1491    // These fields don't need to be cached, because they are assigned only by set():
1492    //     mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFrameSizeAF, mFlags
1493    // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1494
1495    mLock.unlock();
1496
1497    if (waitStreamEnd) {
1498        AutoMutex lock(mLock);
1499
1500        sp<AudioTrackClientProxy> proxy = mProxy;
1501        sp<IMemory> iMem = mCblkMemory;
1502
1503        struct timespec timeout;
1504        timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1505        timeout.tv_nsec = 0;
1506
1507        mLock.unlock();
1508        status_t status = mProxy->waitStreamEndDone(&timeout);
1509        mLock.lock();
1510        switch (status) {
1511        case NO_ERROR:
1512        case DEAD_OBJECT:
1513        case TIMED_OUT:
1514            mLock.unlock();
1515            mCbf(EVENT_STREAM_END, mUserData, NULL);
1516            mLock.lock();
1517            if (mState == STATE_STOPPING) {
1518                mState = STATE_STOPPED;
1519                if (status != DEAD_OBJECT) {
1520                   return NS_INACTIVE;
1521                }
1522            }
1523            return 0;
1524        default:
1525            return 0;
1526        }
1527    }
1528
1529    // perform callbacks while unlocked
1530    if (newUnderrun) {
1531        mCbf(EVENT_UNDERRUN, mUserData, NULL);
1532    }
1533    // FIXME we will miss loops if loop cycle was signaled several times since last call
1534    //       to processAudioBuffer()
1535    if (flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) {
1536        mCbf(EVENT_LOOP_END, mUserData, NULL);
1537    }
1538    if (flags & CBLK_BUFFER_END) {
1539        mCbf(EVENT_BUFFER_END, mUserData, NULL);
1540    }
1541    if (markerReached) {
1542        mCbf(EVENT_MARKER, mUserData, &markerPosition);
1543    }
1544    while (newPosCount > 0) {
1545        size_t temp = newPosition;
1546        mCbf(EVENT_NEW_POS, mUserData, &temp);
1547        newPosition += updatePeriod;
1548        newPosCount--;
1549    }
1550
1551    if (mObservedSequence != sequence) {
1552        mObservedSequence = sequence;
1553        mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
1554        // for offloaded tracks, just wait for the upper layers to recreate the track
1555        if (isOffloaded()) {
1556            return NS_INACTIVE;
1557        }
1558    }
1559
1560    // if inactive, then don't run me again until re-started
1561    if (!active) {
1562        return NS_INACTIVE;
1563    }
1564
1565    // Compute the estimated time until the next timed event (position, markers, loops)
1566    // FIXME only for non-compressed audio
1567    uint32_t minFrames = ~0;
1568    if (!markerReached && position < markerPosition) {
1569        minFrames = markerPosition - position;
1570    }
1571    if (loopPeriod > 0 && loopPeriod < minFrames) {
1572        minFrames = loopPeriod;
1573    }
1574    if (updatePeriod > 0 && updatePeriod < minFrames) {
1575        minFrames = updatePeriod;
1576    }
1577
1578    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
1579    static const uint32_t kPoll = 0;
1580    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1581        minFrames = kPoll * notificationFrames;
1582    }
1583
1584    // Convert frame units to time units
1585    nsecs_t ns = NS_WHENEVER;
1586    if (minFrames != (uint32_t) ~0) {
1587        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1588        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1589        ns = ((minFrames * 1000000000LL) / sampleRate) + kFudgeNs;
1590    }
1591
1592    // If not supplying data by EVENT_MORE_DATA, then we're done
1593    if (mTransfer != TRANSFER_CALLBACK) {
1594        return ns;
1595    }
1596
1597    struct timespec timeout;
1598    const struct timespec *requested = &ClientProxy::kForever;
1599    if (ns != NS_WHENEVER) {
1600        timeout.tv_sec = ns / 1000000000LL;
1601        timeout.tv_nsec = ns % 1000000000LL;
1602        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1603        requested = &timeout;
1604    }
1605
1606    while (mRemainingFrames > 0) {
1607
1608        Buffer audioBuffer;
1609        audioBuffer.frameCount = mRemainingFrames;
1610        size_t nonContig;
1611        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1612        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1613                "obtainBuffer() err=%d frameCount=%u", err, audioBuffer.frameCount);
1614        requested = &ClientProxy::kNonBlocking;
1615        size_t avail = audioBuffer.frameCount + nonContig;
1616        ALOGV("obtainBuffer(%u) returned %u = %u + %u err %d",
1617                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
1618        if (err != NO_ERROR) {
1619            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1620                    (isOffloaded() && (err == DEAD_OBJECT))) {
1621                return 0;
1622            }
1623            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1624            return NS_NEVER;
1625        }
1626
1627        if (mRetryOnPartialBuffer && !isOffloaded()) {
1628            mRetryOnPartialBuffer = false;
1629            if (avail < mRemainingFrames) {
1630                int64_t myns = ((mRemainingFrames - avail) * 1100000000LL) / sampleRate;
1631                if (ns < 0 || myns < ns) {
1632                    ns = myns;
1633                }
1634                return ns;
1635            }
1636        }
1637
1638        // Divide buffer size by 2 to take into account the expansion
1639        // due to 8 to 16 bit conversion: the callback must fill only half
1640        // of the destination buffer
1641        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1642            audioBuffer.size >>= 1;
1643        }
1644
1645        size_t reqSize = audioBuffer.size;
1646        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1647        size_t writtenSize = audioBuffer.size;
1648
1649        // Sanity check on returned size
1650        if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1651            ALOGE("EVENT_MORE_DATA requested %u bytes but callback returned %d bytes",
1652                    reqSize, (int) writtenSize);
1653            return NS_NEVER;
1654        }
1655
1656        if (writtenSize == 0) {
1657            // The callback is done filling buffers
1658            // Keep this thread going to handle timed events and
1659            // still try to get more data in intervals of WAIT_PERIOD_MS
1660            // but don't just loop and block the CPU, so wait
1661            return WAIT_PERIOD_MS * 1000000LL;
1662        }
1663
1664        if (mFormat == AUDIO_FORMAT_PCM_8_BIT && !(mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1665            // 8 to 16 bit conversion, note that source and destination are the same address
1666            memcpy_to_i16_from_u8(audioBuffer.i16, (const uint8_t *) audioBuffer.i8, writtenSize);
1667            audioBuffer.size <<= 1;
1668        }
1669
1670        size_t releasedFrames = audioBuffer.size / mFrameSizeAF;
1671        audioBuffer.frameCount = releasedFrames;
1672        mRemainingFrames -= releasedFrames;
1673        if (misalignment >= releasedFrames) {
1674            misalignment -= releasedFrames;
1675        } else {
1676            misalignment = 0;
1677        }
1678
1679        releaseBuffer(&audioBuffer);
1680
1681        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1682        // if callback doesn't like to accept the full chunk
1683        if (writtenSize < reqSize) {
1684            continue;
1685        }
1686
1687        // There could be enough non-contiguous frames available to satisfy the remaining request
1688        if (mRemainingFrames <= nonContig) {
1689            continue;
1690        }
1691
1692#if 0
1693        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1694        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
1695        // that total to a sum == notificationFrames.
1696        if (0 < misalignment && misalignment <= mRemainingFrames) {
1697            mRemainingFrames = misalignment;
1698            return (mRemainingFrames * 1100000000LL) / sampleRate;
1699        }
1700#endif
1701
1702    }
1703    mRemainingFrames = notificationFrames;
1704    mRetryOnPartialBuffer = true;
1705
1706    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1707    return 0;
1708}
1709
1710status_t AudioTrack::restoreTrack_l(const char *from)
1711{
1712    ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
1713          isOffloaded_l() ? "Offloaded" : "PCM", from);
1714    ++mSequence;
1715    status_t result;
1716
1717    // refresh the audio configuration cache in this process to make sure we get new
1718    // output parameters in createTrack_l()
1719    AudioSystem::clearAudioConfigCache();
1720
1721    if (isOffloaded_l()) {
1722        // FIXME re-creation of offloaded tracks is not yet implemented
1723        return DEAD_OBJECT;
1724    }
1725
1726    // if the new IAudioTrack is created, createTrack_l() will modify the
1727    // following member variables: mAudioTrack, mCblkMemory and mCblk.
1728    // It will also delete the strong references on previous IAudioTrack and IMemory
1729
1730    // take the frames that will be lost by track recreation into account in saved position
1731    size_t position = mProxy->getPosition() + mProxy->getFramesFilled();
1732    size_t bufferPosition = mStaticProxy != NULL ? mStaticProxy->getBufferPosition() : 0;
1733    result = createTrack_l(position /*epoch*/);
1734
1735    if (result == NO_ERROR) {
1736        // continue playback from last known position, but
1737        // don't attempt to restore loop after invalidation; it's difficult and not worthwhile
1738        if (mStaticProxy != NULL) {
1739            mLoopPeriod = 0;
1740            mStaticProxy->setLoop(bufferPosition, mFrameCount, 0);
1741        }
1742        // FIXME How do we simulate the fact that all frames present in the buffer at the time of
1743        //       track destruction have been played? This is critical for SoundPool implementation
1744        //       This must be broken, and needs to be tested/debugged.
1745#if 0
1746        // restore write index and set other indexes to reflect empty buffer status
1747        if (!strcmp(from, "start")) {
1748            // Make sure that a client relying on callback events indicating underrun or
1749            // the actual amount of audio frames played (e.g SoundPool) receives them.
1750            if (mSharedBuffer == 0) {
1751                // restart playback even if buffer is not completely filled.
1752                android_atomic_or(CBLK_FORCEREADY, &mCblk->mFlags);
1753            }
1754        }
1755#endif
1756        if (mState == STATE_ACTIVE) {
1757            result = mAudioTrack->start();
1758        }
1759    }
1760    if (result != NO_ERROR) {
1761        // Use of direct and offloaded output streams is ref counted by audio policy manager.
1762#if 0   // FIXME This should no longer be needed
1763        //Use of direct and offloaded output streams is ref counted by audio policy manager.
1764        // As getOutput was called above and resulted in an output stream to be opened,
1765        // we need to release it.
1766        if (mOutput != 0) {
1767            AudioSystem::releaseOutput(mOutput);
1768            mOutput = 0;
1769        }
1770#endif
1771        ALOGW("restoreTrack_l() failed status %d", result);
1772        mState = STATE_STOPPED;
1773    }
1774
1775    return result;
1776}
1777
1778status_t AudioTrack::setParameters(const String8& keyValuePairs)
1779{
1780    AutoMutex lock(mLock);
1781    return mAudioTrack->setParameters(keyValuePairs);
1782}
1783
1784status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
1785{
1786    AutoMutex lock(mLock);
1787    // FIXME not implemented for fast tracks; should use proxy and SSQ
1788    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1789        return INVALID_OPERATION;
1790    }
1791    if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
1792        return INVALID_OPERATION;
1793    }
1794    status_t status = mAudioTrack->getTimestamp(timestamp);
1795    if (status == NO_ERROR) {
1796        timestamp.mPosition += mProxy->getEpoch();
1797    }
1798    return status;
1799}
1800
1801String8 AudioTrack::getParameters(const String8& keys)
1802{
1803    audio_io_handle_t output = getOutput();
1804    if (output != 0) {
1805        return AudioSystem::getParameters(output, keys);
1806    } else {
1807        return String8::empty();
1808    }
1809}
1810
1811bool AudioTrack::isOffloaded() const
1812{
1813    AutoMutex lock(mLock);
1814    return isOffloaded_l();
1815}
1816
1817status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
1818{
1819
1820    const size_t SIZE = 256;
1821    char buffer[SIZE];
1822    String8 result;
1823
1824    result.append(" AudioTrack::dump\n");
1825    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
1826            mVolume[0], mVolume[1]);
1827    result.append(buffer);
1828    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%zu)\n", mFormat,
1829            mChannelCount, mFrameCount);
1830    result.append(buffer);
1831    snprintf(buffer, 255, "  sample rate(%u), status(%d)\n", mSampleRate, mStatus);
1832    result.append(buffer);
1833    snprintf(buffer, 255, "  state(%d), latency (%d)\n", mState, mLatency);
1834    result.append(buffer);
1835    ::write(fd, result.string(), result.size());
1836    return NO_ERROR;
1837}
1838
1839uint32_t AudioTrack::getUnderrunFrames() const
1840{
1841    AutoMutex lock(mLock);
1842    return mProxy->getUnderrunFrames();
1843}
1844
1845// =========================================================================
1846
1847void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
1848{
1849    sp<AudioTrack> audioTrack = mAudioTrack.promote();
1850    if (audioTrack != 0) {
1851        AutoMutex lock(audioTrack->mLock);
1852        audioTrack->mProxy->binderDied();
1853    }
1854}
1855
1856// =========================================================================
1857
1858AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
1859    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
1860      mIgnoreNextPausedInt(false)
1861{
1862}
1863
1864AudioTrack::AudioTrackThread::~AudioTrackThread()
1865{
1866}
1867
1868bool AudioTrack::AudioTrackThread::threadLoop()
1869{
1870    {
1871        AutoMutex _l(mMyLock);
1872        if (mPaused) {
1873            mMyCond.wait(mMyLock);
1874            // caller will check for exitPending()
1875            return true;
1876        }
1877        if (mIgnoreNextPausedInt) {
1878            mIgnoreNextPausedInt = false;
1879            mPausedInt = false;
1880        }
1881        if (mPausedInt) {
1882            if (mPausedNs > 0) {
1883                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
1884            } else {
1885                mMyCond.wait(mMyLock);
1886            }
1887            mPausedInt = false;
1888            return true;
1889        }
1890    }
1891    nsecs_t ns = mReceiver.processAudioBuffer();
1892    switch (ns) {
1893    case 0:
1894        return true;
1895    case NS_INACTIVE:
1896        pauseInternal();
1897        return true;
1898    case NS_NEVER:
1899        return false;
1900    case NS_WHENEVER:
1901        // FIXME increase poll interval, or make event-driven
1902        ns = 1000000000LL;
1903        // fall through
1904    default:
1905        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %lld", ns);
1906        pauseInternal(ns);
1907        return true;
1908    }
1909}
1910
1911void AudioTrack::AudioTrackThread::requestExit()
1912{
1913    // must be in this order to avoid a race condition
1914    Thread::requestExit();
1915    resume();
1916}
1917
1918void AudioTrack::AudioTrackThread::pause()
1919{
1920    AutoMutex _l(mMyLock);
1921    mPaused = true;
1922}
1923
1924void AudioTrack::AudioTrackThread::resume()
1925{
1926    AutoMutex _l(mMyLock);
1927    mIgnoreNextPausedInt = true;
1928    if (mPaused || mPausedInt) {
1929        mPaused = false;
1930        mPausedInt = false;
1931        mMyCond.signal();
1932    }
1933}
1934
1935void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
1936{
1937    AutoMutex _l(mMyLock);
1938    mPausedInt = true;
1939    mPausedNs = ns;
1940}
1941
1942}; // namespace android
1943