AudioTrackShared.cpp revision bfb1b832079bbb9426f72f3863199a54aefd02da
1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioTrackShared"
18//#define LOG_NDEBUG 0
19
20#include <private/media/AudioTrackShared.h>
21#include <utils/Log.h>
22extern "C" {
23#include "../private/bionic_futex.h"
24}
25
26namespace android {
27
28audio_track_cblk_t::audio_track_cblk_t()
29    : server(0), frameCount_(0), mFutex(0), mMinimum(0),
30    mVolumeLR(0x10001000), mSampleRate(0), mSendLevel(0), mName(0), flags(0)
31{
32    memset(&u, 0, sizeof(u));
33}
34
35// ---------------------------------------------------------------------------
36
37Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
38        bool isOut, bool clientInServer)
39    : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
40      mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
41      mIsShutdown(false), mUnreleased(0)
42{
43}
44
45// ---------------------------------------------------------------------------
46
47ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
48        size_t frameSize, bool isOut, bool clientInServer)
49    : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer), mEpoch(0)
50{
51}
52
53const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
54const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
55
56#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
57
58// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
59// wait.  However it does not protect infinite timeouts.  If defined to be zero, there is no limit.
60// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
61// order of minutes.
62#define MAX_SEC    5
63
64status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
65        struct timespec *elapsed)
66{
67    LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
68    struct timespec total;          // total elapsed time spent waiting
69    total.tv_sec = 0;
70    total.tv_nsec = 0;
71    bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
72
73    status_t status;
74    enum {
75        TIMEOUT_ZERO,       // requested == NULL || *requested == 0
76        TIMEOUT_INFINITE,   // *requested == infinity
77        TIMEOUT_FINITE,     // 0 < *requested < infinity
78        TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
79    } timeout;
80    if (requested == NULL) {
81        timeout = TIMEOUT_ZERO;
82    } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
83        timeout = TIMEOUT_ZERO;
84    } else if (requested->tv_sec == INT_MAX) {
85        timeout = TIMEOUT_INFINITE;
86    } else {
87        timeout = TIMEOUT_FINITE;
88        if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
89            measure = true;
90        }
91    }
92    struct timespec before;
93    bool beforeIsValid = false;
94    audio_track_cblk_t* cblk = mCblk;
95    bool ignoreInitialPendingInterrupt = true;
96    // check for shared memory corruption
97    if (mIsShutdown) {
98        status = NO_INIT;
99        goto end;
100    }
101    for (;;) {
102        int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->flags);
103        // check for track invalidation by server, or server death detection
104        if (flags & CBLK_INVALID) {
105            ALOGV("Track invalidated");
106            status = DEAD_OBJECT;
107            goto end;
108        }
109        // check for obtainBuffer interrupted by client
110        if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
111            ALOGV("obtainBuffer() interrupted by client");
112            status = -EINTR;
113            goto end;
114        }
115        ignoreInitialPendingInterrupt = false;
116        // compute number of frames available to write (AudioTrack) or read (AudioRecord)
117        int32_t front;
118        int32_t rear;
119        if (mIsOut) {
120            // The barrier following the read of mFront is probably redundant.
121            // We're about to perform a conditional branch based on 'filled',
122            // which will force the processor to observe the read of mFront
123            // prior to allowing data writes starting at mRaw.
124            // However, the processor may support speculative execution,
125            // and be unable to undo speculative writes into shared memory.
126            // The barrier will prevent such speculative execution.
127            front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
128            rear = cblk->u.mStreaming.mRear;
129        } else {
130            // On the other hand, this barrier is required.
131            rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
132            front = cblk->u.mStreaming.mFront;
133        }
134        ssize_t filled = rear - front;
135        // pipe should not be overfull
136        if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
137            ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
138            mIsShutdown = true;
139            status = NO_INIT;
140            goto end;
141        }
142        // don't allow filling pipe beyond the nominal size
143        size_t avail = mIsOut ? mFrameCount - filled : filled;
144        if (avail > 0) {
145            // 'avail' may be non-contiguous, so return only the first contiguous chunk
146            size_t part1;
147            if (mIsOut) {
148                rear &= mFrameCountP2 - 1;
149                part1 = mFrameCountP2 - rear;
150            } else {
151                front &= mFrameCountP2 - 1;
152                part1 = mFrameCountP2 - front;
153            }
154            if (part1 > avail) {
155                part1 = avail;
156            }
157            if (part1 > buffer->mFrameCount) {
158                part1 = buffer->mFrameCount;
159            }
160            buffer->mFrameCount = part1;
161            buffer->mRaw = part1 > 0 ?
162                    &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
163            buffer->mNonContig = avail - part1;
164            mUnreleased = part1;
165            status = NO_ERROR;
166            break;
167        }
168        struct timespec remaining;
169        const struct timespec *ts;
170        switch (timeout) {
171        case TIMEOUT_ZERO:
172            status = WOULD_BLOCK;
173            goto end;
174        case TIMEOUT_INFINITE:
175            ts = NULL;
176            break;
177        case TIMEOUT_FINITE:
178            timeout = TIMEOUT_CONTINUE;
179            if (MAX_SEC == 0) {
180                ts = requested;
181                break;
182            }
183            // fall through
184        case TIMEOUT_CONTINUE:
185            // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
186            if (!measure || requested->tv_sec < total.tv_sec ||
187                    (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
188                status = TIMED_OUT;
189                goto end;
190            }
191            remaining.tv_sec = requested->tv_sec - total.tv_sec;
192            if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
193                remaining.tv_nsec += 1000000000;
194                remaining.tv_sec++;
195            }
196            if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
197                remaining.tv_sec = MAX_SEC;
198                remaining.tv_nsec = 0;
199            }
200            ts = &remaining;
201            break;
202        default:
203            LOG_FATAL("%s timeout=%d", timeout);
204            ts = NULL;
205            break;
206        }
207        int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
208        if (!(old & CBLK_FUTEX_WAKE)) {
209            int rc;
210            if (measure && !beforeIsValid) {
211                clock_gettime(CLOCK_MONOTONIC, &before);
212                beforeIsValid = true;
213            }
214            int ret = __futex_syscall4(&cblk->mFutex,
215                    mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
216            // update total elapsed time spent waiting
217            if (measure) {
218                struct timespec after;
219                clock_gettime(CLOCK_MONOTONIC, &after);
220                total.tv_sec += after.tv_sec - before.tv_sec;
221                long deltaNs = after.tv_nsec - before.tv_nsec;
222                if (deltaNs < 0) {
223                    deltaNs += 1000000000;
224                    total.tv_sec--;
225                }
226                if ((total.tv_nsec += deltaNs) >= 1000000000) {
227                    total.tv_nsec -= 1000000000;
228                    total.tv_sec++;
229                }
230                before = after;
231                beforeIsValid = true;
232            }
233            switch (ret) {
234            case 0:             // normal wakeup by server, or by binderDied()
235            case -EWOULDBLOCK:  // benign race condition with server
236            case -EINTR:        // wait was interrupted by signal or other spurious wakeup
237            case -ETIMEDOUT:    // time-out expired
238                // FIXME these error/non-0 status are being dropped
239                break;
240            default:
241                ALOGE("%s unexpected error %d", __func__, ret);
242                status = -ret;
243                goto end;
244            }
245        }
246    }
247
248end:
249    if (status != NO_ERROR) {
250        buffer->mFrameCount = 0;
251        buffer->mRaw = NULL;
252        buffer->mNonContig = 0;
253        mUnreleased = 0;
254    }
255    if (elapsed != NULL) {
256        *elapsed = total;
257    }
258    if (requested == NULL) {
259        requested = &kNonBlocking;
260    }
261    if (measure) {
262        ALOGV("requested %d.%03d elapsed %d.%03d", requested->tv_sec, requested->tv_nsec / 1000000,
263                total.tv_sec, total.tv_nsec / 1000000);
264    }
265    return status;
266}
267
268void ClientProxy::releaseBuffer(Buffer* buffer)
269{
270    LOG_ALWAYS_FATAL_IF(buffer == NULL);
271    size_t stepCount = buffer->mFrameCount;
272    if (stepCount == 0 || mIsShutdown) {
273        // prevent accidental re-use of buffer
274        buffer->mFrameCount = 0;
275        buffer->mRaw = NULL;
276        buffer->mNonContig = 0;
277        return;
278    }
279    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
280    mUnreleased -= stepCount;
281    audio_track_cblk_t* cblk = mCblk;
282    // Both of these barriers are required
283    if (mIsOut) {
284        int32_t rear = cblk->u.mStreaming.mRear;
285        android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
286    } else {
287        int32_t front = cblk->u.mStreaming.mFront;
288        android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
289    }
290}
291
292void ClientProxy::binderDied()
293{
294    audio_track_cblk_t* cblk = mCblk;
295    if (!(android_atomic_or(CBLK_INVALID, &cblk->flags) & CBLK_INVALID)) {
296        // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
297        (void) __futex_syscall3(&cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
298                1);
299    }
300}
301
302void ClientProxy::interrupt()
303{
304    audio_track_cblk_t* cblk = mCblk;
305    if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->flags) & CBLK_INTERRUPT)) {
306        (void) __futex_syscall3(&cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
307                1);
308    }
309}
310
311size_t ClientProxy::getMisalignment()
312{
313    audio_track_cblk_t* cblk = mCblk;
314    return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
315            (mFrameCountP2 - 1);
316}
317
318// ---------------------------------------------------------------------------
319
320void AudioTrackClientProxy::flush()
321{
322    mCblk->u.mStreaming.mFlush++;
323}
324
325bool AudioTrackClientProxy::clearStreamEndDone() {
326    return android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->flags) & CBLK_STREAM_END_DONE;
327}
328
329bool AudioTrackClientProxy::getStreamEndDone() const {
330    return (mCblk->flags & CBLK_STREAM_END_DONE) != 0;
331}
332
333// ---------------------------------------------------------------------------
334
335StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
336        size_t frameCount, size_t frameSize)
337    : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
338      mMutator(&cblk->u.mStatic.mSingleStateQueue), mBufferPosition(0)
339{
340}
341
342void StaticAudioTrackClientProxy::flush()
343{
344    LOG_FATAL("static flush");
345}
346
347void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
348{
349    StaticAudioTrackState newState;
350    newState.mLoopStart = loopStart;
351    newState.mLoopEnd = loopEnd;
352    newState.mLoopCount = loopCount;
353    mBufferPosition = loopStart;
354    (void) mMutator.push(newState);
355}
356
357size_t StaticAudioTrackClientProxy::getBufferPosition()
358{
359    size_t bufferPosition;
360    if (mMutator.ack()) {
361        bufferPosition = mCblk->u.mStatic.mBufferPosition;
362        if (bufferPosition > mFrameCount) {
363            bufferPosition = mFrameCount;
364        }
365    } else {
366        bufferPosition = mBufferPosition;
367    }
368    return bufferPosition;
369}
370
371// ---------------------------------------------------------------------------
372
373ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
374        size_t frameSize, bool isOut, bool clientInServer)
375    : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
376      mAvailToClient(0), mFlush(0), mDeferWake(false)
377{
378}
379
380status_t ServerProxy::obtainBuffer(Buffer* buffer)
381{
382    LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
383    if (mIsShutdown) {
384        goto no_init;
385    }
386    {
387    audio_track_cblk_t* cblk = mCblk;
388    // compute number of frames available to write (AudioTrack) or read (AudioRecord),
389    // or use previous cached value from framesReady(), with added barrier if it omits.
390    int32_t front;
391    int32_t rear;
392    // See notes on barriers at ClientProxy::obtainBuffer()
393    if (mIsOut) {
394        int32_t flush = cblk->u.mStreaming.mFlush;
395        rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
396        if (flush != mFlush) {
397            front = rear;
398            mFlush = flush;
399            // effectively obtain then release whatever is in the buffer
400            android_atomic_release_store(rear, &cblk->u.mStreaming.mFront);
401        } else {
402            front = cblk->u.mStreaming.mFront;
403        }
404    } else {
405        front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
406        rear = cblk->u.mStreaming.mRear;
407    }
408    ssize_t filled = rear - front;
409    // pipe should not already be overfull
410    if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
411        ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
412        mIsShutdown = true;
413    }
414    if (mIsShutdown) {
415        goto no_init;
416    }
417    // don't allow filling pipe beyond the nominal size
418    size_t availToServer;
419    if (mIsOut) {
420        availToServer = filled;
421        mAvailToClient = mFrameCount - filled;
422    } else {
423        availToServer = mFrameCount - filled;
424        mAvailToClient = filled;
425    }
426    // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
427    size_t part1;
428    if (mIsOut) {
429        front &= mFrameCountP2 - 1;
430        part1 = mFrameCountP2 - front;
431    } else {
432        rear &= mFrameCountP2 - 1;
433        part1 = mFrameCountP2 - rear;
434    }
435    if (part1 > availToServer) {
436        part1 = availToServer;
437    }
438    size_t ask = buffer->mFrameCount;
439    if (part1 > ask) {
440        part1 = ask;
441    }
442    // is assignment redundant in some cases?
443    buffer->mFrameCount = part1;
444    buffer->mRaw = part1 > 0 ?
445            &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
446    buffer->mNonContig = availToServer - part1;
447    mUnreleased = part1;
448    // optimization to avoid waking up the client too early
449    // FIXME need to test for recording
450    mDeferWake = part1 < ask && availToServer >= ask;
451    return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
452    }
453no_init:
454    buffer->mFrameCount = 0;
455    buffer->mRaw = NULL;
456    buffer->mNonContig = 0;
457    mUnreleased = 0;
458    return NO_INIT;
459}
460
461void ServerProxy::releaseBuffer(Buffer* buffer)
462{
463    LOG_ALWAYS_FATAL_IF(buffer == NULL);
464    size_t stepCount = buffer->mFrameCount;
465    if (stepCount == 0 || mIsShutdown) {
466        // prevent accidental re-use of buffer
467        buffer->mFrameCount = 0;
468        buffer->mRaw = NULL;
469        buffer->mNonContig = 0;
470        return;
471    }
472    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
473    mUnreleased -= stepCount;
474    audio_track_cblk_t* cblk = mCblk;
475    if (mIsOut) {
476        int32_t front = cblk->u.mStreaming.mFront;
477        android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
478    } else {
479        int32_t rear = cblk->u.mStreaming.mRear;
480        android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
481    }
482
483    mCblk->server += stepCount;
484
485    size_t half = mFrameCount / 2;
486    if (half == 0) {
487        half = 1;
488    }
489    size_t minimum = cblk->mMinimum;
490    if (minimum == 0) {
491        minimum = mIsOut ? half : 1;
492    } else if (minimum > half) {
493        minimum = half;
494    }
495    // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
496    if (!mIsOut || (!mDeferWake && mAvailToClient + stepCount >= minimum)) {
497        ALOGV("mAvailToClient=%u stepCount=%u minimum=%u", mAvailToClient, stepCount, minimum);
498        int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
499        if (!(old & CBLK_FUTEX_WAKE)) {
500            (void) __futex_syscall3(&cblk->mFutex,
501                    mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
502        }
503    }
504
505    buffer->mFrameCount = 0;
506    buffer->mRaw = NULL;
507    buffer->mNonContig = 0;
508}
509
510// ---------------------------------------------------------------------------
511
512size_t AudioTrackServerProxy::framesReady()
513{
514    LOG_ALWAYS_FATAL_IF(!mIsOut);
515
516    if (mIsShutdown) {
517        return 0;
518    }
519    audio_track_cblk_t* cblk = mCblk;
520    // the acquire might not be necessary since not doing a subsequent read
521    int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
522    ssize_t filled = rear - cblk->u.mStreaming.mFront;
523    // pipe should not already be overfull
524    if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
525        ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
526        mIsShutdown = true;
527        return 0;
528    }
529    //  cache this value for later use by obtainBuffer(), with added barrier
530    //  and racy if called by normal mixer thread
531    // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
532    return filled;
533}
534
535bool  AudioTrackServerProxy::setStreamEndDone() {
536    bool old =
537            (android_atomic_or(CBLK_STREAM_END_DONE, &mCblk->flags) & CBLK_STREAM_END_DONE) != 0;
538    if (!old) {
539        (void) __futex_syscall3(&mCblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
540                1);
541    }
542    return old;
543}
544
545// ---------------------------------------------------------------------------
546
547StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
548        size_t frameCount, size_t frameSize)
549    : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
550      mObserver(&cblk->u.mStatic.mSingleStateQueue), mPosition(0),
551      mEnd(frameCount), mFramesReadyIsCalledByMultipleThreads(false)
552{
553    mState.mLoopStart = 0;
554    mState.mLoopEnd = 0;
555    mState.mLoopCount = 0;
556}
557
558void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
559{
560    mFramesReadyIsCalledByMultipleThreads = true;
561}
562
563size_t StaticAudioTrackServerProxy::framesReady()
564{
565    // FIXME
566    // This is racy if called by normal mixer thread,
567    // as we're reading 2 independent variables without a lock.
568    // Can't call mObserver.poll(), as we might be called from wrong thread.
569    // If looping is enabled, should return a higher number (since includes non-contiguous).
570    size_t position = mPosition;
571    if (!mFramesReadyIsCalledByMultipleThreads) {
572        ssize_t positionOrStatus = pollPosition();
573        if (positionOrStatus >= 0) {
574            position = (size_t) positionOrStatus;
575        }
576    }
577    size_t end = mEnd;
578    return position < end ? end - position : 0;
579}
580
581ssize_t StaticAudioTrackServerProxy::pollPosition()
582{
583    size_t position = mPosition;
584    StaticAudioTrackState state;
585    if (mObserver.poll(state)) {
586        bool valid = false;
587        size_t loopStart = state.mLoopStart;
588        size_t loopEnd = state.mLoopEnd;
589        if (state.mLoopCount == 0) {
590            if (loopStart > mFrameCount) {
591                loopStart = mFrameCount;
592            }
593            // ignore loopEnd
594            mPosition = position = loopStart;
595            mEnd = mFrameCount;
596            mState.mLoopCount = 0;
597            valid = true;
598        } else {
599            if (loopStart < loopEnd && loopEnd <= mFrameCount &&
600                    loopEnd - loopStart >= MIN_LOOP) {
601                if (!(loopStart <= position && position < loopEnd)) {
602                    mPosition = position = loopStart;
603                }
604                mEnd = loopEnd;
605                mState = state;
606                valid = true;
607            }
608        }
609        if (!valid) {
610            ALOGE("%s client pushed an invalid state, shutting down", __func__);
611            mIsShutdown = true;
612            return (ssize_t) NO_INIT;
613        }
614        mCblk->u.mStatic.mBufferPosition = position;
615    }
616    return (ssize_t) position;
617}
618
619status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer)
620{
621    if (mIsShutdown) {
622        buffer->mFrameCount = 0;
623        buffer->mRaw = NULL;
624        buffer->mNonContig = 0;
625        mUnreleased = 0;
626        return NO_INIT;
627    }
628    ssize_t positionOrStatus = pollPosition();
629    if (positionOrStatus < 0) {
630        buffer->mFrameCount = 0;
631        buffer->mRaw = NULL;
632        buffer->mNonContig = 0;
633        mUnreleased = 0;
634        return (status_t) positionOrStatus;
635    }
636    size_t position = (size_t) positionOrStatus;
637    size_t avail;
638    if (position < mEnd) {
639        avail = mEnd - position;
640        size_t wanted = buffer->mFrameCount;
641        if (avail < wanted) {
642            buffer->mFrameCount = avail;
643        } else {
644            avail = wanted;
645        }
646        buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
647    } else {
648        avail = 0;
649        buffer->mFrameCount = 0;
650        buffer->mRaw = NULL;
651    }
652    buffer->mNonContig = 0;     // FIXME should be > 0 for looping
653    mUnreleased = avail;
654    return NO_ERROR;
655}
656
657void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
658{
659    size_t stepCount = buffer->mFrameCount;
660    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
661    if (stepCount == 0) {
662        // prevent accidental re-use of buffer
663        buffer->mRaw = NULL;
664        buffer->mNonContig = 0;
665        return;
666    }
667    mUnreleased -= stepCount;
668    audio_track_cblk_t* cblk = mCblk;
669    size_t position = mPosition;
670    size_t newPosition = position + stepCount;
671    int32_t setFlags = 0;
672    if (!(position <= newPosition && newPosition <= mFrameCount)) {
673        ALOGW("%s newPosition %u outside [%u, %u]", __func__, newPosition, position, mFrameCount);
674        newPosition = mFrameCount;
675    } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
676        if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
677            newPosition = mState.mLoopStart;
678            setFlags = CBLK_LOOP_CYCLE;
679        } else {
680            mEnd = mFrameCount;     // this is what allows playback to continue after the loop
681            setFlags = CBLK_LOOP_FINAL;
682        }
683    }
684    if (newPosition == mFrameCount) {
685        setFlags |= CBLK_BUFFER_END;
686    }
687    mPosition = newPosition;
688
689    cblk->server += stepCount;
690    cblk->u.mStatic.mBufferPosition = newPosition;
691    if (setFlags != 0) {
692        (void) android_atomic_or(setFlags, &cblk->flags);
693        // this would be a good place to wake a futex
694    }
695
696    buffer->mFrameCount = 0;
697    buffer->mRaw = NULL;
698    buffer->mNonContig = 0;
699}
700
701// ---------------------------------------------------------------------------
702
703}   // namespace android
704