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 <android-base/macros.h>
21 #include <private/media/AudioTrackShared.h>
22 #include <utils/Log.h>
23 #include <audio_utils/safe_math.h>
24 
25 #include <linux/futex.h>
26 #include <sys/syscall.h>
27 
28 namespace android {
29 
30 // used to clamp a value to size_t.  TODO: move to another file.
31 template <typename T>
clampToSize(T x)32 size_t clampToSize(T x) {
33     return sizeof(T) > sizeof(size_t) && x > (T) SIZE_MAX ? SIZE_MAX : x < 0 ? 0 : (size_t) x;
34 }
35 
36 // incrementSequence is used to determine the next sequence value
37 // for the loop and position sequence counters.  It should return
38 // a value between "other" + 1 and "other" + INT32_MAX, the choice of
39 // which needs to be the "least recently used" sequence value for "self".
40 // In general, this means (new_self) returned is max(self, other) + 1.
41 __attribute__((no_sanitize("integer")))
incrementSequence(uint32_t self,uint32_t other)42 static uint32_t incrementSequence(uint32_t self, uint32_t other) {
43     int32_t diff = (int32_t) self - (int32_t) other;
44     if (diff >= 0 && diff < INT32_MAX) {
45         return self + 1; // we're already ahead of other.
46     }
47     return other + 1; // we're behind, so move just ahead of other.
48 }
49 
audio_track_cblk_t()50 audio_track_cblk_t::audio_track_cblk_t()
51     : mServer(0), mFutex(0), mMinimum(0)
52     , mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0)
53     , mBufferSizeInFrames(0)
54     , mFlags(0)
55 {
56     memset(&u, 0, sizeof(u));
57 }
58 
59 // ---------------------------------------------------------------------------
60 
Proxy(audio_track_cblk_t * cblk,void * buffers,size_t frameCount,size_t frameSize,bool isOut,bool clientInServer)61 Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
62         bool isOut, bool clientInServer)
63     : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
64       mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
65       mIsShutdown(false), mUnreleased(0)
66 {
67 }
68 
69 // ---------------------------------------------------------------------------
70 
ClientProxy(audio_track_cblk_t * cblk,void * buffers,size_t frameCount,size_t frameSize,bool isOut,bool clientInServer)71 ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
72         size_t frameSize, bool isOut, bool clientInServer)
73     : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
74     , mEpoch(0)
75     , mTimestampObserver(&cblk->mExtendedTimestampQueue)
76 {
77     setBufferSizeInFrames(frameCount);
78 }
79 
80 const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
81 const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
82 
83 #define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
84 
85 // To facilitate quicker recovery from server failure, this value limits the timeout per each futex
86 // wait.  However it does not protect infinite timeouts.  If defined to be zero, there is no limit.
87 // FIXME May not be compatible with audio tunneling requirements where timeout should be in the
88 // order of minutes.
89 #define MAX_SEC    5
90 
setBufferSizeInFrames(uint32_t size)91 uint32_t ClientProxy::setBufferSizeInFrames(uint32_t size)
92 {
93     // The minimum should be  greater than zero and less than the size
94     // at which underruns will occur.
95     const uint32_t minimum = 16; // based on AudioMixer::BLOCKSIZE
96     const uint32_t maximum = frameCount();
97     uint32_t clippedSize = size;
98     if (maximum < minimum) {
99         clippedSize = maximum;
100     } else if (clippedSize < minimum) {
101         clippedSize = minimum;
102     } else if (clippedSize > maximum) {
103         clippedSize = maximum;
104     }
105     // for server to read
106     android_atomic_release_store(clippedSize, (int32_t *)&mCblk->mBufferSizeInFrames);
107     // for client to read
108     mBufferSizeInFrames = clippedSize;
109     return clippedSize;
110 }
111 
112 __attribute__((no_sanitize("integer")))
obtainBuffer(Buffer * buffer,const struct timespec * requested,struct timespec * elapsed)113 status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
114         struct timespec *elapsed)
115 {
116     LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
117             "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
118     struct timespec total;          // total elapsed time spent waiting
119     total.tv_sec = 0;
120     total.tv_nsec = 0;
121     bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
122 
123     status_t status;
124     enum {
125         TIMEOUT_ZERO,       // requested == NULL || *requested == 0
126         TIMEOUT_INFINITE,   // *requested == infinity
127         TIMEOUT_FINITE,     // 0 < *requested < infinity
128         TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
129     } timeout;
130     if (requested == NULL) {
131         timeout = TIMEOUT_ZERO;
132     } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
133         timeout = TIMEOUT_ZERO;
134     } else if (requested->tv_sec == INT_MAX) {
135         timeout = TIMEOUT_INFINITE;
136     } else {
137         timeout = TIMEOUT_FINITE;
138         if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
139             measure = true;
140         }
141     }
142     struct timespec before;
143     bool beforeIsValid = false;
144     audio_track_cblk_t* cblk = mCblk;
145     bool ignoreInitialPendingInterrupt = true;
146     // check for shared memory corruption
147     if (mIsShutdown) {
148         status = NO_INIT;
149         goto end;
150     }
151     for (;;) {
152         int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
153         // check for track invalidation by server, or server death detection
154         if (flags & CBLK_INVALID) {
155             ALOGV("Track invalidated");
156             status = DEAD_OBJECT;
157             goto end;
158         }
159         if (flags & CBLK_DISABLED) {
160             ALOGV("Track disabled");
161             status = NOT_ENOUGH_DATA;
162             goto end;
163         }
164         // check for obtainBuffer interrupted by client
165         if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
166             ALOGV("obtainBuffer() interrupted by client");
167             status = -EINTR;
168             goto end;
169         }
170         ignoreInitialPendingInterrupt = false;
171         // compute number of frames available to write (AudioTrack) or read (AudioRecord)
172         int32_t front;
173         int32_t rear;
174         if (mIsOut) {
175             // The barrier following the read of mFront is probably redundant.
176             // We're about to perform a conditional branch based on 'filled',
177             // which will force the processor to observe the read of mFront
178             // prior to allowing data writes starting at mRaw.
179             // However, the processor may support speculative execution,
180             // and be unable to undo speculative writes into shared memory.
181             // The barrier will prevent such speculative execution.
182             front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
183             rear = cblk->u.mStreaming.mRear;
184         } else {
185             // On the other hand, this barrier is required.
186             rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
187             front = cblk->u.mStreaming.mFront;
188         }
189         // write to rear, read from front
190         ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
191         // pipe should not be overfull
192         if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
193             if (mIsOut) {
194                 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
195                         "shutting down", filled, mFrameCount);
196                 mIsShutdown = true;
197                 status = NO_INIT;
198                 goto end;
199             }
200             // for input, sync up on overrun
201             filled = 0;
202             cblk->u.mStreaming.mFront = rear;
203             (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
204         }
205         // Don't allow filling pipe beyond the user settable size.
206         // The calculation for avail can go negative if the buffer size
207         // is suddenly dropped below the amount already in the buffer.
208         // So use a signed calculation to prevent a numeric overflow abort.
209         ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
210         ssize_t avail =  (mIsOut) ? adjustableSize - filled : filled;
211         if (avail < 0) {
212             avail = 0;
213         } else if (avail > 0) {
214             // 'avail' may be non-contiguous, so return only the first contiguous chunk
215             size_t part1;
216             if (mIsOut) {
217                 rear &= mFrameCountP2 - 1;
218                 part1 = mFrameCountP2 - rear;
219             } else {
220                 front &= mFrameCountP2 - 1;
221                 part1 = mFrameCountP2 - front;
222             }
223             if (part1 > (size_t)avail) {
224                 part1 = avail;
225             }
226             if (part1 > buffer->mFrameCount) {
227                 part1 = buffer->mFrameCount;
228             }
229             buffer->mFrameCount = part1;
230             buffer->mRaw = part1 > 0 ?
231                     &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
232             buffer->mNonContig = avail - part1;
233             mUnreleased = part1;
234             status = NO_ERROR;
235             break;
236         }
237         struct timespec remaining;
238         const struct timespec *ts;
239         switch (timeout) {
240         case TIMEOUT_ZERO:
241             status = WOULD_BLOCK;
242             goto end;
243         case TIMEOUT_INFINITE:
244             ts = NULL;
245             break;
246         case TIMEOUT_FINITE:
247             timeout = TIMEOUT_CONTINUE;
248             if (MAX_SEC == 0) {
249                 ts = requested;
250                 break;
251             }
252             FALLTHROUGH_INTENDED;
253         case TIMEOUT_CONTINUE:
254             // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
255             if (!measure || requested->tv_sec < total.tv_sec ||
256                     (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
257                 status = TIMED_OUT;
258                 goto end;
259             }
260             remaining.tv_sec = requested->tv_sec - total.tv_sec;
261             if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
262                 remaining.tv_nsec += 1000000000;
263                 remaining.tv_sec++;
264             }
265             if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
266                 remaining.tv_sec = MAX_SEC;
267                 remaining.tv_nsec = 0;
268             }
269             ts = &remaining;
270             break;
271         default:
272             LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
273             ts = NULL;
274             break;
275         }
276         int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
277         if (!(old & CBLK_FUTEX_WAKE)) {
278             if (measure && !beforeIsValid) {
279                 clock_gettime(CLOCK_MONOTONIC, &before);
280                 beforeIsValid = true;
281             }
282             errno = 0;
283             (void) syscall(__NR_futex, &cblk->mFutex,
284                     mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
285             status_t error = errno; // clock_gettime can affect errno
286             // update total elapsed time spent waiting
287             if (measure) {
288                 struct timespec after;
289                 clock_gettime(CLOCK_MONOTONIC, &after);
290                 total.tv_sec += after.tv_sec - before.tv_sec;
291                 // Use auto instead of long to avoid the google-runtime-int warning.
292                 auto deltaNs = after.tv_nsec - before.tv_nsec;
293                 if (deltaNs < 0) {
294                     deltaNs += 1000000000;
295                     total.tv_sec--;
296                 }
297                 if ((total.tv_nsec += deltaNs) >= 1000000000) {
298                     total.tv_nsec -= 1000000000;
299                     total.tv_sec++;
300                 }
301                 before = after;
302                 beforeIsValid = true;
303             }
304             switch (error) {
305             case 0:            // normal wakeup by server, or by binderDied()
306             case EWOULDBLOCK:  // benign race condition with server
307             case EINTR:        // wait was interrupted by signal or other spurious wakeup
308             case ETIMEDOUT:    // time-out expired
309                 // FIXME these error/non-0 status are being dropped
310                 break;
311             default:
312                 status = error;
313                 ALOGE("%s unexpected error %s", __func__, strerror(status));
314                 goto end;
315             }
316         }
317     }
318 
319 end:
320     if (status != NO_ERROR) {
321         buffer->mFrameCount = 0;
322         buffer->mRaw = NULL;
323         buffer->mNonContig = 0;
324         mUnreleased = 0;
325     }
326     if (elapsed != NULL) {
327         *elapsed = total;
328     }
329     if (requested == NULL) {
330         requested = &kNonBlocking;
331     }
332     if (measure) {
333         ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
334               requested->tv_sec, requested->tv_nsec / 1000000,
335               total.tv_sec, total.tv_nsec / 1000000);
336     }
337     return status;
338 }
339 
340 __attribute__((no_sanitize("integer")))
releaseBuffer(Buffer * buffer)341 void ClientProxy::releaseBuffer(Buffer* buffer)
342 {
343     LOG_ALWAYS_FATAL_IF(buffer == NULL);
344     size_t stepCount = buffer->mFrameCount;
345     if (stepCount == 0 || mIsShutdown) {
346         // prevent accidental re-use of buffer
347         buffer->mFrameCount = 0;
348         buffer->mRaw = NULL;
349         buffer->mNonContig = 0;
350         return;
351     }
352     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
353             "%s: mUnreleased out of range, "
354             "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu), BufferSizeInFrames:%u",
355             __func__, stepCount, mUnreleased, mFrameCount, getBufferSizeInFrames());
356     mUnreleased -= stepCount;
357     audio_track_cblk_t* cblk = mCblk;
358     // Both of these barriers are required
359     if (mIsOut) {
360         int32_t rear = cblk->u.mStreaming.mRear;
361         android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
362     } else {
363         int32_t front = cblk->u.mStreaming.mFront;
364         android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
365     }
366 }
367 
binderDied()368 void ClientProxy::binderDied()
369 {
370     audio_track_cblk_t* cblk = mCblk;
371     if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
372         android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
373         // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
374         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
375                 1);
376     }
377 }
378 
interrupt()379 void ClientProxy::interrupt()
380 {
381     audio_track_cblk_t* cblk = mCblk;
382     if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
383         android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
384         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
385                 1);
386     }
387 }
388 
389 __attribute__((no_sanitize("integer")))
getMisalignment()390 size_t ClientProxy::getMisalignment()
391 {
392     audio_track_cblk_t* cblk = mCblk;
393     return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
394             (mFrameCountP2 - 1);
395 }
396 
397 // ---------------------------------------------------------------------------
398 
flush()399 void AudioTrackClientProxy::flush()
400 {
401     sendStreamingFlushStop(true /* flush */);
402 }
403 
stop()404 void AudioTrackClientProxy::stop()
405 {
406     sendStreamingFlushStop(false /* flush */);
407 }
408 
409 // Sets the client-written mFlush and mStop positions, which control server behavior.
410 //
411 // @param flush indicates whether the operation is a flush or stop.
412 // A client stop sets mStop to the current write position;
413 // the server will not read past this point until start() or subsequent flush().
414 // A client flush sets both mStop and mFlush to the current write position.
415 // This advances the server read limit (if previously set) and on the next
416 // server read advances the server read position to this limit.
417 //
sendStreamingFlushStop(bool flush)418 void AudioTrackClientProxy::sendStreamingFlushStop(bool flush)
419 {
420     // TODO: Replace this by 64 bit counters - avoids wrap complication.
421     // This works for mFrameCountP2 <= 2^30
422     // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
423     // Should newFlush = cblk->u.mStreaming.mRear?  Only problem is
424     // if you want to flush twice to the same rear location after a 32 bit wrap.
425 
426     const size_t increment = mFrameCountP2 << 1;
427     const size_t mask = increment - 1;
428     // No need for client atomic synchronization on mRear, mStop, mFlush
429     // as AudioTrack client only read/writes to them under client lock. Server only reads.
430     const int32_t rearMasked = mCblk->u.mStreaming.mRear & mask;
431 
432     // update stop before flush so that the server front
433     // never advances beyond a (potential) previous stop's rear limit.
434     int32_t stopBits; // the following add can overflow
435     __builtin_add_overflow(mCblk->u.mStreaming.mStop & ~mask, increment, &stopBits);
436     android_atomic_release_store(rearMasked | stopBits, &mCblk->u.mStreaming.mStop);
437 
438     if (flush) {
439         int32_t flushBits; // the following add can overflow
440         __builtin_add_overflow(mCblk->u.mStreaming.mFlush & ~mask, increment, &flushBits);
441         android_atomic_release_store(rearMasked | flushBits, &mCblk->u.mStreaming.mFlush);
442     }
443 }
444 
clearStreamEndDone()445 bool AudioTrackClientProxy::clearStreamEndDone() {
446     return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
447 }
448 
getStreamEndDone() const449 bool AudioTrackClientProxy::getStreamEndDone() const {
450     return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
451 }
452 
waitStreamEndDone(const struct timespec * requested)453 status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
454 {
455     struct timespec total;          // total elapsed time spent waiting
456     total.tv_sec = 0;
457     total.tv_nsec = 0;
458     audio_track_cblk_t* cblk = mCblk;
459     status_t status;
460     enum {
461         TIMEOUT_ZERO,       // requested == NULL || *requested == 0
462         TIMEOUT_INFINITE,   // *requested == infinity
463         TIMEOUT_FINITE,     // 0 < *requested < infinity
464         TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
465     } timeout;
466     if (requested == NULL) {
467         timeout = TIMEOUT_ZERO;
468     } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
469         timeout = TIMEOUT_ZERO;
470     } else if (requested->tv_sec == INT_MAX) {
471         timeout = TIMEOUT_INFINITE;
472     } else {
473         timeout = TIMEOUT_FINITE;
474     }
475     for (;;) {
476         int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
477         // check for track invalidation by server, or server death detection
478         if (flags & CBLK_INVALID) {
479             ALOGV("Track invalidated");
480             status = DEAD_OBJECT;
481             goto end;
482         }
483         // a track is not supposed to underrun at this stage but consider it done
484         if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
485             ALOGV("stream end received");
486             status = NO_ERROR;
487             goto end;
488         }
489         // check for obtainBuffer interrupted by client
490         if (flags & CBLK_INTERRUPT) {
491             ALOGV("waitStreamEndDone() interrupted by client");
492             status = -EINTR;
493             goto end;
494         }
495         struct timespec remaining;
496         const struct timespec *ts;
497         switch (timeout) {
498         case TIMEOUT_ZERO:
499             status = WOULD_BLOCK;
500             goto end;
501         case TIMEOUT_INFINITE:
502             ts = NULL;
503             break;
504         case TIMEOUT_FINITE:
505             timeout = TIMEOUT_CONTINUE;
506             if (MAX_SEC == 0) {
507                 ts = requested;
508                 break;
509             }
510             FALLTHROUGH_INTENDED;
511         case TIMEOUT_CONTINUE:
512             // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
513             if (requested->tv_sec < total.tv_sec ||
514                     (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
515                 status = TIMED_OUT;
516                 goto end;
517             }
518             remaining.tv_sec = requested->tv_sec - total.tv_sec;
519             if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
520                 remaining.tv_nsec += 1000000000;
521                 remaining.tv_sec++;
522             }
523             if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
524                 remaining.tv_sec = MAX_SEC;
525                 remaining.tv_nsec = 0;
526             }
527             ts = &remaining;
528             break;
529         default:
530             LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
531             ts = NULL;
532             break;
533         }
534         int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
535         if (!(old & CBLK_FUTEX_WAKE)) {
536             errno = 0;
537             (void) syscall(__NR_futex, &cblk->mFutex,
538                     mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
539             switch (errno) {
540             case 0:            // normal wakeup by server, or by binderDied()
541             case EWOULDBLOCK:  // benign race condition with server
542             case EINTR:        // wait was interrupted by signal or other spurious wakeup
543             case ETIMEDOUT:    // time-out expired
544                 break;
545             default:
546                 status = errno;
547                 ALOGE("%s unexpected error %s", __func__, strerror(status));
548                 goto end;
549             }
550         }
551     }
552 
553 end:
554     if (requested == NULL) {
555         requested = &kNonBlocking;
556     }
557     return status;
558 }
559 
560 // ---------------------------------------------------------------------------
561 
StaticAudioTrackClientProxy(audio_track_cblk_t * cblk,void * buffers,size_t frameCount,size_t frameSize)562 StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
563         size_t frameCount, size_t frameSize)
564     : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
565       mMutator(&cblk->u.mStatic.mSingleStateQueue),
566       mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
567 {
568     memset(&mState, 0, sizeof(mState));
569     memset(&mPosLoop, 0, sizeof(mPosLoop));
570 }
571 
flush()572 void StaticAudioTrackClientProxy::flush()
573 {
574     LOG_ALWAYS_FATAL("static flush");
575 }
576 
stop()577 void StaticAudioTrackClientProxy::stop()
578 {
579     ; // no special handling required for static tracks.
580 }
581 
setLoop(size_t loopStart,size_t loopEnd,int loopCount)582 void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
583 {
584     // This can only happen on a 64-bit client
585     if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
586         // FIXME Should return an error status
587         return;
588     }
589     mState.mLoopStart = (uint32_t) loopStart;
590     mState.mLoopEnd = (uint32_t) loopEnd;
591     mState.mLoopCount = loopCount;
592     mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
593     // set patch-up variables until the mState is acknowledged by the ServerProxy.
594     // observed buffer position and loop count will freeze until then to give the
595     // illusion of a synchronous change.
596     getBufferPositionAndLoopCount(NULL, NULL);
597     // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
598     if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
599         mPosLoop.mBufferPosition = mState.mLoopStart;
600     }
601     mPosLoop.mLoopCount = mState.mLoopCount;
602     (void) mMutator.push(mState);
603 }
604 
setBufferPosition(size_t position)605 void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
606 {
607     // This can only happen on a 64-bit client
608     if (position > UINT32_MAX) {
609         // FIXME Should return an error status
610         return;
611     }
612     mState.mPosition = (uint32_t) position;
613     mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
614     // set patch-up variables until the mState is acknowledged by the ServerProxy.
615     // observed buffer position and loop count will freeze until then to give the
616     // illusion of a synchronous change.
617     if (mState.mLoopCount > 0) {  // only check if loop count is changing
618         getBufferPositionAndLoopCount(NULL, NULL); // get last position
619     }
620     mPosLoop.mBufferPosition = position;
621     if (position >= mState.mLoopEnd) {
622         // no ongoing loop is possible if position is greater than loopEnd.
623         mPosLoop.mLoopCount = 0;
624     }
625     (void) mMutator.push(mState);
626 }
627 
setBufferPositionAndLoop(size_t position,size_t loopStart,size_t loopEnd,int loopCount)628 void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
629         size_t loopEnd, int loopCount)
630 {
631     setLoop(loopStart, loopEnd, loopCount);
632     setBufferPosition(position);
633 }
634 
getBufferPosition()635 size_t StaticAudioTrackClientProxy::getBufferPosition()
636 {
637     getBufferPositionAndLoopCount(NULL, NULL);
638     return mPosLoop.mBufferPosition;
639 }
640 
getBufferPositionAndLoopCount(size_t * position,int * loopCount)641 void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
642         size_t *position, int *loopCount)
643 {
644     if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
645          if (mPosLoopObserver.poll(mPosLoop)) {
646              ; // a valid mPosLoop should be available if ackDone is true.
647          }
648     }
649     if (position != NULL) {
650         *position = mPosLoop.mBufferPosition;
651     }
652     if (loopCount != NULL) {
653         *loopCount = mPosLoop.mLoopCount;
654     }
655 }
656 
657 // ---------------------------------------------------------------------------
658 
ServerProxy(audio_track_cblk_t * cblk,void * buffers,size_t frameCount,size_t frameSize,bool isOut,bool clientInServer)659 ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
660         size_t frameSize, bool isOut, bool clientInServer)
661     : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
662       mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
663     , mTimestampMutator(&cblk->mExtendedTimestampQueue)
664 {
665     cblk->mBufferSizeInFrames = frameCount;
666 }
667 
668 __attribute__((no_sanitize("integer")))
flushBufferIfNeeded()669 void ServerProxy::flushBufferIfNeeded()
670 {
671     audio_track_cblk_t* cblk = mCblk;
672     // The acquire_load is not really required. But since the write is a release_store in the
673     // client, using acquire_load here makes it easier for people to maintain the code,
674     // and the logic for communicating ipc variables seems somewhat standard,
675     // and there really isn't much penalty for 4 or 8 byte atomics.
676     int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
677     if (flush != mFlush) {
678         ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
679                 flush, mFlush);
680         // shouldn't matter, but for range safety use mRear instead of getRear().
681         int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
682         int32_t front = cblk->u.mStreaming.mFront;
683 
684         // effectively obtain then release whatever is in the buffer
685         const size_t overflowBit = mFrameCountP2 << 1;
686         const size_t mask = overflowBit - 1;
687         int32_t newFront = (front & ~mask) | (flush & mask);
688         ssize_t filled = audio_utils::safe_sub_overflow(rear, newFront);
689         if (filled >= (ssize_t)overflowBit) {
690             // front and rear offsets span the overflow bit of the p2 mask
691             // so rebasing newFront on the front offset is off by the overflow bit.
692             // adjust newFront to match rear offset.
693             ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
694             newFront += overflowBit;
695             filled -= overflowBit;
696         }
697         // Rather than shutting down on a corrupt flush, just treat it as a full flush
698         if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
699             ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
700                     "filled %zd=%#x",
701                     mFlush, flush, front, rear,
702                     (unsigned)mask, newFront, filled, (unsigned)filled);
703             newFront = rear;
704         }
705         mFlush = flush;
706         android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
707         // There is no danger from a false positive, so err on the side of caution
708         if (true /*front != newFront*/) {
709             int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
710             if (!(old & CBLK_FUTEX_WAKE)) {
711                 (void) syscall(__NR_futex, &cblk->mFutex,
712                         mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
713             }
714         }
715         mFlushed += (newFront - front) & mask;
716     }
717 }
718 
719 __attribute__((no_sanitize("integer")))
getRear() const720 int32_t AudioTrackServerProxy::getRear() const
721 {
722     const int32_t stop = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
723     const int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
724     const int32_t stopLast = mStopLast.load(std::memory_order_acquire);
725     if (stop != stopLast) {
726         const int32_t front = mCblk->u.mStreaming.mFront;
727         const size_t overflowBit = mFrameCountP2 << 1;
728         const size_t mask = overflowBit - 1;
729         int32_t newRear = (rear & ~mask) | (stop & mask);
730         ssize_t filled = audio_utils::safe_sub_overflow(newRear, front);
731         // overflowBit is unsigned, so cast to signed for comparison.
732         if (filled >= (ssize_t)overflowBit) {
733             // front and rear offsets span the overflow bit of the p2 mask
734             // so rebasing newRear on the rear offset is off by the overflow bit.
735             ALOGV("stop wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
736             newRear -= overflowBit;
737             filled -= overflowBit;
738         }
739         if (0 <= filled && (size_t) filled <= mFrameCount) {
740             // we're stopped, return the stop level as newRear
741             return newRear;
742         }
743 
744         // A corrupt stop. Log error and ignore.
745         ALOGE("mStopLast %#x -> stop %#x, front %#x, rear %#x, mask %#x, newRear %#x, "
746                 "filled %zd=%#x",
747                 stopLast, stop, front, rear,
748                 (unsigned)mask, newRear, filled, (unsigned)filled);
749         // Don't reset mStopLast as this is const.
750     }
751     return rear;
752 }
753 
start()754 void AudioTrackServerProxy::start()
755 {
756     mStopLast = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
757 }
758 
759 __attribute__((no_sanitize("integer")))
obtainBuffer(Buffer * buffer,bool ackFlush)760 status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
761 {
762     LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
763             "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
764     if (mIsShutdown) {
765         goto no_init;
766     }
767     {
768     audio_track_cblk_t* cblk = mCblk;
769     // compute number of frames available to write (AudioTrack) or read (AudioRecord),
770     // or use previous cached value from framesReady(), with added barrier if it omits.
771     int32_t front;
772     int32_t rear;
773     // See notes on barriers at ClientProxy::obtainBuffer()
774     if (mIsOut) {
775         flushBufferIfNeeded(); // might modify mFront
776         rear = getRear();
777         front = cblk->u.mStreaming.mFront;
778     } else {
779         front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
780         rear = cblk->u.mStreaming.mRear;
781     }
782     ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
783     // pipe should not already be overfull
784     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
785         ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
786                 filled, mFrameCount);
787         mIsShutdown = true;
788     }
789     if (mIsShutdown) {
790         goto no_init;
791     }
792     // don't allow filling pipe beyond the nominal size
793     size_t availToServer;
794     if (mIsOut) {
795         availToServer = filled;
796         mAvailToClient = mFrameCount - filled;
797     } else {
798         availToServer = mFrameCount - filled;
799         mAvailToClient = filled;
800     }
801     // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
802     size_t part1;
803     if (mIsOut) {
804         front &= mFrameCountP2 - 1;
805         part1 = mFrameCountP2 - front;
806     } else {
807         rear &= mFrameCountP2 - 1;
808         part1 = mFrameCountP2 - rear;
809     }
810     if (part1 > availToServer) {
811         part1 = availToServer;
812     }
813     size_t ask = buffer->mFrameCount;
814     if (part1 > ask) {
815         part1 = ask;
816     }
817     // is assignment redundant in some cases?
818     buffer->mFrameCount = part1;
819     buffer->mRaw = part1 > 0 ?
820             &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
821     buffer->mNonContig = availToServer - part1;
822     // After flush(), allow releaseBuffer() on a previously obtained buffer;
823     // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
824     if (!ackFlush) {
825         mUnreleased = part1;
826     }
827     return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
828     }
829 no_init:
830     buffer->mFrameCount = 0;
831     buffer->mRaw = NULL;
832     buffer->mNonContig = 0;
833     mUnreleased = 0;
834     return NO_INIT;
835 }
836 
837 __attribute__((no_sanitize("integer")))
releaseBuffer(Buffer * buffer)838 void ServerProxy::releaseBuffer(Buffer* buffer)
839 {
840     LOG_ALWAYS_FATAL_IF(buffer == NULL);
841     size_t stepCount = buffer->mFrameCount;
842     if (stepCount == 0 || mIsShutdown) {
843         // prevent accidental re-use of buffer
844         buffer->mFrameCount = 0;
845         buffer->mRaw = NULL;
846         buffer->mNonContig = 0;
847         return;
848     }
849     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
850             "%s: mUnreleased out of range, "
851             "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu)",
852             __func__, stepCount, mUnreleased, mFrameCount);
853     mUnreleased -= stepCount;
854     audio_track_cblk_t* cblk = mCblk;
855     if (mIsOut) {
856         int32_t front = cblk->u.mStreaming.mFront;
857         android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
858     } else {
859         int32_t rear = cblk->u.mStreaming.mRear;
860         android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
861     }
862 
863     cblk->mServer += stepCount;
864     mReleased += stepCount;
865 
866     size_t half = mFrameCount / 2;
867     if (half == 0) {
868         half = 1;
869     }
870     size_t minimum = (size_t) cblk->mMinimum;
871     if (minimum == 0) {
872         minimum = mIsOut ? half : 1;
873     } else if (minimum > half) {
874         minimum = half;
875     }
876     // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
877     if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
878         ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
879         int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
880         if (!(old & CBLK_FUTEX_WAKE)) {
881             (void) syscall(__NR_futex, &cblk->mFutex,
882                     mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
883         }
884     }
885 
886     buffer->mFrameCount = 0;
887     buffer->mRaw = NULL;
888     buffer->mNonContig = 0;
889 }
890 
891 // ---------------------------------------------------------------------------
892 
893 __attribute__((no_sanitize("integer")))
framesReady()894 size_t AudioTrackServerProxy::framesReady()
895 {
896     LOG_ALWAYS_FATAL_IF(!mIsOut);
897 
898     if (mIsShutdown) {
899         return 0;
900     }
901     audio_track_cblk_t* cblk = mCblk;
902 
903     int32_t flush = cblk->u.mStreaming.mFlush;
904     if (flush != mFlush) {
905         // FIXME should return an accurate value, but over-estimate is better than under-estimate
906         return mFrameCount;
907     }
908     const int32_t rear = getRear();
909     ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
910     // pipe should not already be overfull
911     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
912         ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
913                 filled, mFrameCount);
914         mIsShutdown = true;
915         return 0;
916     }
917     //  cache this value for later use by obtainBuffer(), with added barrier
918     //  and racy if called by normal mixer thread
919     // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
920     return filled;
921 }
922 
923 __attribute__((no_sanitize("integer")))
framesReadySafe() const924 size_t AudioTrackServerProxy::framesReadySafe() const
925 {
926     if (mIsShutdown) {
927         return 0;
928     }
929     const audio_track_cblk_t* cblk = mCblk;
930     const int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
931     if (flush != mFlush) {
932         return mFrameCount;
933     }
934     const int32_t rear = getRear();
935     const ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
936     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
937         return 0; // error condition, silently return 0.
938     }
939     return filled;
940 }
941 
setStreamEndDone()942 bool  AudioTrackServerProxy::setStreamEndDone() {
943     audio_track_cblk_t* cblk = mCblk;
944     bool old =
945             (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
946     if (!old) {
947         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
948                 1);
949     }
950     return old;
951 }
952 
953 __attribute__((no_sanitize("integer")))
tallyUnderrunFrames(uint32_t frameCount)954 void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
955 {
956     audio_track_cblk_t* cblk = mCblk;
957     if (frameCount > 0) {
958         cblk->u.mStreaming.mUnderrunFrames += frameCount;
959 
960         if (!mUnderrunning) { // start of underrun?
961             mUnderrunCount++;
962             cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
963             mUnderrunning = true;
964             ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
965                 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
966         }
967 
968         // FIXME also wake futex so that underrun is noticed more quickly
969         (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
970     } else {
971         ALOGV_IF(mUnderrunning,
972             "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
973             frameCount, cblk->u.mStreaming.mUnderrunFrames);
974         mUnderrunning = false; // so we can detect the next edge
975     }
976 }
977 
getPlaybackRate()978 AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
979 {   // do not call from multiple threads without holding lock
980     mPlaybackRateObserver.poll(mPlaybackRate);
981     return mPlaybackRate;
982 }
983 
984 // ---------------------------------------------------------------------------
985 
StaticAudioTrackServerProxy(audio_track_cblk_t * cblk,void * buffers,size_t frameCount,size_t frameSize)986 StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
987         size_t frameCount, size_t frameSize)
988     : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
989       mObserver(&cblk->u.mStatic.mSingleStateQueue),
990       mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
991       mFramesReadySafe(frameCount), mFramesReady(frameCount),
992       mFramesReadyIsCalledByMultipleThreads(false)
993 {
994     memset(&mState, 0, sizeof(mState));
995 }
996 
framesReadyIsCalledByMultipleThreads()997 void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
998 {
999     mFramesReadyIsCalledByMultipleThreads = true;
1000 }
1001 
framesReady()1002 size_t StaticAudioTrackServerProxy::framesReady()
1003 {
1004     // Can't call pollPosition() from multiple threads.
1005     if (!mFramesReadyIsCalledByMultipleThreads) {
1006         (void) pollPosition();
1007     }
1008     return mFramesReadySafe;
1009 }
1010 
framesReadySafe() const1011 size_t StaticAudioTrackServerProxy::framesReadySafe() const
1012 {
1013     return mFramesReadySafe;
1014 }
1015 
updateStateWithLoop(StaticAudioTrackState * localState,const StaticAudioTrackState & update) const1016 status_t StaticAudioTrackServerProxy::updateStateWithLoop(
1017         StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1018 {
1019     if (localState->mLoopSequence != update.mLoopSequence) {
1020         bool valid = false;
1021         const size_t loopStart = update.mLoopStart;
1022         const size_t loopEnd = update.mLoopEnd;
1023         size_t position = localState->mPosition;
1024         if (update.mLoopCount == 0) {
1025             valid = true;
1026         } else if (update.mLoopCount >= -1) {
1027             if (loopStart < loopEnd && loopEnd <= mFrameCount &&
1028                     loopEnd - loopStart >= MIN_LOOP) {
1029                 // If the current position is greater than the end of the loop
1030                 // we "wrap" to the loop start. This might cause an audible pop.
1031                 if (position >= loopEnd) {
1032                     position = loopStart;
1033                 }
1034                 valid = true;
1035             }
1036         }
1037         if (!valid || position > mFrameCount) {
1038             return NO_INIT;
1039         }
1040         localState->mPosition = position;
1041         localState->mLoopCount = update.mLoopCount;
1042         localState->mLoopEnd = loopEnd;
1043         localState->mLoopStart = loopStart;
1044         localState->mLoopSequence = update.mLoopSequence;
1045     }
1046     return OK;
1047 }
1048 
updateStateWithPosition(StaticAudioTrackState * localState,const StaticAudioTrackState & update) const1049 status_t StaticAudioTrackServerProxy::updateStateWithPosition(
1050         StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1051 {
1052     if (localState->mPositionSequence != update.mPositionSequence) {
1053         if (update.mPosition > mFrameCount) {
1054             return NO_INIT;
1055         } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
1056             localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
1057         }
1058         localState->mPosition = update.mPosition;
1059         localState->mPositionSequence = update.mPositionSequence;
1060     }
1061     return OK;
1062 }
1063 
pollPosition()1064 ssize_t StaticAudioTrackServerProxy::pollPosition()
1065 {
1066     StaticAudioTrackState state;
1067     if (mObserver.poll(state)) {
1068         StaticAudioTrackState trystate = mState;
1069         bool result;
1070         const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
1071 
1072         if (diffSeq < 0) {
1073             result = updateStateWithLoop(&trystate, state) == OK &&
1074                     updateStateWithPosition(&trystate, state) == OK;
1075         } else {
1076             result = updateStateWithPosition(&trystate, state) == OK &&
1077                     updateStateWithLoop(&trystate, state) == OK;
1078         }
1079         if (!result) {
1080             mObserver.done();
1081             // caution: no update occurs so server state will be inconsistent with client state.
1082             ALOGE("%s client pushed an invalid state, shutting down", __func__);
1083             mIsShutdown = true;
1084             return (ssize_t) NO_INIT;
1085         }
1086         mState = trystate;
1087         if (mState.mLoopCount == -1) {
1088             mFramesReady = INT64_MAX;
1089         } else if (mState.mLoopCount == 0) {
1090             mFramesReady = mFrameCount - mState.mPosition;
1091         } else if (mState.mLoopCount > 0) {
1092             // TODO: Later consider fixing overflow, but does not seem needed now
1093             // as will not overflow if loopStart and loopEnd are Java "ints".
1094             mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
1095                     + mFrameCount - mState.mPosition;
1096         }
1097         mFramesReadySafe = clampToSize(mFramesReady);
1098         // This may overflow, but client is not supposed to rely on it
1099         StaticAudioTrackPosLoop posLoop;
1100 
1101         posLoop.mLoopCount = (int32_t) mState.mLoopCount;
1102         posLoop.mBufferPosition = (uint32_t) mState.mPosition;
1103         mPosLoopMutator.push(posLoop);
1104         mObserver.done(); // safe to read mStatic variables.
1105     }
1106     return (ssize_t) mState.mPosition;
1107 }
1108 
1109 __attribute__((no_sanitize("integer")))
obtainBuffer(Buffer * buffer,bool ackFlush)1110 status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
1111 {
1112     if (mIsShutdown) {
1113         buffer->mFrameCount = 0;
1114         buffer->mRaw = NULL;
1115         buffer->mNonContig = 0;
1116         mUnreleased = 0;
1117         return NO_INIT;
1118     }
1119     ssize_t positionOrStatus = pollPosition();
1120     if (positionOrStatus < 0) {
1121         buffer->mFrameCount = 0;
1122         buffer->mRaw = NULL;
1123         buffer->mNonContig = 0;
1124         mUnreleased = 0;
1125         return (status_t) positionOrStatus;
1126     }
1127     size_t position = (size_t) positionOrStatus;
1128     size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
1129     size_t avail;
1130     if (position < end) {
1131         avail = end - position;
1132         size_t wanted = buffer->mFrameCount;
1133         if (avail < wanted) {
1134             buffer->mFrameCount = avail;
1135         } else {
1136             avail = wanted;
1137         }
1138         buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1139     } else {
1140         avail = 0;
1141         buffer->mFrameCount = 0;
1142         buffer->mRaw = NULL;
1143     }
1144     // As mFramesReady is the total remaining frames in the static audio track,
1145     // it is always larger or equal to avail.
1146     LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail,
1147             "%s: mFramesReady out of range, mFramesReady:%lld < avail:%zu",
1148             __func__, (long long)mFramesReady, avail);
1149     buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
1150     if (!ackFlush) {
1151         mUnreleased = avail;
1152     }
1153     return NO_ERROR;
1154 }
1155 
1156 __attribute__((no_sanitize("integer")))
releaseBuffer(Buffer * buffer)1157 void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1158 {
1159     size_t stepCount = buffer->mFrameCount;
1160     LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady),
1161             "%s: stepCount out of range, "
1162             "!(stepCount:%zu <= mFramesReady:%lld)",
1163             __func__, stepCount, (long long)mFramesReady);
1164     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased),
1165             "%s: stepCount out of range, "
1166             "!(stepCount:%zu <= mUnreleased:%zu)",
1167             __func__, stepCount, mUnreleased);
1168     if (stepCount == 0) {
1169         // prevent accidental re-use of buffer
1170         buffer->mRaw = NULL;
1171         buffer->mNonContig = 0;
1172         return;
1173     }
1174     mUnreleased -= stepCount;
1175     audio_track_cblk_t* cblk = mCblk;
1176     size_t position = mState.mPosition;
1177     size_t newPosition = position + stepCount;
1178     int32_t setFlags = 0;
1179     if (!(position <= newPosition && newPosition <= mFrameCount)) {
1180         ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1181                 mFrameCount);
1182         newPosition = mFrameCount;
1183     } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
1184         newPosition = mState.mLoopStart;
1185         if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
1186             setFlags = CBLK_LOOP_CYCLE;
1187         } else {
1188             setFlags = CBLK_LOOP_FINAL;
1189         }
1190     }
1191     if (newPosition == mFrameCount) {
1192         setFlags |= CBLK_BUFFER_END;
1193     }
1194     mState.mPosition = newPosition;
1195     if (mFramesReady != INT64_MAX) {
1196         mFramesReady -= stepCount;
1197     }
1198     mFramesReadySafe = clampToSize(mFramesReady);
1199 
1200     cblk->mServer += stepCount;
1201     mReleased += stepCount;
1202 
1203     // This may overflow, but client is not supposed to rely on it
1204     StaticAudioTrackPosLoop posLoop;
1205     posLoop.mBufferPosition = mState.mPosition;
1206     posLoop.mLoopCount = mState.mLoopCount;
1207     mPosLoopMutator.push(posLoop);
1208     if (setFlags != 0) {
1209         (void) android_atomic_or(setFlags, &cblk->mFlags);
1210         // this would be a good place to wake a futex
1211     }
1212 
1213     buffer->mFrameCount = 0;
1214     buffer->mRaw = NULL;
1215     buffer->mNonContig = 0;
1216 }
1217 
tallyUnderrunFrames(uint32_t frameCount)1218 void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
1219 {
1220     // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1221     // we don't have a location to count underrun frames.  The underrun frame counter
1222     // only exists in AudioTrackSharedStreaming.  Fortunately, underruns are not
1223     // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1224 
1225     // FIXME also wake futex so that underrun is noticed more quickly
1226     if (frameCount > 0) {
1227         (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1228     }
1229 }
1230 
getRear() const1231 int32_t StaticAudioTrackServerProxy::getRear() const
1232 {
1233     LOG_ALWAYS_FATAL("getRear() not permitted for static tracks");
1234     return 0;
1235 }
1236 
1237 __attribute__((no_sanitize("integer")))
framesReadySafe() const1238 size_t AudioRecordServerProxy::framesReadySafe() const
1239 {
1240     if (mIsShutdown) {
1241         return 0;
1242     }
1243     const int32_t front = android_atomic_acquire_load(&mCblk->u.mStreaming.mFront);
1244     const int32_t rear = mCblk->u.mStreaming.mRear;
1245     const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
1246     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
1247         return 0; // error condition, silently return 0.
1248     }
1249     return filled;
1250 }
1251 
1252 // ---------------------------------------------------------------------------
1253 
1254 }   // namespace android
1255