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