AudioTrackShared.cpp revision 20f51b1ea04c410a25f214e37bcdb586e2a028cc
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>
22
23#include <linux/futex.h>
24#include <sys/syscall.h>
25
26namespace android {
27
28audio_track_cblk_t::audio_track_cblk_t()
29    : mServer(0), mFutex(0), mMinimum(0),
30    mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0), mFlags(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->mFlags);
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            if (mIsOut) {
138                ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
139                        "shutting down", filled, mFrameCount);
140                mIsShutdown = true;
141                status = NO_INIT;
142                goto end;
143            }
144            // for input, sync up on overrun
145            filled = 0;
146            cblk->u.mStreaming.mFront = rear;
147            (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
148        }
149        // don't allow filling pipe beyond the nominal size
150        size_t avail = mIsOut ? mFrameCount - filled : filled;
151        if (avail > 0) {
152            // 'avail' may be non-contiguous, so return only the first contiguous chunk
153            size_t part1;
154            if (mIsOut) {
155                rear &= mFrameCountP2 - 1;
156                part1 = mFrameCountP2 - rear;
157            } else {
158                front &= mFrameCountP2 - 1;
159                part1 = mFrameCountP2 - front;
160            }
161            if (part1 > avail) {
162                part1 = avail;
163            }
164            if (part1 > buffer->mFrameCount) {
165                part1 = buffer->mFrameCount;
166            }
167            buffer->mFrameCount = part1;
168            buffer->mRaw = part1 > 0 ?
169                    &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
170            buffer->mNonContig = avail - part1;
171            mUnreleased = part1;
172            status = NO_ERROR;
173            break;
174        }
175        struct timespec remaining;
176        const struct timespec *ts;
177        switch (timeout) {
178        case TIMEOUT_ZERO:
179            status = WOULD_BLOCK;
180            goto end;
181        case TIMEOUT_INFINITE:
182            ts = NULL;
183            break;
184        case TIMEOUT_FINITE:
185            timeout = TIMEOUT_CONTINUE;
186            if (MAX_SEC == 0) {
187                ts = requested;
188                break;
189            }
190            // fall through
191        case TIMEOUT_CONTINUE:
192            // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
193            if (!measure || requested->tv_sec < total.tv_sec ||
194                    (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
195                status = TIMED_OUT;
196                goto end;
197            }
198            remaining.tv_sec = requested->tv_sec - total.tv_sec;
199            if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
200                remaining.tv_nsec += 1000000000;
201                remaining.tv_sec++;
202            }
203            if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
204                remaining.tv_sec = MAX_SEC;
205                remaining.tv_nsec = 0;
206            }
207            ts = &remaining;
208            break;
209        default:
210            LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
211            ts = NULL;
212            break;
213        }
214        int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
215        if (!(old & CBLK_FUTEX_WAKE)) {
216            if (measure && !beforeIsValid) {
217                clock_gettime(CLOCK_MONOTONIC, &before);
218                beforeIsValid = true;
219            }
220            errno = 0;
221            (void) syscall(__NR_futex, &cblk->mFutex,
222                    mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
223            // update total elapsed time spent waiting
224            if (measure) {
225                struct timespec after;
226                clock_gettime(CLOCK_MONOTONIC, &after);
227                total.tv_sec += after.tv_sec - before.tv_sec;
228                long deltaNs = after.tv_nsec - before.tv_nsec;
229                if (deltaNs < 0) {
230                    deltaNs += 1000000000;
231                    total.tv_sec--;
232                }
233                if ((total.tv_nsec += deltaNs) >= 1000000000) {
234                    total.tv_nsec -= 1000000000;
235                    total.tv_sec++;
236                }
237                before = after;
238                beforeIsValid = true;
239            }
240            switch (errno) {
241            case 0:            // normal wakeup by server, or by binderDied()
242            case EWOULDBLOCK:  // benign race condition with server
243            case EINTR:        // wait was interrupted by signal or other spurious wakeup
244            case ETIMEDOUT:    // time-out expired
245                // FIXME these error/non-0 status are being dropped
246                break;
247            default:
248                status = errno;
249                ALOGE("%s unexpected error %s", __func__, strerror(status));
250                goto end;
251            }
252        }
253    }
254
255end:
256    if (status != NO_ERROR) {
257        buffer->mFrameCount = 0;
258        buffer->mRaw = NULL;
259        buffer->mNonContig = 0;
260        mUnreleased = 0;
261    }
262    if (elapsed != NULL) {
263        *elapsed = total;
264    }
265    if (requested == NULL) {
266        requested = &kNonBlocking;
267    }
268    if (measure) {
269        ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
270              requested->tv_sec, requested->tv_nsec / 1000000,
271              total.tv_sec, total.tv_nsec / 1000000);
272    }
273    return status;
274}
275
276void ClientProxy::releaseBuffer(Buffer* buffer)
277{
278    LOG_ALWAYS_FATAL_IF(buffer == NULL);
279    size_t stepCount = buffer->mFrameCount;
280    if (stepCount == 0 || mIsShutdown) {
281        // prevent accidental re-use of buffer
282        buffer->mFrameCount = 0;
283        buffer->mRaw = NULL;
284        buffer->mNonContig = 0;
285        return;
286    }
287    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
288    mUnreleased -= stepCount;
289    audio_track_cblk_t* cblk = mCblk;
290    // Both of these barriers are required
291    if (mIsOut) {
292        int32_t rear = cblk->u.mStreaming.mRear;
293        android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
294    } else {
295        int32_t front = cblk->u.mStreaming.mFront;
296        android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
297    }
298}
299
300void ClientProxy::binderDied()
301{
302    audio_track_cblk_t* cblk = mCblk;
303    if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
304        // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
305        (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
306                1);
307    }
308}
309
310void ClientProxy::interrupt()
311{
312    audio_track_cblk_t* cblk = mCblk;
313    if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
314        (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
315                1);
316    }
317}
318
319size_t ClientProxy::getMisalignment()
320{
321    audio_track_cblk_t* cblk = mCblk;
322    return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
323            (mFrameCountP2 - 1);
324}
325
326size_t ClientProxy::getFramesFilled() {
327    audio_track_cblk_t* cblk = mCblk;
328    int32_t front;
329    int32_t rear;
330
331    if (mIsOut) {
332        front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
333        rear = cblk->u.mStreaming.mRear;
334    } else {
335        rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
336        front = cblk->u.mStreaming.mFront;
337    }
338    ssize_t filled = rear - front;
339    // pipe should not be overfull
340    if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
341        ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
342        return 0;
343    }
344    return (size_t)filled;
345}
346
347// ---------------------------------------------------------------------------
348
349void AudioTrackClientProxy::flush()
350{
351    // This works for mFrameCountP2 <= 2^30
352    size_t increment = mFrameCountP2 << 1;
353    size_t mask = increment - 1;
354    audio_track_cblk_t* cblk = mCblk;
355    int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
356                        ((cblk->u.mStreaming.mFlush & ~mask) + increment);
357    android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
358}
359
360bool AudioTrackClientProxy::clearStreamEndDone() {
361    return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
362}
363
364bool AudioTrackClientProxy::getStreamEndDone() const {
365    return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
366}
367
368status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
369{
370    struct timespec total;          // total elapsed time spent waiting
371    total.tv_sec = 0;
372    total.tv_nsec = 0;
373    audio_track_cblk_t* cblk = mCblk;
374    status_t status;
375    enum {
376        TIMEOUT_ZERO,       // requested == NULL || *requested == 0
377        TIMEOUT_INFINITE,   // *requested == infinity
378        TIMEOUT_FINITE,     // 0 < *requested < infinity
379        TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
380    } timeout;
381    if (requested == NULL) {
382        timeout = TIMEOUT_ZERO;
383    } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
384        timeout = TIMEOUT_ZERO;
385    } else if (requested->tv_sec == INT_MAX) {
386        timeout = TIMEOUT_INFINITE;
387    } else {
388        timeout = TIMEOUT_FINITE;
389    }
390    for (;;) {
391        int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
392        // check for track invalidation by server, or server death detection
393        if (flags & CBLK_INVALID) {
394            ALOGV("Track invalidated");
395            status = DEAD_OBJECT;
396            goto end;
397        }
398        if (flags & CBLK_STREAM_END_DONE) {
399            ALOGV("stream end received");
400            status = NO_ERROR;
401            goto end;
402        }
403        // check for obtainBuffer interrupted by client
404        // check for obtainBuffer interrupted by client
405        if (flags & CBLK_INTERRUPT) {
406            ALOGV("waitStreamEndDone() interrupted by client");
407            status = -EINTR;
408            goto end;
409        }
410        struct timespec remaining;
411        const struct timespec *ts;
412        switch (timeout) {
413        case TIMEOUT_ZERO:
414            status = WOULD_BLOCK;
415            goto end;
416        case TIMEOUT_INFINITE:
417            ts = NULL;
418            break;
419        case TIMEOUT_FINITE:
420            timeout = TIMEOUT_CONTINUE;
421            if (MAX_SEC == 0) {
422                ts = requested;
423                break;
424            }
425            // fall through
426        case TIMEOUT_CONTINUE:
427            // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
428            if (requested->tv_sec < total.tv_sec ||
429                    (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
430                status = TIMED_OUT;
431                goto end;
432            }
433            remaining.tv_sec = requested->tv_sec - total.tv_sec;
434            if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
435                remaining.tv_nsec += 1000000000;
436                remaining.tv_sec++;
437            }
438            if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
439                remaining.tv_sec = MAX_SEC;
440                remaining.tv_nsec = 0;
441            }
442            ts = &remaining;
443            break;
444        default:
445            LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
446            ts = NULL;
447            break;
448        }
449        int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
450        if (!(old & CBLK_FUTEX_WAKE)) {
451            errno = 0;
452            (void) syscall(__NR_futex, &cblk->mFutex,
453                    mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
454            switch (errno) {
455            case 0:            // normal wakeup by server, or by binderDied()
456            case EWOULDBLOCK:  // benign race condition with server
457            case EINTR:        // wait was interrupted by signal or other spurious wakeup
458            case ETIMEDOUT:    // time-out expired
459                break;
460            default:
461                status = errno;
462                ALOGE("%s unexpected error %s", __func__, strerror(status));
463                goto end;
464            }
465        }
466    }
467
468end:
469    if (requested == NULL) {
470        requested = &kNonBlocking;
471    }
472    return status;
473}
474
475// ---------------------------------------------------------------------------
476
477StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
478        size_t frameCount, size_t frameSize)
479    : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
480      mMutator(&cblk->u.mStatic.mSingleStateQueue), mBufferPosition(0)
481{
482}
483
484void StaticAudioTrackClientProxy::flush()
485{
486    LOG_ALWAYS_FATAL("static flush");
487}
488
489void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
490{
491    // This can only happen on a 64-bit client
492    if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
493        // FIXME Should return an error status
494        return;
495    }
496    StaticAudioTrackState newState;
497    newState.mLoopStart = (uint32_t) loopStart;
498    newState.mLoopEnd = (uint32_t) loopEnd;
499    newState.mLoopCount = loopCount;
500    mBufferPosition = loopStart;
501    (void) mMutator.push(newState);
502}
503
504size_t StaticAudioTrackClientProxy::getBufferPosition()
505{
506    size_t bufferPosition;
507    if (mMutator.ack()) {
508        bufferPosition = (size_t) mCblk->u.mStatic.mBufferPosition;
509        if (bufferPosition > mFrameCount) {
510            bufferPosition = mFrameCount;
511        }
512    } else {
513        bufferPosition = mBufferPosition;
514    }
515    return bufferPosition;
516}
517
518// ---------------------------------------------------------------------------
519
520ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
521        size_t frameSize, bool isOut, bool clientInServer)
522    : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
523      mAvailToClient(0), mFlush(0)
524{
525}
526
527status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
528{
529    LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
530    if (mIsShutdown) {
531        goto no_init;
532    }
533    {
534    audio_track_cblk_t* cblk = mCblk;
535    // compute number of frames available to write (AudioTrack) or read (AudioRecord),
536    // or use previous cached value from framesReady(), with added barrier if it omits.
537    int32_t front;
538    int32_t rear;
539    // See notes on barriers at ClientProxy::obtainBuffer()
540    if (mIsOut) {
541        int32_t flush = cblk->u.mStreaming.mFlush;
542        rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
543        front = cblk->u.mStreaming.mFront;
544        if (flush != mFlush) {
545            // effectively obtain then release whatever is in the buffer
546            size_t mask = (mFrameCountP2 << 1) - 1;
547            int32_t newFront = (front & ~mask) | (flush & mask);
548            ssize_t filled = rear - newFront;
549            // Rather than shutting down on a corrupt flush, just treat it as a full flush
550            if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
551                ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, filled %d=%#x",
552                        mFlush, flush, front, rear, mask, newFront, filled, filled);
553                newFront = rear;
554            }
555            mFlush = flush;
556            android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
557            // There is no danger from a false positive, so err on the side of caution
558            if (true /*front != newFront*/) {
559                int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
560                if (!(old & CBLK_FUTEX_WAKE)) {
561                    (void) syscall(__NR_futex, &cblk->mFutex,
562                            mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
563                }
564            }
565            front = newFront;
566        }
567    } else {
568        front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
569        rear = cblk->u.mStreaming.mRear;
570    }
571    ssize_t filled = rear - front;
572    // pipe should not already be overfull
573    if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
574        ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
575        mIsShutdown = true;
576    }
577    if (mIsShutdown) {
578        goto no_init;
579    }
580    // don't allow filling pipe beyond the nominal size
581    size_t availToServer;
582    if (mIsOut) {
583        availToServer = filled;
584        mAvailToClient = mFrameCount - filled;
585    } else {
586        availToServer = mFrameCount - filled;
587        mAvailToClient = filled;
588    }
589    // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
590    size_t part1;
591    if (mIsOut) {
592        front &= mFrameCountP2 - 1;
593        part1 = mFrameCountP2 - front;
594    } else {
595        rear &= mFrameCountP2 - 1;
596        part1 = mFrameCountP2 - rear;
597    }
598    if (part1 > availToServer) {
599        part1 = availToServer;
600    }
601    size_t ask = buffer->mFrameCount;
602    if (part1 > ask) {
603        part1 = ask;
604    }
605    // is assignment redundant in some cases?
606    buffer->mFrameCount = part1;
607    buffer->mRaw = part1 > 0 ?
608            &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
609    buffer->mNonContig = availToServer - part1;
610    // After flush(), allow releaseBuffer() on a previously obtained buffer;
611    // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
612    if (!ackFlush) {
613        mUnreleased = part1;
614    }
615    return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
616    }
617no_init:
618    buffer->mFrameCount = 0;
619    buffer->mRaw = NULL;
620    buffer->mNonContig = 0;
621    mUnreleased = 0;
622    return NO_INIT;
623}
624
625void ServerProxy::releaseBuffer(Buffer* buffer)
626{
627    LOG_ALWAYS_FATAL_IF(buffer == NULL);
628    size_t stepCount = buffer->mFrameCount;
629    if (stepCount == 0 || mIsShutdown) {
630        // prevent accidental re-use of buffer
631        buffer->mFrameCount = 0;
632        buffer->mRaw = NULL;
633        buffer->mNonContig = 0;
634        return;
635    }
636    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
637    mUnreleased -= stepCount;
638    audio_track_cblk_t* cblk = mCblk;
639    if (mIsOut) {
640        int32_t front = cblk->u.mStreaming.mFront;
641        android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
642    } else {
643        int32_t rear = cblk->u.mStreaming.mRear;
644        android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
645    }
646
647    cblk->mServer += stepCount;
648
649    size_t half = mFrameCount / 2;
650    if (half == 0) {
651        half = 1;
652    }
653    size_t minimum = (size_t) cblk->mMinimum;
654    if (minimum == 0) {
655        minimum = mIsOut ? half : 1;
656    } else if (minimum > half) {
657        minimum = half;
658    }
659    // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
660    if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
661        ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
662        int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
663        if (!(old & CBLK_FUTEX_WAKE)) {
664            (void) syscall(__NR_futex, &cblk->mFutex,
665                    mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
666        }
667    }
668
669    buffer->mFrameCount = 0;
670    buffer->mRaw = NULL;
671    buffer->mNonContig = 0;
672}
673
674// ---------------------------------------------------------------------------
675
676size_t AudioTrackServerProxy::framesReady()
677{
678    LOG_ALWAYS_FATAL_IF(!mIsOut);
679
680    if (mIsShutdown) {
681        return 0;
682    }
683    audio_track_cblk_t* cblk = mCblk;
684
685    int32_t flush = cblk->u.mStreaming.mFlush;
686    if (flush != mFlush) {
687        // FIXME should return an accurate value, but over-estimate is better than under-estimate
688        return mFrameCount;
689    }
690    // the acquire might not be necessary since not doing a subsequent read
691    int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
692    ssize_t filled = rear - cblk->u.mStreaming.mFront;
693    // pipe should not already be overfull
694    if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
695        ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
696        mIsShutdown = true;
697        return 0;
698    }
699    //  cache this value for later use by obtainBuffer(), with added barrier
700    //  and racy if called by normal mixer thread
701    // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
702    return filled;
703}
704
705bool  AudioTrackServerProxy::setStreamEndDone() {
706    audio_track_cblk_t* cblk = mCblk;
707    bool old =
708            (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
709    if (!old) {
710        (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
711                1);
712    }
713    return old;
714}
715
716void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
717{
718    audio_track_cblk_t* cblk = mCblk;
719    cblk->u.mStreaming.mUnderrunFrames += frameCount;
720
721    // FIXME also wake futex so that underrun is noticed more quickly
722    (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
723}
724
725// ---------------------------------------------------------------------------
726
727StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
728        size_t frameCount, size_t frameSize)
729    : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
730      mObserver(&cblk->u.mStatic.mSingleStateQueue), mPosition(0),
731      mEnd(frameCount), mFramesReadyIsCalledByMultipleThreads(false)
732{
733    mState.mLoopStart = 0;
734    mState.mLoopEnd = 0;
735    mState.mLoopCount = 0;
736}
737
738void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
739{
740    mFramesReadyIsCalledByMultipleThreads = true;
741}
742
743size_t StaticAudioTrackServerProxy::framesReady()
744{
745    // FIXME
746    // This is racy if called by normal mixer thread,
747    // as we're reading 2 independent variables without a lock.
748    // Can't call mObserver.poll(), as we might be called from wrong thread.
749    // If looping is enabled, should return a higher number (since includes non-contiguous).
750    size_t position = mPosition;
751    if (!mFramesReadyIsCalledByMultipleThreads) {
752        ssize_t positionOrStatus = pollPosition();
753        if (positionOrStatus >= 0) {
754            position = (size_t) positionOrStatus;
755        }
756    }
757    size_t end = mEnd;
758    return position < end ? end - position : 0;
759}
760
761ssize_t StaticAudioTrackServerProxy::pollPosition()
762{
763    size_t position = mPosition;
764    StaticAudioTrackState state;
765    if (mObserver.poll(state)) {
766        bool valid = false;
767        size_t loopStart = state.mLoopStart;
768        size_t loopEnd = state.mLoopEnd;
769        if (state.mLoopCount == 0) {
770            if (loopStart > mFrameCount) {
771                loopStart = mFrameCount;
772            }
773            // ignore loopEnd
774            mPosition = position = loopStart;
775            mEnd = mFrameCount;
776            mState.mLoopCount = 0;
777            valid = true;
778        } else {
779            if (loopStart < loopEnd && loopEnd <= mFrameCount &&
780                    loopEnd - loopStart >= MIN_LOOP) {
781                if (!(loopStart <= position && position < loopEnd)) {
782                    mPosition = position = loopStart;
783                }
784                mEnd = loopEnd;
785                mState = state;
786                valid = true;
787            }
788        }
789        if (!valid) {
790            ALOGE("%s client pushed an invalid state, shutting down", __func__);
791            mIsShutdown = true;
792            return (ssize_t) NO_INIT;
793        }
794        // This may overflow, but client is not supposed to rely on it
795        mCblk->u.mStatic.mBufferPosition = (uint32_t) position;
796    }
797    return (ssize_t) position;
798}
799
800status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush __unused)
801{
802    if (mIsShutdown) {
803        buffer->mFrameCount = 0;
804        buffer->mRaw = NULL;
805        buffer->mNonContig = 0;
806        mUnreleased = 0;
807        return NO_INIT;
808    }
809    ssize_t positionOrStatus = pollPosition();
810    if (positionOrStatus < 0) {
811        buffer->mFrameCount = 0;
812        buffer->mRaw = NULL;
813        buffer->mNonContig = 0;
814        mUnreleased = 0;
815        return (status_t) positionOrStatus;
816    }
817    size_t position = (size_t) positionOrStatus;
818    size_t avail;
819    if (position < mEnd) {
820        avail = mEnd - position;
821        size_t wanted = buffer->mFrameCount;
822        if (avail < wanted) {
823            buffer->mFrameCount = avail;
824        } else {
825            avail = wanted;
826        }
827        buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
828    } else {
829        avail = 0;
830        buffer->mFrameCount = 0;
831        buffer->mRaw = NULL;
832    }
833    buffer->mNonContig = 0;     // FIXME should be > 0 for looping
834    mUnreleased = avail;
835    return NO_ERROR;
836}
837
838void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
839{
840    size_t stepCount = buffer->mFrameCount;
841    LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
842    if (stepCount == 0) {
843        // prevent accidental re-use of buffer
844        buffer->mRaw = NULL;
845        buffer->mNonContig = 0;
846        return;
847    }
848    mUnreleased -= stepCount;
849    audio_track_cblk_t* cblk = mCblk;
850    size_t position = mPosition;
851    size_t newPosition = position + stepCount;
852    int32_t setFlags = 0;
853    if (!(position <= newPosition && newPosition <= mFrameCount)) {
854        ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position, mFrameCount);
855        newPosition = mFrameCount;
856    } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
857        if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
858            newPosition = mState.mLoopStart;
859            setFlags = CBLK_LOOP_CYCLE;
860        } else {
861            mEnd = mFrameCount;     // this is what allows playback to continue after the loop
862            setFlags = CBLK_LOOP_FINAL;
863        }
864    }
865    if (newPosition == mFrameCount) {
866        setFlags |= CBLK_BUFFER_END;
867    }
868    mPosition = newPosition;
869
870    cblk->mServer += stepCount;
871    // This may overflow, but client is not supposed to rely on it
872    cblk->u.mStatic.mBufferPosition = (uint32_t) newPosition;
873    if (setFlags != 0) {
874        (void) android_atomic_or(setFlags, &cblk->mFlags);
875        // this would be a good place to wake a futex
876    }
877
878    buffer->mFrameCount = 0;
879    buffer->mRaw = NULL;
880    buffer->mNonContig = 0;
881}
882
883void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount __unused)
884{
885    // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
886    // we don't have a location to count underrun frames.  The underrun frame counter
887    // only exists in AudioTrackSharedStreaming.  Fortunately, underruns are not
888    // possible for static buffer tracks other than at end of buffer, so this is not a loss.
889
890    // FIXME also wake futex so that underrun is noticed more quickly
891    (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
892}
893
894// ---------------------------------------------------------------------------
895
896}   // namespace android
897