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