AudioTrack.cpp revision 8edb8dc44b8a2f81bdb5db645b6b708548771a31
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//#define LOG_NDEBUG 0
19#define LOG_TAG "AudioTrack"
20
21#include <inttypes.h>
22#include <math.h>
23#include <sys/resource.h>
24
25#include <audio_utils/primitives.h>
26#include <binder/IPCThreadState.h>
27#include <media/AudioTrack.h>
28#include <utils/Log.h>
29#include <private/media/AudioTrackShared.h>
30#include <media/IAudioFlinger.h>
31#include <media/AudioPolicyHelper.h>
32#include <media/AudioResamplerPublic.h>
33
34#define WAIT_PERIOD_MS                  10
35#define WAIT_STREAM_END_TIMEOUT_SEC     120
36static const int kMaxLoopCountNotifications = 32;
37
38namespace android {
39// ---------------------------------------------------------------------------
40
41template <typename T>
42const T &min(const T &x, const T &y) {
43    return x < y ? x : y;
44}
45
46static int64_t convertTimespecToUs(const struct timespec &tv)
47{
48    return tv.tv_sec * 1000000ll + tv.tv_nsec / 1000;
49}
50
51// current monotonic time in microseconds.
52static int64_t getNowUs()
53{
54    struct timespec tv;
55    (void) clock_gettime(CLOCK_MONOTONIC, &tv);
56    return convertTimespecToUs(tv);
57}
58
59// Must match similar computation in createTrack_l in Threads.cpp.
60// TODO: Move to a common library
61static size_t calculateMinFrameCount(
62        uint32_t afLatencyMs, uint32_t afFrameCount, uint32_t afSampleRate,
63        uint32_t sampleRate, float speed)
64{
65    // Ensure that buffer depth covers at least audio hardware latency
66    uint32_t minBufCount = afLatencyMs / ((1000 * afFrameCount) / afSampleRate);
67    if (minBufCount < 2) {
68        minBufCount = 2;
69    }
70    ALOGV("calculateMinFrameCount afLatency %u  afFrameCount %u  afSampleRate %u  "
71            "sampleRate %u  speed %f  minBufCount: %u",
72            afLatencyMs, afFrameCount, afSampleRate, sampleRate, speed, minBufCount);
73    return minBufCount * sourceFramesNeededWithTimestretch(
74            sampleRate, afFrameCount, afSampleRate, speed);
75}
76
77// static
78status_t AudioTrack::getMinFrameCount(
79        size_t* frameCount,
80        audio_stream_type_t streamType,
81        uint32_t sampleRate)
82{
83    if (frameCount == NULL) {
84        return BAD_VALUE;
85    }
86
87    // FIXME handle in server, like createTrack_l(), possible missing info:
88    //          audio_io_handle_t output
89    //          audio_format_t format
90    //          audio_channel_mask_t channelMask
91    //          audio_output_flags_t flags (FAST)
92    uint32_t afSampleRate;
93    status_t status;
94    status = AudioSystem::getOutputSamplingRate(&afSampleRate, streamType);
95    if (status != NO_ERROR) {
96        ALOGE("Unable to query output sample rate for stream type %d; status %d",
97                streamType, status);
98        return status;
99    }
100    size_t afFrameCount;
101    status = AudioSystem::getOutputFrameCount(&afFrameCount, streamType);
102    if (status != NO_ERROR) {
103        ALOGE("Unable to query output frame count for stream type %d; status %d",
104                streamType, status);
105        return status;
106    }
107    uint32_t afLatency;
108    status = AudioSystem::getOutputLatency(&afLatency, streamType);
109    if (status != NO_ERROR) {
110        ALOGE("Unable to query output latency for stream type %d; status %d",
111                streamType, status);
112        return status;
113    }
114
115    // When called from createTrack, speed is 1.0f (normal speed).
116    // This is rechecked again on setting playback rate (TODO: on setting sample rate, too).
117    *frameCount = calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, 1.0f);
118
119    // The formula above should always produce a non-zero value under normal circumstances:
120    // AudioTrack.SAMPLE_RATE_HZ_MIN <= sampleRate <= AudioTrack.SAMPLE_RATE_HZ_MAX.
121    // Return error in the unlikely event that it does not, as that's part of the API contract.
122    if (*frameCount == 0) {
123        ALOGE("AudioTrack::getMinFrameCount failed for streamType %d, sampleRate %u",
124                streamType, sampleRate);
125        return BAD_VALUE;
126    }
127    ALOGV("getMinFrameCount=%zu: afFrameCount=%zu, afSampleRate=%u, afLatency=%u",
128            *frameCount, afFrameCount, afSampleRate, afLatency);
129    return NO_ERROR;
130}
131
132// ---------------------------------------------------------------------------
133
134AudioTrack::AudioTrack()
135    : mStatus(NO_INIT),
136      mIsTimed(false),
137      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
138      mPreviousSchedulingGroup(SP_DEFAULT),
139      mPausedPosition(0),
140      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
141{
142    mAttributes.content_type = AUDIO_CONTENT_TYPE_UNKNOWN;
143    mAttributes.usage = AUDIO_USAGE_UNKNOWN;
144    mAttributes.flags = 0x0;
145    strcpy(mAttributes.tags, "");
146}
147
148AudioTrack::AudioTrack(
149        audio_stream_type_t streamType,
150        uint32_t sampleRate,
151        audio_format_t format,
152        audio_channel_mask_t channelMask,
153        size_t frameCount,
154        audio_output_flags_t flags,
155        callback_t cbf,
156        void* user,
157        uint32_t notificationFrames,
158        int sessionId,
159        transfer_type transferType,
160        const audio_offload_info_t *offloadInfo,
161        int uid,
162        pid_t pid,
163        const audio_attributes_t* pAttributes)
164    : mStatus(NO_INIT),
165      mIsTimed(false),
166      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
167      mPreviousSchedulingGroup(SP_DEFAULT),
168      mPausedPosition(0),
169      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
170{
171    mStatus = set(streamType, sampleRate, format, channelMask,
172            frameCount, flags, cbf, user, notificationFrames,
173            0 /*sharedBuffer*/, false /*threadCanCallJava*/, sessionId, transferType,
174            offloadInfo, uid, pid, pAttributes);
175}
176
177AudioTrack::AudioTrack(
178        audio_stream_type_t streamType,
179        uint32_t sampleRate,
180        audio_format_t format,
181        audio_channel_mask_t channelMask,
182        const sp<IMemory>& sharedBuffer,
183        audio_output_flags_t flags,
184        callback_t cbf,
185        void* user,
186        uint32_t notificationFrames,
187        int sessionId,
188        transfer_type transferType,
189        const audio_offload_info_t *offloadInfo,
190        int uid,
191        pid_t pid,
192        const audio_attributes_t* pAttributes)
193    : mStatus(NO_INIT),
194      mIsTimed(false),
195      mPreviousPriority(ANDROID_PRIORITY_NORMAL),
196      mPreviousSchedulingGroup(SP_DEFAULT),
197      mPausedPosition(0),
198      mSelectedDeviceId(AUDIO_PORT_HANDLE_NONE)
199{
200    mStatus = set(streamType, sampleRate, format, channelMask,
201            0 /*frameCount*/, flags, cbf, user, notificationFrames,
202            sharedBuffer, false /*threadCanCallJava*/, sessionId, transferType, offloadInfo,
203            uid, pid, pAttributes);
204}
205
206AudioTrack::~AudioTrack()
207{
208    if (mStatus == NO_ERROR) {
209        // Make sure that callback function exits in the case where
210        // it is looping on buffer full condition in obtainBuffer().
211        // Otherwise the callback thread will never exit.
212        stop();
213        if (mAudioTrackThread != 0) {
214            mProxy->interrupt();
215            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
216            mAudioTrackThread->requestExitAndWait();
217            mAudioTrackThread.clear();
218        }
219        IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
220        mAudioTrack.clear();
221        mCblkMemory.clear();
222        mSharedBuffer.clear();
223        IPCThreadState::self()->flushCommands();
224        ALOGV("~AudioTrack, releasing session id %d from %d on behalf of %d",
225                mSessionId, IPCThreadState::self()->getCallingPid(), mClientPid);
226        AudioSystem::releaseAudioSessionId(mSessionId, mClientPid);
227    }
228}
229
230status_t AudioTrack::set(
231        audio_stream_type_t streamType,
232        uint32_t sampleRate,
233        audio_format_t format,
234        audio_channel_mask_t channelMask,
235        size_t frameCount,
236        audio_output_flags_t flags,
237        callback_t cbf,
238        void* user,
239        uint32_t notificationFrames,
240        const sp<IMemory>& sharedBuffer,
241        bool threadCanCallJava,
242        int sessionId,
243        transfer_type transferType,
244        const audio_offload_info_t *offloadInfo,
245        int uid,
246        pid_t pid,
247        const audio_attributes_t* pAttributes)
248{
249    ALOGV("set(): streamType %d, sampleRate %u, format %#x, channelMask %#x, frameCount %zu, "
250          "flags #%x, notificationFrames %u, sessionId %d, transferType %d, uid %d, pid %d",
251          streamType, sampleRate, format, channelMask, frameCount, flags, notificationFrames,
252          sessionId, transferType, uid, pid);
253
254    switch (transferType) {
255    case TRANSFER_DEFAULT:
256        if (sharedBuffer != 0) {
257            transferType = TRANSFER_SHARED;
258        } else if (cbf == NULL || threadCanCallJava) {
259            transferType = TRANSFER_SYNC;
260        } else {
261            transferType = TRANSFER_CALLBACK;
262        }
263        break;
264    case TRANSFER_CALLBACK:
265        if (cbf == NULL || sharedBuffer != 0) {
266            ALOGE("Transfer type TRANSFER_CALLBACK but cbf == NULL || sharedBuffer != 0");
267            return BAD_VALUE;
268        }
269        break;
270    case TRANSFER_OBTAIN:
271    case TRANSFER_SYNC:
272        if (sharedBuffer != 0) {
273            ALOGE("Transfer type TRANSFER_OBTAIN but sharedBuffer != 0");
274            return BAD_VALUE;
275        }
276        break;
277    case TRANSFER_SHARED:
278        if (sharedBuffer == 0) {
279            ALOGE("Transfer type TRANSFER_SHARED but sharedBuffer == 0");
280            return BAD_VALUE;
281        }
282        break;
283    default:
284        ALOGE("Invalid transfer type %d", transferType);
285        return BAD_VALUE;
286    }
287    mSharedBuffer = sharedBuffer;
288    mTransfer = transferType;
289
290    ALOGV_IF(sharedBuffer != 0, "sharedBuffer: %p, size: %d", sharedBuffer->pointer(),
291            sharedBuffer->size());
292
293    ALOGV("set() streamType %d frameCount %zu flags %04x", streamType, frameCount, flags);
294
295    // invariant that mAudioTrack != 0 is true only after set() returns successfully
296    if (mAudioTrack != 0) {
297        ALOGE("Track already in use");
298        return INVALID_OPERATION;
299    }
300
301    // handle default values first.
302    if (streamType == AUDIO_STREAM_DEFAULT) {
303        streamType = AUDIO_STREAM_MUSIC;
304    }
305    if (pAttributes == NULL) {
306        if (uint32_t(streamType) >= AUDIO_STREAM_PUBLIC_CNT) {
307            ALOGE("Invalid stream type %d", streamType);
308            return BAD_VALUE;
309        }
310        mStreamType = streamType;
311
312    } else {
313        // stream type shouldn't be looked at, this track has audio attributes
314        memcpy(&mAttributes, pAttributes, sizeof(audio_attributes_t));
315        ALOGV("Building AudioTrack with attributes: usage=%d content=%d flags=0x%x tags=[%s]",
316                mAttributes.usage, mAttributes.content_type, mAttributes.flags, mAttributes.tags);
317        mStreamType = AUDIO_STREAM_DEFAULT;
318        if ((mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
319            flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
320        }
321    }
322
323    // these below should probably come from the audioFlinger too...
324    if (format == AUDIO_FORMAT_DEFAULT) {
325        format = AUDIO_FORMAT_PCM_16_BIT;
326    }
327
328    // validate parameters
329    if (!audio_is_valid_format(format)) {
330        ALOGE("Invalid format %#x", format);
331        return BAD_VALUE;
332    }
333    mFormat = format;
334
335    if (!audio_is_output_channel(channelMask)) {
336        ALOGE("Invalid channel mask %#x", channelMask);
337        return BAD_VALUE;
338    }
339    mChannelMask = channelMask;
340    uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
341    mChannelCount = channelCount;
342
343    // force direct flag if format is not linear PCM
344    // or offload was requested
345    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
346            || !audio_is_linear_pcm(format)) {
347        ALOGV( (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
348                    ? "Offload request, forcing to Direct Output"
349                    : "Not linear PCM, forcing to Direct Output");
350        flags = (audio_output_flags_t)
351                // FIXME why can't we allow direct AND fast?
352                ((flags | AUDIO_OUTPUT_FLAG_DIRECT) & ~AUDIO_OUTPUT_FLAG_FAST);
353    }
354
355    // force direct flag if HW A/V sync requested
356    if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
357        flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
358    }
359
360    if (flags & AUDIO_OUTPUT_FLAG_DIRECT) {
361        if (audio_is_linear_pcm(format)) {
362            mFrameSize = channelCount * audio_bytes_per_sample(format);
363        } else {
364            mFrameSize = sizeof(uint8_t);
365        }
366    } else {
367        ALOG_ASSERT(audio_is_linear_pcm(format));
368        mFrameSize = channelCount * audio_bytes_per_sample(format);
369        // createTrack will return an error if PCM format is not supported by server,
370        // so no need to check for specific PCM formats here
371    }
372
373    // sampling rate must be specified for direct outputs
374    if (sampleRate == 0 && (flags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
375        return BAD_VALUE;
376    }
377    mSampleRate = sampleRate;
378    mSpeed = AUDIO_TIMESTRETCH_SPEED_NORMAL;
379    mPitch = AUDIO_TIMESTRETCH_PITCH_NORMAL;
380
381    // Make copy of input parameter offloadInfo so that in the future:
382    //  (a) createTrack_l doesn't need it as an input parameter
383    //  (b) we can support re-creation of offloaded tracks
384    if (offloadInfo != NULL) {
385        mOffloadInfoCopy = *offloadInfo;
386        mOffloadInfo = &mOffloadInfoCopy;
387    } else {
388        mOffloadInfo = NULL;
389    }
390
391    mVolume[AUDIO_INTERLEAVE_LEFT] = 1.0f;
392    mVolume[AUDIO_INTERLEAVE_RIGHT] = 1.0f;
393    mSendLevel = 0.0f;
394    // mFrameCount is initialized in createTrack_l
395    mReqFrameCount = frameCount;
396    mNotificationFramesReq = notificationFrames;
397    mNotificationFramesAct = 0;
398    if (sessionId == AUDIO_SESSION_ALLOCATE) {
399        mSessionId = AudioSystem::newAudioUniqueId();
400    } else {
401        mSessionId = sessionId;
402    }
403    int callingpid = IPCThreadState::self()->getCallingPid();
404    int mypid = getpid();
405    if (uid == -1 || (callingpid != mypid)) {
406        mClientUid = IPCThreadState::self()->getCallingUid();
407    } else {
408        mClientUid = uid;
409    }
410    if (pid == -1 || (callingpid != mypid)) {
411        mClientPid = callingpid;
412    } else {
413        mClientPid = pid;
414    }
415    mAuxEffectId = 0;
416    mFlags = flags;
417    mCbf = cbf;
418
419    if (cbf != NULL) {
420        mAudioTrackThread = new AudioTrackThread(*this, threadCanCallJava);
421        mAudioTrackThread->run("AudioTrack", ANDROID_PRIORITY_AUDIO, 0 /*stack*/);
422        // thread begins in paused state, and will not reference us until start()
423    }
424
425    // create the IAudioTrack
426    status_t status = createTrack_l();
427
428    if (status != NO_ERROR) {
429        if (mAudioTrackThread != 0) {
430            mAudioTrackThread->requestExit();   // see comment in AudioTrack.h
431            mAudioTrackThread->requestExitAndWait();
432            mAudioTrackThread.clear();
433        }
434        return status;
435    }
436
437    mStatus = NO_ERROR;
438    mState = STATE_STOPPED;
439    mUserData = user;
440    mLoopCount = 0;
441    mLoopStart = 0;
442    mLoopEnd = 0;
443    mLoopCountNotified = 0;
444    mMarkerPosition = 0;
445    mMarkerReached = false;
446    mNewPosition = 0;
447    mUpdatePeriod = 0;
448    mServer = 0;
449    mPosition = 0;
450    mReleased = 0;
451    mStartUs = 0;
452    AudioSystem::acquireAudioSessionId(mSessionId, mClientPid);
453    mSequence = 1;
454    mObservedSequence = mSequence;
455    mInUnderrun = false;
456
457    return NO_ERROR;
458}
459
460// -------------------------------------------------------------------------
461
462status_t AudioTrack::start()
463{
464    AutoMutex lock(mLock);
465
466    if (mState == STATE_ACTIVE) {
467        return INVALID_OPERATION;
468    }
469
470    mInUnderrun = true;
471
472    State previousState = mState;
473    if (previousState == STATE_PAUSED_STOPPING) {
474        mState = STATE_STOPPING;
475    } else {
476        mState = STATE_ACTIVE;
477    }
478    (void) updateAndGetPosition_l();
479    if (previousState == STATE_STOPPED || previousState == STATE_FLUSHED) {
480        // reset current position as seen by client to 0
481        mPosition = 0;
482        // For offloaded tracks, we don't know if the hardware counters are really zero here,
483        // since the flush is asynchronous and stop may not fully drain.
484        // We save the time when the track is started to later verify whether
485        // the counters are realistic (i.e. start from zero after this time).
486        mStartUs = getNowUs();
487
488        // force refresh of remaining frames by processAudioBuffer() as last
489        // write before stop could be partial.
490        mRefreshRemaining = true;
491    }
492    mNewPosition = mPosition + mUpdatePeriod;
493    int32_t flags = android_atomic_and(~CBLK_DISABLED, &mCblk->mFlags);
494
495    sp<AudioTrackThread> t = mAudioTrackThread;
496    if (t != 0) {
497        if (previousState == STATE_STOPPING) {
498            mProxy->interrupt();
499        } else {
500            t->resume();
501        }
502    } else {
503        mPreviousPriority = getpriority(PRIO_PROCESS, 0);
504        get_sched_policy(0, &mPreviousSchedulingGroup);
505        androidSetThreadPriority(0, ANDROID_PRIORITY_AUDIO);
506    }
507
508    status_t status = NO_ERROR;
509    if (!(flags & CBLK_INVALID)) {
510        status = mAudioTrack->start();
511        if (status == DEAD_OBJECT) {
512            flags |= CBLK_INVALID;
513        }
514    }
515    if (flags & CBLK_INVALID) {
516        status = restoreTrack_l("start");
517    }
518
519    if (status != NO_ERROR) {
520        ALOGE("start() status %d", status);
521        mState = previousState;
522        if (t != 0) {
523            if (previousState != STATE_STOPPING) {
524                t->pause();
525            }
526        } else {
527            setpriority(PRIO_PROCESS, 0, mPreviousPriority);
528            set_sched_policy(0, mPreviousSchedulingGroup);
529        }
530    }
531
532    return status;
533}
534
535void AudioTrack::stop()
536{
537    AutoMutex lock(mLock);
538    if (mState != STATE_ACTIVE && mState != STATE_PAUSED) {
539        return;
540    }
541
542    if (isOffloaded_l()) {
543        mState = STATE_STOPPING;
544    } else {
545        mState = STATE_STOPPED;
546        mReleased = 0;
547    }
548
549    mProxy->interrupt();
550    mAudioTrack->stop();
551    // the playback head position will reset to 0, so if a marker is set, we need
552    // to activate it again
553    mMarkerReached = false;
554
555    if (mSharedBuffer != 0) {
556        // clear buffer position and loop count.
557        mStaticProxy->setBufferPositionAndLoop(0 /* position */,
558                0 /* loopStart */, 0 /* loopEnd */, 0 /* loopCount */);
559    }
560
561    sp<AudioTrackThread> t = mAudioTrackThread;
562    if (t != 0) {
563        if (!isOffloaded_l()) {
564            t->pause();
565        }
566    } else {
567        setpriority(PRIO_PROCESS, 0, mPreviousPriority);
568        set_sched_policy(0, mPreviousSchedulingGroup);
569    }
570}
571
572bool AudioTrack::stopped() const
573{
574    AutoMutex lock(mLock);
575    return mState != STATE_ACTIVE;
576}
577
578void AudioTrack::flush()
579{
580    if (mSharedBuffer != 0) {
581        return;
582    }
583    AutoMutex lock(mLock);
584    if (mState == STATE_ACTIVE || mState == STATE_FLUSHED) {
585        return;
586    }
587    flush_l();
588}
589
590void AudioTrack::flush_l()
591{
592    ALOG_ASSERT(mState != STATE_ACTIVE);
593
594    // clear playback marker and periodic update counter
595    mMarkerPosition = 0;
596    mMarkerReached = false;
597    mUpdatePeriod = 0;
598    mRefreshRemaining = true;
599
600    mState = STATE_FLUSHED;
601    mReleased = 0;
602    if (isOffloaded_l()) {
603        mProxy->interrupt();
604    }
605    mProxy->flush();
606    mAudioTrack->flush();
607}
608
609void AudioTrack::pause()
610{
611    AutoMutex lock(mLock);
612    if (mState == STATE_ACTIVE) {
613        mState = STATE_PAUSED;
614    } else if (mState == STATE_STOPPING) {
615        mState = STATE_PAUSED_STOPPING;
616    } else {
617        return;
618    }
619    mProxy->interrupt();
620    mAudioTrack->pause();
621
622    if (isOffloaded_l()) {
623        if (mOutput != AUDIO_IO_HANDLE_NONE) {
624            // An offload output can be re-used between two audio tracks having
625            // the same configuration. A timestamp query for a paused track
626            // while the other is running would return an incorrect time.
627            // To fix this, cache the playback position on a pause() and return
628            // this time when requested until the track is resumed.
629
630            // OffloadThread sends HAL pause in its threadLoop. Time saved
631            // here can be slightly off.
632
633            // TODO: check return code for getRenderPosition.
634
635            uint32_t halFrames;
636            AudioSystem::getRenderPosition(mOutput, &halFrames, &mPausedPosition);
637            ALOGV("AudioTrack::pause for offload, cache current position %u", mPausedPosition);
638        }
639    }
640}
641
642status_t AudioTrack::setVolume(float left, float right)
643{
644    // This duplicates a test by AudioTrack JNI, but that is not the only caller
645    if (isnanf(left) || left < GAIN_FLOAT_ZERO || left > GAIN_FLOAT_UNITY ||
646            isnanf(right) || right < GAIN_FLOAT_ZERO || right > GAIN_FLOAT_UNITY) {
647        return BAD_VALUE;
648    }
649
650    AutoMutex lock(mLock);
651    mVolume[AUDIO_INTERLEAVE_LEFT] = left;
652    mVolume[AUDIO_INTERLEAVE_RIGHT] = right;
653
654    mProxy->setVolumeLR(gain_minifloat_pack(gain_from_float(left), gain_from_float(right)));
655
656    if (isOffloaded_l()) {
657        mAudioTrack->signal();
658    }
659    return NO_ERROR;
660}
661
662status_t AudioTrack::setVolume(float volume)
663{
664    return setVolume(volume, volume);
665}
666
667status_t AudioTrack::setAuxEffectSendLevel(float level)
668{
669    // This duplicates a test by AudioTrack JNI, but that is not the only caller
670    if (isnanf(level) || level < GAIN_FLOAT_ZERO || level > GAIN_FLOAT_UNITY) {
671        return BAD_VALUE;
672    }
673
674    AutoMutex lock(mLock);
675    mSendLevel = level;
676    mProxy->setSendLevel(level);
677
678    return NO_ERROR;
679}
680
681void AudioTrack::getAuxEffectSendLevel(float* level) const
682{
683    if (level != NULL) {
684        *level = mSendLevel;
685    }
686}
687
688status_t AudioTrack::setSampleRate(uint32_t rate)
689{
690    AutoMutex lock(mLock);
691    if (rate == mSampleRate) {
692        return NO_ERROR;
693    }
694    if (mIsTimed || isOffloadedOrDirect_l() || (mFlags & AUDIO_OUTPUT_FLAG_FAST)) {
695        return INVALID_OPERATION;
696    }
697    if (mOutput == AUDIO_IO_HANDLE_NONE) {
698        return NO_INIT;
699    }
700    // NOTE: it is theoretically possible, but highly unlikely, that a device change
701    // could mean a previously allowed sampling rate is no longer allowed.
702    uint32_t afSamplingRate;
703    if (AudioSystem::getSamplingRate(mOutput, &afSamplingRate) != NO_ERROR) {
704        return NO_INIT;
705    }
706    if (rate == 0 || rate > afSamplingRate * AUDIO_RESAMPLER_DOWN_RATIO_MAX) {
707        return BAD_VALUE;
708    }
709    // TODO: Should we also check if the buffer size is compatible?
710
711    mSampleRate = rate;
712    mProxy->setSampleRate(rate);
713
714    return NO_ERROR;
715}
716
717uint32_t AudioTrack::getSampleRate() const
718{
719    if (mIsTimed) {
720        return 0;
721    }
722
723    AutoMutex lock(mLock);
724
725    // sample rate can be updated during playback by the offloaded decoder so we need to
726    // query the HAL and update if needed.
727// FIXME use Proxy return channel to update the rate from server and avoid polling here
728    if (isOffloadedOrDirect_l()) {
729        if (mOutput != AUDIO_IO_HANDLE_NONE) {
730            uint32_t sampleRate = 0;
731            status_t status = AudioSystem::getSamplingRate(mOutput, &sampleRate);
732            if (status == NO_ERROR) {
733                mSampleRate = sampleRate;
734            }
735        }
736    }
737    return mSampleRate;
738}
739
740status_t AudioTrack::setPlaybackRate(float speed, float pitch)
741{
742    if (speed < AUDIO_TIMESTRETCH_SPEED_MIN
743            || speed > AUDIO_TIMESTRETCH_SPEED_MAX
744            || pitch < AUDIO_TIMESTRETCH_PITCH_MIN
745            || pitch > AUDIO_TIMESTRETCH_PITCH_MAX) {
746        return BAD_VALUE;
747    }
748    AutoMutex lock(mLock);
749    if (speed == mSpeed && pitch == mPitch) {
750        return NO_ERROR;
751    }
752    if (mIsTimed || isOffloadedOrDirect_l()) {
753        return INVALID_OPERATION;
754    }
755    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
756        return INVALID_OPERATION;
757    }
758    // Check if the buffer size is compatible.
759    if (!isSampleRateSpeedAllowed_l(mSampleRate, speed)) {
760        ALOGV("setPlaybackRate(%f, %f) failed", speed, pitch);
761        return BAD_VALUE;
762    }
763    mSpeed = speed;
764    mPitch = pitch;
765    mProxy->setPlaybackRate(speed, pitch);
766    return NO_ERROR;
767}
768
769void AudioTrack::getPlaybackRate(float *speed, float *pitch) const
770{
771    AutoMutex lock(mLock);
772    *speed = mSpeed;
773    *pitch = mPitch;
774}
775
776status_t AudioTrack::setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount)
777{
778    if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
779        return INVALID_OPERATION;
780    }
781
782    if (loopCount == 0) {
783        ;
784    } else if (loopCount >= -1 && loopStart < loopEnd && loopEnd <= mFrameCount &&
785            loopEnd - loopStart >= MIN_LOOP) {
786        ;
787    } else {
788        return BAD_VALUE;
789    }
790
791    AutoMutex lock(mLock);
792    // See setPosition() regarding setting parameters such as loop points or position while active
793    if (mState == STATE_ACTIVE) {
794        return INVALID_OPERATION;
795    }
796    setLoop_l(loopStart, loopEnd, loopCount);
797    return NO_ERROR;
798}
799
800void AudioTrack::setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount)
801{
802    // We do not update the periodic notification point.
803    // mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
804    mLoopCount = loopCount;
805    mLoopEnd = loopEnd;
806    mLoopStart = loopStart;
807    mLoopCountNotified = loopCount;
808    mStaticProxy->setLoop(loopStart, loopEnd, loopCount);
809
810    // Waking the AudioTrackThread is not needed as this cannot be called when active.
811}
812
813status_t AudioTrack::setMarkerPosition(uint32_t marker)
814{
815    // The only purpose of setting marker position is to get a callback
816    if (mCbf == NULL || isOffloadedOrDirect()) {
817        return INVALID_OPERATION;
818    }
819
820    AutoMutex lock(mLock);
821    mMarkerPosition = marker;
822    mMarkerReached = false;
823
824    sp<AudioTrackThread> t = mAudioTrackThread;
825    if (t != 0) {
826        t->wake();
827    }
828    return NO_ERROR;
829}
830
831status_t AudioTrack::getMarkerPosition(uint32_t *marker) const
832{
833    if (isOffloadedOrDirect()) {
834        return INVALID_OPERATION;
835    }
836    if (marker == NULL) {
837        return BAD_VALUE;
838    }
839
840    AutoMutex lock(mLock);
841    *marker = mMarkerPosition;
842
843    return NO_ERROR;
844}
845
846status_t AudioTrack::setPositionUpdatePeriod(uint32_t updatePeriod)
847{
848    // The only purpose of setting position update period is to get a callback
849    if (mCbf == NULL || isOffloadedOrDirect()) {
850        return INVALID_OPERATION;
851    }
852
853    AutoMutex lock(mLock);
854    mNewPosition = updateAndGetPosition_l() + updatePeriod;
855    mUpdatePeriod = updatePeriod;
856
857    sp<AudioTrackThread> t = mAudioTrackThread;
858    if (t != 0) {
859        t->wake();
860    }
861    return NO_ERROR;
862}
863
864status_t AudioTrack::getPositionUpdatePeriod(uint32_t *updatePeriod) const
865{
866    if (isOffloadedOrDirect()) {
867        return INVALID_OPERATION;
868    }
869    if (updatePeriod == NULL) {
870        return BAD_VALUE;
871    }
872
873    AutoMutex lock(mLock);
874    *updatePeriod = mUpdatePeriod;
875
876    return NO_ERROR;
877}
878
879status_t AudioTrack::setPosition(uint32_t position)
880{
881    if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
882        return INVALID_OPERATION;
883    }
884    if (position > mFrameCount) {
885        return BAD_VALUE;
886    }
887
888    AutoMutex lock(mLock);
889    // Currently we require that the player is inactive before setting parameters such as position
890    // or loop points.  Otherwise, there could be a race condition: the application could read the
891    // current position, compute a new position or loop parameters, and then set that position or
892    // loop parameters but it would do the "wrong" thing since the position has continued to advance
893    // in the mean time.  If we ever provide a sequencer in server, we could allow a way for the app
894    // to specify how it wants to handle such scenarios.
895    if (mState == STATE_ACTIVE) {
896        return INVALID_OPERATION;
897    }
898    // After setting the position, use full update period before notification.
899    mNewPosition = updateAndGetPosition_l() + mUpdatePeriod;
900    mStaticProxy->setBufferPosition(position);
901
902    // Waking the AudioTrackThread is not needed as this cannot be called when active.
903    return NO_ERROR;
904}
905
906status_t AudioTrack::getPosition(uint32_t *position)
907{
908    if (position == NULL) {
909        return BAD_VALUE;
910    }
911
912    AutoMutex lock(mLock);
913    if (isOffloadedOrDirect_l()) {
914        uint32_t dspFrames = 0;
915
916        if (isOffloaded_l() && ((mState == STATE_PAUSED) || (mState == STATE_PAUSED_STOPPING))) {
917            ALOGV("getPosition called in paused state, return cached position %u", mPausedPosition);
918            *position = mPausedPosition;
919            return NO_ERROR;
920        }
921
922        if (mOutput != AUDIO_IO_HANDLE_NONE) {
923            uint32_t halFrames;
924            AudioSystem::getRenderPosition(mOutput, &halFrames, &dspFrames);
925        }
926        // FIXME: dspFrames may not be zero in (mState == STATE_STOPPED || mState == STATE_FLUSHED)
927        // due to hardware latency. We leave this behavior for now.
928        *position = dspFrames;
929    } else {
930        if (mCblk->mFlags & CBLK_INVALID) {
931            restoreTrack_l("getPosition");
932        }
933
934        // IAudioTrack::stop() isn't synchronous; we don't know when presentation completes
935        *position = (mState == STATE_STOPPED || mState == STATE_FLUSHED) ?
936                0 : updateAndGetPosition_l();
937    }
938    return NO_ERROR;
939}
940
941status_t AudioTrack::getBufferPosition(uint32_t *position)
942{
943    if (mSharedBuffer == 0 || mIsTimed) {
944        return INVALID_OPERATION;
945    }
946    if (position == NULL) {
947        return BAD_VALUE;
948    }
949
950    AutoMutex lock(mLock);
951    *position = mStaticProxy->getBufferPosition();
952    return NO_ERROR;
953}
954
955status_t AudioTrack::reload()
956{
957    if (mSharedBuffer == 0 || mIsTimed || isOffloadedOrDirect()) {
958        return INVALID_OPERATION;
959    }
960
961    AutoMutex lock(mLock);
962    // See setPosition() regarding setting parameters such as loop points or position while active
963    if (mState == STATE_ACTIVE) {
964        return INVALID_OPERATION;
965    }
966    mNewPosition = mUpdatePeriod;
967    (void) updateAndGetPosition_l();
968    mPosition = 0;
969#if 0
970    // The documentation is not clear on the behavior of reload() and the restoration
971    // of loop count. Historically we have not restored loop count, start, end,
972    // but it makes sense if one desires to repeat playing a particular sound.
973    if (mLoopCount != 0) {
974        mLoopCountNotified = mLoopCount;
975        mStaticProxy->setLoop(mLoopStart, mLoopEnd, mLoopCount);
976    }
977#endif
978    mStaticProxy->setBufferPosition(0);
979    return NO_ERROR;
980}
981
982audio_io_handle_t AudioTrack::getOutput() const
983{
984    AutoMutex lock(mLock);
985    return mOutput;
986}
987
988status_t AudioTrack::setOutputDevice(audio_port_handle_t deviceId) {
989    AutoMutex lock(mLock);
990    if (mSelectedDeviceId != deviceId) {
991        mSelectedDeviceId = deviceId;
992        return restoreTrack_l("setOutputDevice() restart");
993    } else {
994        return NO_ERROR;
995    }
996}
997
998audio_port_handle_t AudioTrack::getOutputDevice() {
999    AutoMutex lock(mLock);
1000    return mSelectedDeviceId;
1001}
1002
1003status_t AudioTrack::attachAuxEffect(int effectId)
1004{
1005    AutoMutex lock(mLock);
1006    status_t status = mAudioTrack->attachAuxEffect(effectId);
1007    if (status == NO_ERROR) {
1008        mAuxEffectId = effectId;
1009    }
1010    return status;
1011}
1012
1013audio_stream_type_t AudioTrack::streamType() const
1014{
1015    if (mStreamType == AUDIO_STREAM_DEFAULT) {
1016        return audio_attributes_to_stream_type(&mAttributes);
1017    }
1018    return mStreamType;
1019}
1020
1021// -------------------------------------------------------------------------
1022
1023// must be called with mLock held
1024status_t AudioTrack::createTrack_l()
1025{
1026    const sp<IAudioFlinger>& audioFlinger = AudioSystem::get_audio_flinger();
1027    if (audioFlinger == 0) {
1028        ALOGE("Could not get audioflinger");
1029        return NO_INIT;
1030    }
1031
1032    audio_io_handle_t output;
1033    audio_stream_type_t streamType = mStreamType;
1034    audio_attributes_t *attr = (mStreamType == AUDIO_STREAM_DEFAULT) ? &mAttributes : NULL;
1035
1036    status_t status;
1037    status = AudioSystem::getOutputForAttr(attr, &output,
1038                                           (audio_session_t)mSessionId, &streamType,
1039                                           mSampleRate, mFormat, mChannelMask,
1040                                           mFlags, mSelectedDeviceId, mOffloadInfo);
1041
1042    if (status != NO_ERROR || output == AUDIO_IO_HANDLE_NONE) {
1043        ALOGE("Could not get audio output for session %d, stream type %d, usage %d, sample rate %u, format %#x,"
1044              " channel mask %#x, flags %#x",
1045              mSessionId, streamType, mAttributes.usage, mSampleRate, mFormat, mChannelMask, mFlags);
1046        return BAD_VALUE;
1047    }
1048    {
1049    // Now that we have a reference to an I/O handle and have not yet handed it off to AudioFlinger,
1050    // we must release it ourselves if anything goes wrong.
1051
1052    // Not all of these values are needed under all conditions, but it is easier to get them all
1053
1054    uint32_t afLatency;
1055    status = AudioSystem::getLatency(output, &afLatency);
1056    if (status != NO_ERROR) {
1057        ALOGE("getLatency(%d) failed status %d", output, status);
1058        goto release;
1059    }
1060    ALOGV("createTrack_l() output %d afLatency %u", output, afLatency);
1061
1062    size_t afFrameCount;
1063    status = AudioSystem::getFrameCount(output, &afFrameCount);
1064    if (status != NO_ERROR) {
1065        ALOGE("getFrameCount(output=%d) status %d", output, status);
1066        goto release;
1067    }
1068
1069    uint32_t afSampleRate;
1070    status = AudioSystem::getSamplingRate(output, &afSampleRate);
1071    if (status != NO_ERROR) {
1072        ALOGE("getSamplingRate(output=%d) status %d", output, status);
1073        goto release;
1074    }
1075    if (mSampleRate == 0) {
1076        mSampleRate = afSampleRate;
1077    }
1078    // Client decides whether the track is TIMED (see below), but can only express a preference
1079    // for FAST.  Server will perform additional tests.
1080    if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) && !((
1081            // either of these use cases:
1082            // use case 1: shared buffer
1083            (mSharedBuffer != 0) ||
1084            // use case 2: callback transfer mode
1085            (mTransfer == TRANSFER_CALLBACK) ||
1086            // use case 3: obtain/release mode
1087            (mTransfer == TRANSFER_OBTAIN)) &&
1088            // matching sample rate
1089            (mSampleRate == afSampleRate))) {
1090        ALOGW("AUDIO_OUTPUT_FLAG_FAST denied by client; transfer %d, track %u Hz, output %u Hz",
1091                mTransfer, mSampleRate, afSampleRate);
1092        // once denied, do not request again if IAudioTrack is re-created
1093        mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1094    }
1095
1096    // The client's AudioTrack buffer is divided into n parts for purpose of wakeup by server, where
1097    //  n = 1   fast track with single buffering; nBuffering is ignored
1098    //  n = 2   fast track with double buffering
1099    //  n = 2   normal track, (including those with sample rate conversion)
1100    //  n >= 3  very high latency or very small notification interval (unused).
1101    const uint32_t nBuffering = 2;
1102
1103    mNotificationFramesAct = mNotificationFramesReq;
1104
1105    size_t frameCount = mReqFrameCount;
1106    if (!audio_is_linear_pcm(mFormat)) {
1107
1108        if (mSharedBuffer != 0) {
1109            // Same comment as below about ignoring frameCount parameter for set()
1110            frameCount = mSharedBuffer->size();
1111        } else if (frameCount == 0) {
1112            frameCount = afFrameCount;
1113        }
1114        if (mNotificationFramesAct != frameCount) {
1115            mNotificationFramesAct = frameCount;
1116        }
1117    } else if (mSharedBuffer != 0) {
1118        // FIXME: Ensure client side memory buffers need
1119        // not have additional alignment beyond sample
1120        // (e.g. 16 bit stereo accessed as 32 bit frame).
1121        size_t alignment = audio_bytes_per_sample(mFormat);
1122        if (alignment & 1) {
1123            // for AUDIO_FORMAT_PCM_24_BIT_PACKED (not exposed through Java).
1124            alignment = 1;
1125        }
1126        if (mChannelCount > 1) {
1127            // More than 2 channels does not require stronger alignment than stereo
1128            alignment <<= 1;
1129        }
1130        if (((uintptr_t)mSharedBuffer->pointer() & (alignment - 1)) != 0) {
1131            ALOGE("Invalid buffer alignment: address %p, channel count %u",
1132                    mSharedBuffer->pointer(), mChannelCount);
1133            status = BAD_VALUE;
1134            goto release;
1135        }
1136
1137        // When initializing a shared buffer AudioTrack via constructors,
1138        // there's no frameCount parameter.
1139        // But when initializing a shared buffer AudioTrack via set(),
1140        // there _is_ a frameCount parameter.  We silently ignore it.
1141        frameCount = mSharedBuffer->size() / mFrameSize;
1142    } else {
1143        // For fast tracks the frame count calculations and checks are done by server
1144
1145        if ((mFlags & AUDIO_OUTPUT_FLAG_FAST) == 0) {
1146            // for normal tracks precompute the frame count based on speed.
1147            const size_t minFrameCount = calculateMinFrameCount(
1148                    afLatency, afFrameCount, afSampleRate, mSampleRate, mSpeed);
1149            if (frameCount < minFrameCount) {
1150                frameCount = minFrameCount;
1151            }
1152        }
1153    }
1154
1155    IAudioFlinger::track_flags_t trackFlags = IAudioFlinger::TRACK_DEFAULT;
1156    if (mIsTimed) {
1157        trackFlags |= IAudioFlinger::TRACK_TIMED;
1158    }
1159
1160    pid_t tid = -1;
1161    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1162        trackFlags |= IAudioFlinger::TRACK_FAST;
1163        if (mAudioTrackThread != 0) {
1164            tid = mAudioTrackThread->getTid();
1165        }
1166    }
1167
1168    if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1169        trackFlags |= IAudioFlinger::TRACK_OFFLOAD;
1170    }
1171
1172    if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1173        trackFlags |= IAudioFlinger::TRACK_DIRECT;
1174    }
1175
1176    size_t temp = frameCount;   // temp may be replaced by a revised value of frameCount,
1177                                // but we will still need the original value also
1178    int originalSessionId = mSessionId;
1179    sp<IAudioTrack> track = audioFlinger->createTrack(streamType,
1180                                                      mSampleRate,
1181                                                      mFormat,
1182                                                      mChannelMask,
1183                                                      &temp,
1184                                                      &trackFlags,
1185                                                      mSharedBuffer,
1186                                                      output,
1187                                                      tid,
1188                                                      &mSessionId,
1189                                                      mClientUid,
1190                                                      &status);
1191    ALOGE_IF(originalSessionId != AUDIO_SESSION_ALLOCATE && mSessionId != originalSessionId,
1192            "session ID changed from %d to %d", originalSessionId, mSessionId);
1193
1194    if (status != NO_ERROR) {
1195        ALOGE("AudioFlinger could not create track, status: %d", status);
1196        goto release;
1197    }
1198    ALOG_ASSERT(track != 0);
1199
1200    // AudioFlinger now owns the reference to the I/O handle,
1201    // so we are no longer responsible for releasing it.
1202
1203    sp<IMemory> iMem = track->getCblk();
1204    if (iMem == 0) {
1205        ALOGE("Could not get control block");
1206        return NO_INIT;
1207    }
1208    void *iMemPointer = iMem->pointer();
1209    if (iMemPointer == NULL) {
1210        ALOGE("Could not get control block pointer");
1211        return NO_INIT;
1212    }
1213    // invariant that mAudioTrack != 0 is true only after set() returns successfully
1214    if (mAudioTrack != 0) {
1215        IInterface::asBinder(mAudioTrack)->unlinkToDeath(mDeathNotifier, this);
1216        mDeathNotifier.clear();
1217    }
1218    mAudioTrack = track;
1219    mCblkMemory = iMem;
1220    IPCThreadState::self()->flushCommands();
1221
1222    audio_track_cblk_t* cblk = static_cast<audio_track_cblk_t*>(iMemPointer);
1223    mCblk = cblk;
1224    // note that temp is the (possibly revised) value of frameCount
1225    if (temp < frameCount || (frameCount == 0 && temp == 0)) {
1226        // In current design, AudioTrack client checks and ensures frame count validity before
1227        // passing it to AudioFlinger so AudioFlinger should not return a different value except
1228        // for fast track as it uses a special method of assigning frame count.
1229        ALOGW("Requested frameCount %zu but received frameCount %zu", frameCount, temp);
1230    }
1231    frameCount = temp;
1232
1233    mAwaitBoost = false;
1234    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
1235        if (trackFlags & IAudioFlinger::TRACK_FAST) {
1236            ALOGV("AUDIO_OUTPUT_FLAG_FAST successful; frameCount %zu", frameCount);
1237            mAwaitBoost = true;
1238        } else {
1239            ALOGV("AUDIO_OUTPUT_FLAG_FAST denied by server; frameCount %zu", frameCount);
1240            // once denied, do not request again if IAudioTrack is re-created
1241            mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_FAST);
1242        }
1243    }
1244    if (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
1245        if (trackFlags & IAudioFlinger::TRACK_OFFLOAD) {
1246            ALOGV("AUDIO_OUTPUT_FLAG_OFFLOAD successful");
1247        } else {
1248            ALOGW("AUDIO_OUTPUT_FLAG_OFFLOAD denied by server");
1249            mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1250            // FIXME This is a warning, not an error, so don't return error status
1251            //return NO_INIT;
1252        }
1253    }
1254    if (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1255        if (trackFlags & IAudioFlinger::TRACK_DIRECT) {
1256            ALOGV("AUDIO_OUTPUT_FLAG_DIRECT successful");
1257        } else {
1258            ALOGW("AUDIO_OUTPUT_FLAG_DIRECT denied by server");
1259            mFlags = (audio_output_flags_t) (mFlags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1260            // FIXME This is a warning, not an error, so don't return error status
1261            //return NO_INIT;
1262        }
1263    }
1264    // Make sure that application is notified with sufficient margin before underrun
1265    if (mSharedBuffer == 0 && audio_is_linear_pcm(mFormat)) {
1266        // Theoretically double-buffering is not required for fast tracks,
1267        // due to tighter scheduling.  But in practice, to accommodate kernels with
1268        // scheduling jitter, and apps with computation jitter, we use double-buffering
1269        // for fast tracks just like normal streaming tracks.
1270        if (mNotificationFramesAct == 0 || mNotificationFramesAct > frameCount / nBuffering) {
1271            mNotificationFramesAct = frameCount / nBuffering;
1272        }
1273    }
1274
1275    // We retain a copy of the I/O handle, but don't own the reference
1276    mOutput = output;
1277    mRefreshRemaining = true;
1278
1279    // Starting address of buffers in shared memory.  If there is a shared buffer, buffers
1280    // is the value of pointer() for the shared buffer, otherwise buffers points
1281    // immediately after the control block.  This address is for the mapping within client
1282    // address space.  AudioFlinger::TrackBase::mBuffer is for the server address space.
1283    void* buffers;
1284    if (mSharedBuffer == 0) {
1285        buffers = cblk + 1;
1286    } else {
1287        buffers = mSharedBuffer->pointer();
1288        if (buffers == NULL) {
1289            ALOGE("Could not get buffer pointer");
1290            return NO_INIT;
1291        }
1292    }
1293
1294    mAudioTrack->attachAuxEffect(mAuxEffectId);
1295    // FIXME doesn't take into account speed or future sample rate changes (until restoreTrack)
1296    // FIXME don't believe this lie
1297    mLatency = afLatency + (1000*frameCount) / mSampleRate;
1298
1299    mFrameCount = frameCount;
1300    // If IAudioTrack is re-created, don't let the requested frameCount
1301    // decrease.  This can confuse clients that cache frameCount().
1302    if (frameCount > mReqFrameCount) {
1303        mReqFrameCount = frameCount;
1304    }
1305
1306    // update proxy
1307    if (mSharedBuffer == 0) {
1308        mStaticProxy.clear();
1309        mProxy = new AudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
1310    } else {
1311        mStaticProxy = new StaticAudioTrackClientProxy(cblk, buffers, frameCount, mFrameSize);
1312        mProxy = mStaticProxy;
1313    }
1314
1315    mProxy->setVolumeLR(gain_minifloat_pack(
1316            gain_from_float(mVolume[AUDIO_INTERLEAVE_LEFT]),
1317            gain_from_float(mVolume[AUDIO_INTERLEAVE_RIGHT])));
1318
1319    mProxy->setSendLevel(mSendLevel);
1320    mProxy->setSampleRate(mSampleRate);
1321    mProxy->setPlaybackRate(mSpeed, mPitch);
1322    mProxy->setMinimum(mNotificationFramesAct);
1323
1324    mDeathNotifier = new DeathNotifier(this);
1325    IInterface::asBinder(mAudioTrack)->linkToDeath(mDeathNotifier, this);
1326
1327    return NO_ERROR;
1328    }
1329
1330release:
1331    AudioSystem::releaseOutput(output, streamType, (audio_session_t)mSessionId);
1332    if (status == NO_ERROR) {
1333        status = NO_INIT;
1334    }
1335    return status;
1336}
1337
1338status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, int32_t waitCount, size_t *nonContig)
1339{
1340    if (audioBuffer == NULL) {
1341        return BAD_VALUE;
1342    }
1343    if (mTransfer != TRANSFER_OBTAIN) {
1344        audioBuffer->frameCount = 0;
1345        audioBuffer->size = 0;
1346        audioBuffer->raw = NULL;
1347        return INVALID_OPERATION;
1348    }
1349
1350    const struct timespec *requested;
1351    struct timespec timeout;
1352    if (waitCount == -1) {
1353        requested = &ClientProxy::kForever;
1354    } else if (waitCount == 0) {
1355        requested = &ClientProxy::kNonBlocking;
1356    } else if (waitCount > 0) {
1357        long long ms = WAIT_PERIOD_MS * (long long) waitCount;
1358        timeout.tv_sec = ms / 1000;
1359        timeout.tv_nsec = (int) (ms % 1000) * 1000000;
1360        requested = &timeout;
1361    } else {
1362        ALOGE("%s invalid waitCount %d", __func__, waitCount);
1363        requested = NULL;
1364    }
1365    return obtainBuffer(audioBuffer, requested, NULL /*elapsed*/, nonContig);
1366}
1367
1368status_t AudioTrack::obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
1369        struct timespec *elapsed, size_t *nonContig)
1370{
1371    // previous and new IAudioTrack sequence numbers are used to detect track re-creation
1372    uint32_t oldSequence = 0;
1373    uint32_t newSequence;
1374
1375    Proxy::Buffer buffer;
1376    status_t status = NO_ERROR;
1377
1378    static const int32_t kMaxTries = 5;
1379    int32_t tryCounter = kMaxTries;
1380
1381    do {
1382        // obtainBuffer() is called with mutex unlocked, so keep extra references to these fields to
1383        // keep them from going away if another thread re-creates the track during obtainBuffer()
1384        sp<AudioTrackClientProxy> proxy;
1385        sp<IMemory> iMem;
1386
1387        {   // start of lock scope
1388            AutoMutex lock(mLock);
1389
1390            newSequence = mSequence;
1391            // did previous obtainBuffer() fail due to media server death or voluntary invalidation?
1392            if (status == DEAD_OBJECT) {
1393                // re-create track, unless someone else has already done so
1394                if (newSequence == oldSequence) {
1395                    status = restoreTrack_l("obtainBuffer");
1396                    if (status != NO_ERROR) {
1397                        buffer.mFrameCount = 0;
1398                        buffer.mRaw = NULL;
1399                        buffer.mNonContig = 0;
1400                        break;
1401                    }
1402                }
1403            }
1404            oldSequence = newSequence;
1405
1406            // Keep the extra references
1407            proxy = mProxy;
1408            iMem = mCblkMemory;
1409
1410            if (mState == STATE_STOPPING) {
1411                status = -EINTR;
1412                buffer.mFrameCount = 0;
1413                buffer.mRaw = NULL;
1414                buffer.mNonContig = 0;
1415                break;
1416            }
1417
1418            // Non-blocking if track is stopped or paused
1419            if (mState != STATE_ACTIVE) {
1420                requested = &ClientProxy::kNonBlocking;
1421            }
1422
1423        }   // end of lock scope
1424
1425        buffer.mFrameCount = audioBuffer->frameCount;
1426        // FIXME starts the requested timeout and elapsed over from scratch
1427        status = proxy->obtainBuffer(&buffer, requested, elapsed);
1428
1429    } while ((status == DEAD_OBJECT) && (tryCounter-- > 0));
1430
1431    audioBuffer->frameCount = buffer.mFrameCount;
1432    audioBuffer->size = buffer.mFrameCount * mFrameSize;
1433    audioBuffer->raw = buffer.mRaw;
1434    if (nonContig != NULL) {
1435        *nonContig = buffer.mNonContig;
1436    }
1437    return status;
1438}
1439
1440void AudioTrack::releaseBuffer(const Buffer* audioBuffer)
1441{
1442    // FIXME add error checking on mode, by adding an internal version
1443    if (mTransfer == TRANSFER_SHARED) {
1444        return;
1445    }
1446
1447    size_t stepCount = audioBuffer->size / mFrameSize;
1448    if (stepCount == 0) {
1449        return;
1450    }
1451
1452    Proxy::Buffer buffer;
1453    buffer.mFrameCount = stepCount;
1454    buffer.mRaw = audioBuffer->raw;
1455
1456    AutoMutex lock(mLock);
1457    mReleased += stepCount;
1458    mInUnderrun = false;
1459    mProxy->releaseBuffer(&buffer);
1460
1461    // restart track if it was disabled by audioflinger due to previous underrun
1462    if (mState == STATE_ACTIVE) {
1463        audio_track_cblk_t* cblk = mCblk;
1464        if (android_atomic_and(~CBLK_DISABLED, &cblk->mFlags) & CBLK_DISABLED) {
1465            ALOGW("releaseBuffer() track %p disabled due to previous underrun, restarting", this);
1466            // FIXME ignoring status
1467            mAudioTrack->start();
1468        }
1469    }
1470}
1471
1472// -------------------------------------------------------------------------
1473
1474ssize_t AudioTrack::write(const void* buffer, size_t userSize, bool blocking)
1475{
1476    if (mTransfer != TRANSFER_SYNC || mIsTimed) {
1477        return INVALID_OPERATION;
1478    }
1479
1480    if (isDirect()) {
1481        AutoMutex lock(mLock);
1482        int32_t flags = android_atomic_and(
1483                            ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END),
1484                            &mCblk->mFlags);
1485        if (flags & CBLK_INVALID) {
1486            return DEAD_OBJECT;
1487        }
1488    }
1489
1490    if (ssize_t(userSize) < 0 || (buffer == NULL && userSize != 0)) {
1491        // Sanity-check: user is most-likely passing an error code, and it would
1492        // make the return value ambiguous (actualSize vs error).
1493        ALOGE("AudioTrack::write(buffer=%p, size=%zu (%zd)", buffer, userSize, userSize);
1494        return BAD_VALUE;
1495    }
1496
1497    size_t written = 0;
1498    Buffer audioBuffer;
1499
1500    while (userSize >= mFrameSize) {
1501        audioBuffer.frameCount = userSize / mFrameSize;
1502
1503        status_t err = obtainBuffer(&audioBuffer,
1504                blocking ? &ClientProxy::kForever : &ClientProxy::kNonBlocking);
1505        if (err < 0) {
1506            if (written > 0) {
1507                break;
1508            }
1509            return ssize_t(err);
1510        }
1511
1512        size_t toWrite = audioBuffer.size;
1513        memcpy(audioBuffer.i8, buffer, toWrite);
1514        buffer = ((const char *) buffer) + toWrite;
1515        userSize -= toWrite;
1516        written += toWrite;
1517
1518        releaseBuffer(&audioBuffer);
1519    }
1520
1521    return written;
1522}
1523
1524// -------------------------------------------------------------------------
1525
1526TimedAudioTrack::TimedAudioTrack() {
1527    mIsTimed = true;
1528}
1529
1530status_t TimedAudioTrack::allocateTimedBuffer(size_t size, sp<IMemory>* buffer)
1531{
1532    AutoMutex lock(mLock);
1533    status_t result = UNKNOWN_ERROR;
1534
1535#if 1
1536    // acquire a strong reference on the IMemory and IAudioTrack so that they cannot be destroyed
1537    // while we are accessing the cblk
1538    sp<IAudioTrack> audioTrack = mAudioTrack;
1539    sp<IMemory> iMem = mCblkMemory;
1540#endif
1541
1542    // If the track is not invalid already, try to allocate a buffer.  alloc
1543    // fails indicating that the server is dead, flag the track as invalid so
1544    // we can attempt to restore in just a bit.
1545    audio_track_cblk_t* cblk = mCblk;
1546    if (!(cblk->mFlags & CBLK_INVALID)) {
1547        result = mAudioTrack->allocateTimedBuffer(size, buffer);
1548        if (result == DEAD_OBJECT) {
1549            android_atomic_or(CBLK_INVALID, &cblk->mFlags);
1550        }
1551    }
1552
1553    // If the track is invalid at this point, attempt to restore it. and try the
1554    // allocation one more time.
1555    if (cblk->mFlags & CBLK_INVALID) {
1556        result = restoreTrack_l("allocateTimedBuffer");
1557
1558        if (result == NO_ERROR) {
1559            result = mAudioTrack->allocateTimedBuffer(size, buffer);
1560        }
1561    }
1562
1563    return result;
1564}
1565
1566status_t TimedAudioTrack::queueTimedBuffer(const sp<IMemory>& buffer,
1567                                           int64_t pts)
1568{
1569    status_t status = mAudioTrack->queueTimedBuffer(buffer, pts);
1570    {
1571        AutoMutex lock(mLock);
1572        audio_track_cblk_t* cblk = mCblk;
1573        // restart track if it was disabled by audioflinger due to previous underrun
1574        if (buffer->size() != 0 && status == NO_ERROR &&
1575                (mState == STATE_ACTIVE) && (cblk->mFlags & CBLK_DISABLED)) {
1576            android_atomic_and(~CBLK_DISABLED, &cblk->mFlags);
1577            ALOGW("queueTimedBuffer() track %p disabled, restarting", this);
1578            // FIXME ignoring status
1579            mAudioTrack->start();
1580        }
1581    }
1582    return status;
1583}
1584
1585status_t TimedAudioTrack::setMediaTimeTransform(const LinearTransform& xform,
1586                                                TargetTimeline target)
1587{
1588    return mAudioTrack->setMediaTimeTransform(xform, target);
1589}
1590
1591// -------------------------------------------------------------------------
1592
1593nsecs_t AudioTrack::processAudioBuffer()
1594{
1595    // Currently the AudioTrack thread is not created if there are no callbacks.
1596    // Would it ever make sense to run the thread, even without callbacks?
1597    // If so, then replace this by checks at each use for mCbf != NULL.
1598    LOG_ALWAYS_FATAL_IF(mCblk == NULL);
1599
1600    mLock.lock();
1601    if (mAwaitBoost) {
1602        mAwaitBoost = false;
1603        mLock.unlock();
1604        static const int32_t kMaxTries = 5;
1605        int32_t tryCounter = kMaxTries;
1606        uint32_t pollUs = 10000;
1607        do {
1608            int policy = sched_getscheduler(0);
1609            if (policy == SCHED_FIFO || policy == SCHED_RR) {
1610                break;
1611            }
1612            usleep(pollUs);
1613            pollUs <<= 1;
1614        } while (tryCounter-- > 0);
1615        if (tryCounter < 0) {
1616            ALOGE("did not receive expected priority boost on time");
1617        }
1618        // Run again immediately
1619        return 0;
1620    }
1621
1622    // Can only reference mCblk while locked
1623    int32_t flags = android_atomic_and(
1624        ~(CBLK_UNDERRUN | CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL | CBLK_BUFFER_END), &mCblk->mFlags);
1625
1626    // Check for track invalidation
1627    if (flags & CBLK_INVALID) {
1628        // for offloaded tracks restoreTrack_l() will just update the sequence and clear
1629        // AudioSystem cache. We should not exit here but after calling the callback so
1630        // that the upper layers can recreate the track
1631        if (!isOffloadedOrDirect_l() || (mSequence == mObservedSequence)) {
1632            status_t status = restoreTrack_l("processAudioBuffer");
1633            // after restoration, continue below to make sure that the loop and buffer events
1634            // are notified because they have been cleared from mCblk->mFlags above.
1635        }
1636    }
1637
1638    bool waitStreamEnd = mState == STATE_STOPPING;
1639    bool active = mState == STATE_ACTIVE;
1640
1641    // Manage underrun callback, must be done under lock to avoid race with releaseBuffer()
1642    bool newUnderrun = false;
1643    if (flags & CBLK_UNDERRUN) {
1644#if 0
1645        // Currently in shared buffer mode, when the server reaches the end of buffer,
1646        // the track stays active in continuous underrun state.  It's up to the application
1647        // to pause or stop the track, or set the position to a new offset within buffer.
1648        // This was some experimental code to auto-pause on underrun.   Keeping it here
1649        // in "if 0" so we can re-visit this if we add a real sequencer for shared memory content.
1650        if (mTransfer == TRANSFER_SHARED) {
1651            mState = STATE_PAUSED;
1652            active = false;
1653        }
1654#endif
1655        if (!mInUnderrun) {
1656            mInUnderrun = true;
1657            newUnderrun = true;
1658        }
1659    }
1660
1661    // Get current position of server
1662    size_t position = updateAndGetPosition_l();
1663
1664    // Manage marker callback
1665    bool markerReached = false;
1666    size_t markerPosition = mMarkerPosition;
1667    // FIXME fails for wraparound, need 64 bits
1668    if (!mMarkerReached && (markerPosition > 0) && (position >= markerPosition)) {
1669        mMarkerReached = markerReached = true;
1670    }
1671
1672    // Determine number of new position callback(s) that will be needed, while locked
1673    size_t newPosCount = 0;
1674    size_t newPosition = mNewPosition;
1675    size_t updatePeriod = mUpdatePeriod;
1676    // FIXME fails for wraparound, need 64 bits
1677    if (updatePeriod > 0 && position >= newPosition) {
1678        newPosCount = ((position - newPosition) / updatePeriod) + 1;
1679        mNewPosition += updatePeriod * newPosCount;
1680    }
1681
1682    // Cache other fields that will be needed soon
1683    uint32_t sampleRate = mSampleRate;
1684    float speed = mSpeed;
1685    uint32_t notificationFrames = mNotificationFramesAct;
1686    if (mRefreshRemaining) {
1687        mRefreshRemaining = false;
1688        mRemainingFrames = notificationFrames;
1689        mRetryOnPartialBuffer = false;
1690    }
1691    size_t misalignment = mProxy->getMisalignment();
1692    uint32_t sequence = mSequence;
1693    sp<AudioTrackClientProxy> proxy = mProxy;
1694
1695    // Determine the number of new loop callback(s) that will be needed, while locked.
1696    int loopCountNotifications = 0;
1697    uint32_t loopPeriod = 0; // time in frames for next EVENT_LOOP_END or EVENT_BUFFER_END
1698
1699    if (mLoopCount > 0) {
1700        int loopCount;
1701        size_t bufferPosition;
1702        mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1703        loopPeriod = ((loopCount > 0) ? mLoopEnd : mFrameCount) - bufferPosition;
1704        loopCountNotifications = min(mLoopCountNotified - loopCount, kMaxLoopCountNotifications);
1705        mLoopCountNotified = loopCount; // discard any excess notifications
1706    } else if (mLoopCount < 0) {
1707        // FIXME: We're not accurate with notification count and position with infinite looping
1708        // since loopCount from server side will always return -1 (we could decrement it).
1709        size_t bufferPosition = mStaticProxy->getBufferPosition();
1710        loopCountNotifications = int((flags & (CBLK_LOOP_CYCLE | CBLK_LOOP_FINAL)) != 0);
1711        loopPeriod = mLoopEnd - bufferPosition;
1712    } else if (/* mLoopCount == 0 && */ mSharedBuffer != 0) {
1713        size_t bufferPosition = mStaticProxy->getBufferPosition();
1714        loopPeriod = mFrameCount - bufferPosition;
1715    }
1716
1717    // These fields don't need to be cached, because they are assigned only by set():
1718    //     mTransfer, mCbf, mUserData, mFormat, mFrameSize, mFlags
1719    // mFlags is also assigned by createTrack_l(), but not the bit we care about.
1720
1721    mLock.unlock();
1722
1723    if (waitStreamEnd) {
1724        struct timespec timeout;
1725        timeout.tv_sec = WAIT_STREAM_END_TIMEOUT_SEC;
1726        timeout.tv_nsec = 0;
1727
1728        status_t status = proxy->waitStreamEndDone(&timeout);
1729        switch (status) {
1730        case NO_ERROR:
1731        case DEAD_OBJECT:
1732        case TIMED_OUT:
1733            mCbf(EVENT_STREAM_END, mUserData, NULL);
1734            {
1735                AutoMutex lock(mLock);
1736                // The previously assigned value of waitStreamEnd is no longer valid,
1737                // since the mutex has been unlocked and either the callback handler
1738                // or another thread could have re-started the AudioTrack during that time.
1739                waitStreamEnd = mState == STATE_STOPPING;
1740                if (waitStreamEnd) {
1741                    mState = STATE_STOPPED;
1742                    mReleased = 0;
1743                }
1744            }
1745            if (waitStreamEnd && status != DEAD_OBJECT) {
1746               return NS_INACTIVE;
1747            }
1748            break;
1749        }
1750        return 0;
1751    }
1752
1753    // perform callbacks while unlocked
1754    if (newUnderrun) {
1755        mCbf(EVENT_UNDERRUN, mUserData, NULL);
1756    }
1757    while (loopCountNotifications > 0) {
1758        mCbf(EVENT_LOOP_END, mUserData, NULL);
1759        --loopCountNotifications;
1760    }
1761    if (flags & CBLK_BUFFER_END) {
1762        mCbf(EVENT_BUFFER_END, mUserData, NULL);
1763    }
1764    if (markerReached) {
1765        mCbf(EVENT_MARKER, mUserData, &markerPosition);
1766    }
1767    while (newPosCount > 0) {
1768        size_t temp = newPosition;
1769        mCbf(EVENT_NEW_POS, mUserData, &temp);
1770        newPosition += updatePeriod;
1771        newPosCount--;
1772    }
1773
1774    if (mObservedSequence != sequence) {
1775        mObservedSequence = sequence;
1776        mCbf(EVENT_NEW_IAUDIOTRACK, mUserData, NULL);
1777        // for offloaded tracks, just wait for the upper layers to recreate the track
1778        if (isOffloadedOrDirect()) {
1779            return NS_INACTIVE;
1780        }
1781    }
1782
1783    // if inactive, then don't run me again until re-started
1784    if (!active) {
1785        return NS_INACTIVE;
1786    }
1787
1788    // Compute the estimated time until the next timed event (position, markers, loops)
1789    // FIXME only for non-compressed audio
1790    uint32_t minFrames = ~0;
1791    if (!markerReached && position < markerPosition) {
1792        minFrames = markerPosition - position;
1793    }
1794    if (loopPeriod > 0 && loopPeriod < minFrames) {
1795        // loopPeriod is already adjusted for actual position.
1796        minFrames = loopPeriod;
1797    }
1798    if (updatePeriod > 0) {
1799        minFrames = min(minFrames, uint32_t(newPosition - position));
1800    }
1801
1802    // If > 0, poll periodically to recover from a stuck server.  A good value is 2.
1803    static const uint32_t kPoll = 0;
1804    if (kPoll > 0 && mTransfer == TRANSFER_CALLBACK && kPoll * notificationFrames < minFrames) {
1805        minFrames = kPoll * notificationFrames;
1806    }
1807
1808    // Convert frame units to time units
1809    nsecs_t ns = NS_WHENEVER;
1810    if (minFrames != (uint32_t) ~0) {
1811        // This "fudge factor" avoids soaking CPU, and compensates for late progress by server
1812        static const nsecs_t kFudgeNs = 10000000LL; // 10 ms
1813        ns = ((double)minFrames * 1000000000) / ((double)sampleRate * speed) + kFudgeNs;
1814    }
1815
1816    // If not supplying data by EVENT_MORE_DATA, then we're done
1817    if (mTransfer != TRANSFER_CALLBACK) {
1818        return ns;
1819    }
1820
1821    struct timespec timeout;
1822    const struct timespec *requested = &ClientProxy::kForever;
1823    if (ns != NS_WHENEVER) {
1824        timeout.tv_sec = ns / 1000000000LL;
1825        timeout.tv_nsec = ns % 1000000000LL;
1826        ALOGV("timeout %ld.%03d", timeout.tv_sec, (int) timeout.tv_nsec / 1000000);
1827        requested = &timeout;
1828    }
1829
1830    while (mRemainingFrames > 0) {
1831
1832        Buffer audioBuffer;
1833        audioBuffer.frameCount = mRemainingFrames;
1834        size_t nonContig;
1835        status_t err = obtainBuffer(&audioBuffer, requested, NULL, &nonContig);
1836        LOG_ALWAYS_FATAL_IF((err != NO_ERROR) != (audioBuffer.frameCount == 0),
1837                "obtainBuffer() err=%d frameCount=%zu", err, audioBuffer.frameCount);
1838        requested = &ClientProxy::kNonBlocking;
1839        size_t avail = audioBuffer.frameCount + nonContig;
1840        ALOGV("obtainBuffer(%u) returned %zu = %zu + %zu err %d",
1841                mRemainingFrames, avail, audioBuffer.frameCount, nonContig, err);
1842        if (err != NO_ERROR) {
1843            if (err == TIMED_OUT || err == WOULD_BLOCK || err == -EINTR ||
1844                    (isOffloaded() && (err == DEAD_OBJECT))) {
1845                return 0;
1846            }
1847            ALOGE("Error %d obtaining an audio buffer, giving up.", err);
1848            return NS_NEVER;
1849        }
1850
1851        if (mRetryOnPartialBuffer && !isOffloaded()) {
1852            mRetryOnPartialBuffer = false;
1853            if (avail < mRemainingFrames) {
1854                int64_t myns = ((double)(mRemainingFrames - avail) * 1100000000)
1855                        / ((double)sampleRate * speed);
1856                if (ns < 0 || myns < ns) {
1857                    ns = myns;
1858                }
1859                return ns;
1860            }
1861        }
1862
1863        size_t reqSize = audioBuffer.size;
1864        mCbf(EVENT_MORE_DATA, mUserData, &audioBuffer);
1865        size_t writtenSize = audioBuffer.size;
1866
1867        // Sanity check on returned size
1868        if (ssize_t(writtenSize) < 0 || writtenSize > reqSize) {
1869            ALOGE("EVENT_MORE_DATA requested %zu bytes but callback returned %zd bytes",
1870                    reqSize, ssize_t(writtenSize));
1871            return NS_NEVER;
1872        }
1873
1874        if (writtenSize == 0) {
1875            // The callback is done filling buffers
1876            // Keep this thread going to handle timed events and
1877            // still try to get more data in intervals of WAIT_PERIOD_MS
1878            // but don't just loop and block the CPU, so wait
1879            return WAIT_PERIOD_MS * 1000000LL;
1880        }
1881
1882        size_t releasedFrames = writtenSize / mFrameSize;
1883        audioBuffer.frameCount = releasedFrames;
1884        mRemainingFrames -= releasedFrames;
1885        if (misalignment >= releasedFrames) {
1886            misalignment -= releasedFrames;
1887        } else {
1888            misalignment = 0;
1889        }
1890
1891        releaseBuffer(&audioBuffer);
1892
1893        // FIXME here is where we would repeat EVENT_MORE_DATA again on same advanced buffer
1894        // if callback doesn't like to accept the full chunk
1895        if (writtenSize < reqSize) {
1896            continue;
1897        }
1898
1899        // There could be enough non-contiguous frames available to satisfy the remaining request
1900        if (mRemainingFrames <= nonContig) {
1901            continue;
1902        }
1903
1904#if 0
1905        // This heuristic tries to collapse a series of EVENT_MORE_DATA that would total to a
1906        // sum <= notificationFrames.  It replaces that series by at most two EVENT_MORE_DATA
1907        // that total to a sum == notificationFrames.
1908        if (0 < misalignment && misalignment <= mRemainingFrames) {
1909            mRemainingFrames = misalignment;
1910            return ((double)mRemainingFrames * 1100000000) / ((double)sampleRate * speed);
1911        }
1912#endif
1913
1914    }
1915    mRemainingFrames = notificationFrames;
1916    mRetryOnPartialBuffer = true;
1917
1918    // A lot has transpired since ns was calculated, so run again immediately and re-calculate
1919    return 0;
1920}
1921
1922status_t AudioTrack::restoreTrack_l(const char *from)
1923{
1924    ALOGW("dead IAudioTrack, %s, creating a new one from %s()",
1925          isOffloadedOrDirect_l() ? "Offloaded or Direct" : "PCM", from);
1926    ++mSequence;
1927
1928    // refresh the audio configuration cache in this process to make sure we get new
1929    // output parameters and new IAudioFlinger in createTrack_l()
1930    AudioSystem::clearAudioConfigCache();
1931
1932    if (isOffloadedOrDirect_l()) {
1933        // FIXME re-creation of offloaded tracks is not yet implemented
1934        return DEAD_OBJECT;
1935    }
1936
1937    // save the old static buffer position
1938    size_t bufferPosition = 0;
1939    int loopCount = 0;
1940    if (mStaticProxy != 0) {
1941        mStaticProxy->getBufferPositionAndLoopCount(&bufferPosition, &loopCount);
1942    }
1943
1944    // If a new IAudioTrack is successfully created, createTrack_l() will modify the
1945    // following member variables: mAudioTrack, mCblkMemory and mCblk.
1946    // It will also delete the strong references on previous IAudioTrack and IMemory.
1947    // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
1948    status_t result = createTrack_l();
1949
1950    // take the frames that will be lost by track recreation into account in saved position
1951    // For streaming tracks, this is the amount we obtained from the user/client
1952    // (not the number actually consumed at the server - those are already lost).
1953    (void) updateAndGetPosition_l();
1954    if (mStaticProxy == 0) {
1955        mPosition = mReleased;
1956    }
1957
1958    if (result == NO_ERROR) {
1959        // Continue playback from last known position and restore loop.
1960        if (mStaticProxy != 0) {
1961            if (loopCount != 0) {
1962                mStaticProxy->setBufferPositionAndLoop(bufferPosition,
1963                        mLoopStart, mLoopEnd, loopCount);
1964            } else {
1965                mStaticProxy->setBufferPosition(bufferPosition);
1966                if (bufferPosition == mFrameCount) {
1967                    ALOGD("restoring track at end of static buffer");
1968                }
1969            }
1970        }
1971        if (mState == STATE_ACTIVE) {
1972            result = mAudioTrack->start();
1973        }
1974    }
1975    if (result != NO_ERROR) {
1976        ALOGW("restoreTrack_l() failed status %d", result);
1977        mState = STATE_STOPPED;
1978        mReleased = 0;
1979    }
1980
1981    return result;
1982}
1983
1984uint32_t AudioTrack::updateAndGetPosition_l()
1985{
1986    // This is the sole place to read server consumed frames
1987    uint32_t newServer = mProxy->getPosition();
1988    int32_t delta = newServer - mServer;
1989    mServer = newServer;
1990    // TODO There is controversy about whether there can be "negative jitter" in server position.
1991    //      This should be investigated further, and if possible, it should be addressed.
1992    //      A more definite failure mode is infrequent polling by client.
1993    //      One could call (void)getPosition_l() in releaseBuffer(),
1994    //      so mReleased and mPosition are always lock-step as best possible.
1995    //      That should ensure delta never goes negative for infrequent polling
1996    //      unless the server has more than 2^31 frames in its buffer,
1997    //      in which case the use of uint32_t for these counters has bigger issues.
1998    if (delta < 0) {
1999        ALOGE("detected illegal retrograde motion by the server: mServer advanced by %d", delta);
2000        delta = 0;
2001    }
2002    return mPosition += (uint32_t) delta;
2003}
2004
2005bool AudioTrack::isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const
2006{
2007    // applicable for mixing tracks only (not offloaded or direct)
2008    if (mStaticProxy != 0) {
2009        return true; // static tracks do not have issues with buffer sizing.
2010    }
2011    status_t status;
2012    uint32_t afLatency;
2013    status = AudioSystem::getLatency(mOutput, &afLatency);
2014    if (status != NO_ERROR) {
2015        ALOGE("getLatency(%d) failed status %d", mOutput, status);
2016        return false;
2017    }
2018
2019    size_t afFrameCount;
2020    status = AudioSystem::getFrameCount(mOutput, &afFrameCount);
2021    if (status != NO_ERROR) {
2022        ALOGE("getFrameCount(output=%d) status %d", mOutput, status);
2023        return false;
2024    }
2025
2026    uint32_t afSampleRate;
2027    status = AudioSystem::getSamplingRate(mOutput, &afSampleRate);
2028    if (status != NO_ERROR) {
2029        ALOGE("getSamplingRate(output=%d) status %d", mOutput, status);
2030        return false;
2031    }
2032
2033    const size_t minFrameCount =
2034            calculateMinFrameCount(afLatency, afFrameCount, afSampleRate, sampleRate, speed);
2035    ALOGV("isSampleRateSpeedAllowed_l mFrameCount %zu  minFrameCount %zu",
2036            mFrameCount, minFrameCount);
2037    return mFrameCount >= minFrameCount;
2038}
2039
2040status_t AudioTrack::setParameters(const String8& keyValuePairs)
2041{
2042    AutoMutex lock(mLock);
2043    return mAudioTrack->setParameters(keyValuePairs);
2044}
2045
2046status_t AudioTrack::getTimestamp(AudioTimestamp& timestamp)
2047{
2048    AutoMutex lock(mLock);
2049    // FIXME not implemented for fast tracks; should use proxy and SSQ
2050    if (mFlags & AUDIO_OUTPUT_FLAG_FAST) {
2051        return INVALID_OPERATION;
2052    }
2053
2054    switch (mState) {
2055    case STATE_ACTIVE:
2056    case STATE_PAUSED:
2057        break; // handle below
2058    case STATE_FLUSHED:
2059    case STATE_STOPPED:
2060        return WOULD_BLOCK;
2061    case STATE_STOPPING:
2062    case STATE_PAUSED_STOPPING:
2063        if (!isOffloaded_l()) {
2064            return INVALID_OPERATION;
2065        }
2066        break; // offloaded tracks handled below
2067    default:
2068        LOG_ALWAYS_FATAL("Invalid mState in getTimestamp(): %d", mState);
2069        break;
2070    }
2071
2072    if (mCblk->mFlags & CBLK_INVALID) {
2073        restoreTrack_l("getTimestamp");
2074    }
2075
2076    // The presented frame count must always lag behind the consumed frame count.
2077    // To avoid a race, read the presented frames first.  This ensures that presented <= consumed.
2078    status_t status = mAudioTrack->getTimestamp(timestamp);
2079    if (status != NO_ERROR) {
2080        ALOGV_IF(status != WOULD_BLOCK, "getTimestamp error:%#x", status);
2081        return status;
2082    }
2083    if (isOffloadedOrDirect_l()) {
2084        if (isOffloaded_l() && (mState == STATE_PAUSED || mState == STATE_PAUSED_STOPPING)) {
2085            // use cached paused position in case another offloaded track is running.
2086            timestamp.mPosition = mPausedPosition;
2087            clock_gettime(CLOCK_MONOTONIC, &timestamp.mTime);
2088            return NO_ERROR;
2089        }
2090
2091        // Check whether a pending flush or stop has completed, as those commands may
2092        // be asynchronous or return near finish.
2093        if (mStartUs != 0 && mSampleRate != 0) {
2094            static const int kTimeJitterUs = 100000; // 100 ms
2095            static const int k1SecUs = 1000000;
2096
2097            const int64_t timeNow = getNowUs();
2098
2099            if (timeNow < mStartUs + k1SecUs) { // within first second of starting
2100                const int64_t timestampTimeUs = convertTimespecToUs(timestamp.mTime);
2101                if (timestampTimeUs < mStartUs) {
2102                    return WOULD_BLOCK;  // stale timestamp time, occurs before start.
2103                }
2104                const int64_t deltaTimeUs = timestampTimeUs - mStartUs;
2105                const int64_t deltaPositionByUs = (double)timestamp.mPosition * 1000000
2106                        / ((double)mSampleRate * mSpeed);
2107
2108                if (deltaPositionByUs > deltaTimeUs + kTimeJitterUs) {
2109                    // Verify that the counter can't count faster than the sample rate
2110                    // since the start time.  If greater, then that means we have failed
2111                    // to completely flush or stop the previous playing track.
2112                    ALOGW("incomplete flush or stop:"
2113                            " deltaTimeUs(%lld) deltaPositionUs(%lld) tsmPosition(%u)",
2114                            (long long)deltaTimeUs, (long long)deltaPositionByUs,
2115                            timestamp.mPosition);
2116                    return WOULD_BLOCK;
2117                }
2118            }
2119            mStartUs = 0; // no need to check again, start timestamp has either expired or unneeded.
2120        }
2121    } else {
2122        // Update the mapping between local consumed (mPosition) and server consumed (mServer)
2123        (void) updateAndGetPosition_l();
2124        // Server consumed (mServer) and presented both use the same server time base,
2125        // and server consumed is always >= presented.
2126        // The delta between these represents the number of frames in the buffer pipeline.
2127        // If this delta between these is greater than the client position, it means that
2128        // actually presented is still stuck at the starting line (figuratively speaking),
2129        // waiting for the first frame to go by.  So we can't report a valid timestamp yet.
2130        if ((uint32_t) (mServer - timestamp.mPosition) > mPosition) {
2131            return INVALID_OPERATION;
2132        }
2133        // Convert timestamp position from server time base to client time base.
2134        // TODO The following code should work OK now because timestamp.mPosition is 32-bit.
2135        // But if we change it to 64-bit then this could fail.
2136        // If (mPosition - mServer) can be negative then should use:
2137        //   (int32_t)(mPosition - mServer)
2138        timestamp.mPosition += mPosition - mServer;
2139        // Immediately after a call to getPosition_l(), mPosition and
2140        // mServer both represent the same frame position.  mPosition is
2141        // in client's point of view, and mServer is in server's point of
2142        // view.  So the difference between them is the "fudge factor"
2143        // between client and server views due to stop() and/or new
2144        // IAudioTrack.  And timestamp.mPosition is initially in server's
2145        // point of view, so we need to apply the same fudge factor to it.
2146    }
2147    return status;
2148}
2149
2150String8 AudioTrack::getParameters(const String8& keys)
2151{
2152    audio_io_handle_t output = getOutput();
2153    if (output != AUDIO_IO_HANDLE_NONE) {
2154        return AudioSystem::getParameters(output, keys);
2155    } else {
2156        return String8::empty();
2157    }
2158}
2159
2160bool AudioTrack::isOffloaded() const
2161{
2162    AutoMutex lock(mLock);
2163    return isOffloaded_l();
2164}
2165
2166bool AudioTrack::isDirect() const
2167{
2168    AutoMutex lock(mLock);
2169    return isDirect_l();
2170}
2171
2172bool AudioTrack::isOffloadedOrDirect() const
2173{
2174    AutoMutex lock(mLock);
2175    return isOffloadedOrDirect_l();
2176}
2177
2178
2179status_t AudioTrack::dump(int fd, const Vector<String16>& args __unused) const
2180{
2181
2182    const size_t SIZE = 256;
2183    char buffer[SIZE];
2184    String8 result;
2185
2186    result.append(" AudioTrack::dump\n");
2187    snprintf(buffer, 255, "  stream type(%d), left - right volume(%f, %f)\n", mStreamType,
2188            mVolume[AUDIO_INTERLEAVE_LEFT], mVolume[AUDIO_INTERLEAVE_RIGHT]);
2189    result.append(buffer);
2190    snprintf(buffer, 255, "  format(%d), channel count(%d), frame count(%zu)\n", mFormat,
2191            mChannelCount, mFrameCount);
2192    result.append(buffer);
2193    snprintf(buffer, 255, "  sample rate(%u), speed(%f), status(%d)\n",
2194            mSampleRate, mSpeed, mStatus);
2195    result.append(buffer);
2196    snprintf(buffer, 255, "  state(%d), latency (%d)\n", mState, mLatency);
2197    result.append(buffer);
2198    ::write(fd, result.string(), result.size());
2199    return NO_ERROR;
2200}
2201
2202uint32_t AudioTrack::getUnderrunFrames() const
2203{
2204    AutoMutex lock(mLock);
2205    return mProxy->getUnderrunFrames();
2206}
2207
2208// =========================================================================
2209
2210void AudioTrack::DeathNotifier::binderDied(const wp<IBinder>& who __unused)
2211{
2212    sp<AudioTrack> audioTrack = mAudioTrack.promote();
2213    if (audioTrack != 0) {
2214        AutoMutex lock(audioTrack->mLock);
2215        audioTrack->mProxy->binderDied();
2216    }
2217}
2218
2219// =========================================================================
2220
2221AudioTrack::AudioTrackThread::AudioTrackThread(AudioTrack& receiver, bool bCanCallJava)
2222    : Thread(bCanCallJava), mReceiver(receiver), mPaused(true), mPausedInt(false), mPausedNs(0LL),
2223      mIgnoreNextPausedInt(false)
2224{
2225}
2226
2227AudioTrack::AudioTrackThread::~AudioTrackThread()
2228{
2229}
2230
2231bool AudioTrack::AudioTrackThread::threadLoop()
2232{
2233    {
2234        AutoMutex _l(mMyLock);
2235        if (mPaused) {
2236            mMyCond.wait(mMyLock);
2237            // caller will check for exitPending()
2238            return true;
2239        }
2240        if (mIgnoreNextPausedInt) {
2241            mIgnoreNextPausedInt = false;
2242            mPausedInt = false;
2243        }
2244        if (mPausedInt) {
2245            if (mPausedNs > 0) {
2246                (void) mMyCond.waitRelative(mMyLock, mPausedNs);
2247            } else {
2248                mMyCond.wait(mMyLock);
2249            }
2250            mPausedInt = false;
2251            return true;
2252        }
2253    }
2254    if (exitPending()) {
2255        return false;
2256    }
2257    nsecs_t ns = mReceiver.processAudioBuffer();
2258    switch (ns) {
2259    case 0:
2260        return true;
2261    case NS_INACTIVE:
2262        pauseInternal();
2263        return true;
2264    case NS_NEVER:
2265        return false;
2266    case NS_WHENEVER:
2267        // Event driven: call wake() when callback notifications conditions change.
2268        ns = INT64_MAX;
2269        // fall through
2270    default:
2271        LOG_ALWAYS_FATAL_IF(ns < 0, "processAudioBuffer() returned %" PRId64, ns);
2272        pauseInternal(ns);
2273        return true;
2274    }
2275}
2276
2277void AudioTrack::AudioTrackThread::requestExit()
2278{
2279    // must be in this order to avoid a race condition
2280    Thread::requestExit();
2281    resume();
2282}
2283
2284void AudioTrack::AudioTrackThread::pause()
2285{
2286    AutoMutex _l(mMyLock);
2287    mPaused = true;
2288}
2289
2290void AudioTrack::AudioTrackThread::resume()
2291{
2292    AutoMutex _l(mMyLock);
2293    mIgnoreNextPausedInt = true;
2294    if (mPaused || mPausedInt) {
2295        mPaused = false;
2296        mPausedInt = false;
2297        mMyCond.signal();
2298    }
2299}
2300
2301void AudioTrack::AudioTrackThread::wake()
2302{
2303    AutoMutex _l(mMyLock);
2304    if (!mPaused && mPausedInt && mPausedNs > 0) {
2305        // audio track is active and internally paused with timeout.
2306        mIgnoreNextPausedInt = true;
2307        mPausedInt = false;
2308        mMyCond.signal();
2309    }
2310}
2311
2312void AudioTrack::AudioTrackThread::pauseInternal(nsecs_t ns)
2313{
2314    AutoMutex _l(mMyLock);
2315    mPausedInt = true;
2316    mPausedNs = ns;
2317}
2318
2319} // namespace android
2320