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