• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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         int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
314         if (!(old & CBLK_FUTEX_WAKE)) {
315             if (measure && !beforeIsValid) {
316                 clock_gettime(CLOCK_MONOTONIC, &before);
317                 beforeIsValid = true;
318             }
319             errno = 0;
320             (void) syscall(__NR_futex, &cblk->mFutex,
321                     mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
322             status_t error = errno; // clock_gettime can affect errno
323             // update total elapsed time spent waiting
324             if (measure) {
325                 struct timespec after;
326                 clock_gettime(CLOCK_MONOTONIC, &after);
327                 total.tv_sec += after.tv_sec - before.tv_sec;
328                 // Use auto instead of long to avoid the google-runtime-int warning.
329                 auto deltaNs = after.tv_nsec - before.tv_nsec;
330                 if (deltaNs < 0) {
331                     deltaNs += 1000000000;
332                     total.tv_sec--;
333                 }
334                 if ((total.tv_nsec += deltaNs) >= 1000000000) {
335                     total.tv_nsec -= 1000000000;
336                     total.tv_sec++;
337                 }
338                 before = after;
339                 beforeIsValid = true;
340             }
341             switch (error) {
342             case 0:            // normal wakeup by server, or by binderDied()
343             case EWOULDBLOCK:  // benign race condition with server
344             case EINTR:        // wait was interrupted by signal or other spurious wakeup
345             case ETIMEDOUT:    // time-out expired
346                 // FIXME these error/non-0 status are being dropped
347                 break;
348             default:
349                 status = error;
350                 ALOGE("%s unexpected error %s", __func__, strerror(status));
351                 goto end;
352             }
353         }
354     }
355 
356 end:
357     if (status != NO_ERROR) {
358         buffer->mFrameCount = 0;
359         buffer->mRaw = NULL;
360         buffer->mNonContig = 0;
361         mUnreleased = 0;
362     }
363     if (elapsed != NULL) {
364         *elapsed = total;
365     }
366     if (requested == NULL) {
367         requested = &kNonBlocking;
368     }
369     if (measure) {
370         ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
371               requested->tv_sec, requested->tv_nsec / 1000000,
372               total.tv_sec, total.tv_nsec / 1000000);
373     }
374     return status;
375 }
376 
377 __attribute__((no_sanitize("integer")))
releaseBuffer(Buffer * buffer)378 void ClientProxy::releaseBuffer(Buffer* buffer)
379 {
380     LOG_ALWAYS_FATAL_IF(buffer == NULL);
381     size_t stepCount = buffer->mFrameCount;
382     if (stepCount == 0 || mIsShutdown) {
383         // prevent accidental re-use of buffer
384         buffer->mFrameCount = 0;
385         buffer->mRaw = NULL;
386         buffer->mNonContig = 0;
387         return;
388     }
389     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
390             "%s: mUnreleased out of range, "
391             "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu), BufferSizeInFrames:%u",
392             __func__, stepCount, mUnreleased, mFrameCount, getBufferSizeInFrames());
393     mUnreleased -= stepCount;
394     audio_track_cblk_t* cblk = mCblk;
395     // Both of these barriers are required
396     if (mIsOut) {
397         int32_t rear = cblk->u.mStreaming.mRear;
398         android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
399     } else {
400         int32_t front = cblk->u.mStreaming.mFront;
401         android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
402     }
403 }
404 
binderDied()405 void ClientProxy::binderDied()
406 {
407     audio_track_cblk_t* cblk = mCblk;
408     if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
409         android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
410         // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
411         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
412                 INT_MAX);
413     }
414 }
415 
interrupt()416 void ClientProxy::interrupt()
417 {
418     audio_track_cblk_t* cblk = mCblk;
419     if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
420         android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
421         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
422                 INT_MAX);
423     }
424 }
425 
426 __attribute__((no_sanitize("integer")))
getMisalignment()427 size_t ClientProxy::getMisalignment()
428 {
429     audio_track_cblk_t* cblk = mCblk;
430     return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
431             (mFrameCountP2 - 1);
432 }
433 
434 // ---------------------------------------------------------------------------
435 
flush()436 void AudioTrackClientProxy::flush()
437 {
438     sendStreamingFlushStop(true /* flush */);
439 }
440 
stop()441 void AudioTrackClientProxy::stop()
442 {
443     sendStreamingFlushStop(false /* flush */);
444 }
445 
446 // Sets the client-written mFlush and mStop positions, which control server behavior.
447 //
448 // @param flush indicates whether the operation is a flush or stop.
449 // A client stop sets mStop to the current write position;
450 // the server will not read past this point until start() or subsequent flush().
451 // A client flush sets both mStop and mFlush to the current write position.
452 // This advances the server read limit (if previously set) and on the next
453 // server read advances the server read position to this limit.
454 //
sendStreamingFlushStop(bool flush)455 void AudioTrackClientProxy::sendStreamingFlushStop(bool flush)
456 {
457     // TODO: Replace this by 64 bit counters - avoids wrap complication.
458     // This works for mFrameCountP2 <= 2^30
459     // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
460     // Should newFlush = cblk->u.mStreaming.mRear?  Only problem is
461     // if you want to flush twice to the same rear location after a 32 bit wrap.
462 
463     const size_t increment = mFrameCountP2 << 1;
464     const size_t mask = increment - 1;
465     // No need for client atomic synchronization on mRear, mStop, mFlush
466     // as AudioTrack client only read/writes to them under client lock. Server only reads.
467     const int32_t rearMasked = mCblk->u.mStreaming.mRear & mask;
468 
469     // update stop before flush so that the server front
470     // never advances beyond a (potential) previous stop's rear limit.
471     int32_t stopBits; // the following add can overflow
472     __builtin_add_overflow(mCblk->u.mStreaming.mStop & ~mask, increment, &stopBits);
473     android_atomic_release_store(rearMasked | stopBits, &mCblk->u.mStreaming.mStop);
474 
475     if (flush) {
476         int32_t flushBits; // the following add can overflow
477         __builtin_add_overflow(mCblk->u.mStreaming.mFlush & ~mask, increment, &flushBits);
478         android_atomic_release_store(rearMasked | flushBits, &mCblk->u.mStreaming.mFlush);
479     }
480 }
481 
clearStreamEndDone()482 bool AudioTrackClientProxy::clearStreamEndDone() {
483     return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
484 }
485 
getStreamEndDone() const486 bool AudioTrackClientProxy::getStreamEndDone() const {
487     return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
488 }
489 
waitStreamEndDone(const struct timespec * requested)490 status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
491 {
492     struct timespec total;          // total elapsed time spent waiting
493     struct timespec before;
494     bool beforeIsValid = false;
495     total.tv_sec = 0;
496     total.tv_nsec = 0;
497     audio_track_cblk_t* cblk = mCblk;
498     status_t status;
499     enum {
500         TIMEOUT_ZERO,       // requested == NULL || *requested == 0
501         TIMEOUT_INFINITE,   // *requested == infinity
502         TIMEOUT_FINITE,     // 0 < *requested < infinity
503         TIMEOUT_CONTINUE,   // additional chances after TIMEOUT_FINITE
504     } timeout;
505     if (requested == NULL) {
506         timeout = TIMEOUT_ZERO;
507     } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
508         timeout = TIMEOUT_ZERO;
509     } else if (requested->tv_sec == INT_MAX) {
510         timeout = TIMEOUT_INFINITE;
511     } else {
512         timeout = TIMEOUT_FINITE;
513     }
514     for (;;) {
515         int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
516         // check for track invalidation by server, or server death detection
517         if (flags & CBLK_INVALID) {
518             ALOGV("Track invalidated");
519             status = DEAD_OBJECT;
520             goto end;
521         }
522         // a track is not supposed to underrun at this stage but consider it done
523         if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
524             ALOGV("stream end received");
525             status = NO_ERROR;
526             goto end;
527         }
528         // check for obtainBuffer interrupted by client
529         if (flags & CBLK_INTERRUPT) {
530             ALOGV("waitStreamEndDone() interrupted by client");
531             status = -EINTR;
532             goto end;
533         }
534         struct timespec remaining;
535         const struct timespec *ts;
536         switch (timeout) {
537         case TIMEOUT_ZERO:
538             status = WOULD_BLOCK;
539             goto end;
540         case TIMEOUT_INFINITE:
541             ts = NULL;
542             break;
543         case TIMEOUT_FINITE:
544             timeout = TIMEOUT_CONTINUE;
545             if (MAX_SEC == 0) {
546                 ts = requested;
547                 break;
548             }
549             FALLTHROUGH_INTENDED;
550         case TIMEOUT_CONTINUE:
551             // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
552             if (requested->tv_sec < total.tv_sec ||
553                     (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
554                 status = TIMED_OUT;
555                 goto end;
556             }
557             remaining.tv_sec = requested->tv_sec - total.tv_sec;
558             if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
559                 remaining.tv_nsec += 1000000000;
560                 remaining.tv_sec++;
561             }
562             if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
563                 remaining.tv_sec = MAX_SEC;
564                 remaining.tv_nsec = 0;
565             }
566             ts = &remaining;
567             break;
568         default:
569             LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
570             ts = NULL;
571             break;
572         }
573         int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
574         if (!(old & CBLK_FUTEX_WAKE)) {
575             if (!beforeIsValid) {
576                 clock_gettime(CLOCK_MONOTONIC, &before);
577                 beforeIsValid = true;
578             }
579             errno = 0;
580             (void) syscall(__NR_futex, &cblk->mFutex,
581                     mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
582             status_t error = errno; // clock_gettime can affect errno
583             {
584                 struct timespec after;
585                 clock_gettime(CLOCK_MONOTONIC, &after);
586                 total.tv_sec += after.tv_sec - before.tv_sec;
587                 // Use auto instead of long to avoid the google-runtime-int warning.
588                 auto deltaNs = after.tv_nsec - before.tv_nsec;
589                 if (deltaNs < 0) {
590                     deltaNs += 1000000000;
591                     total.tv_sec--;
592                 }
593                 if ((total.tv_nsec += deltaNs) >= 1000000000) {
594                     total.tv_nsec -= 1000000000;
595                     total.tv_sec++;
596                 }
597                 before = after;
598             }
599             switch (error) {
600             case 0:            // normal wakeup by server, or by binderDied()
601             case EWOULDBLOCK:  // benign race condition with server
602             case EINTR:        // wait was interrupted by signal or other spurious wakeup
603             case ETIMEDOUT:    // time-out expired
604                 break;
605             default:
606                 status = error;
607                 ALOGE("%s unexpected error %s", __func__, strerror(status));
608                 goto end;
609             }
610         }
611     }
612 
613 end:
614     if (requested == NULL) {
615         requested = &kNonBlocking;
616     }
617     return status;
618 }
619 
620 // ---------------------------------------------------------------------------
621 
StaticAudioTrackClientProxy(audio_track_cblk_t * cblk,void * buffers,size_t frameCount,size_t frameSize)622 StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
623         size_t frameCount, size_t frameSize)
624     : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
625       mMutator(&cblk->u.mStatic.mSingleStateQueue),
626       mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
627 {
628     memset(&mState, 0, sizeof(mState));
629     memset(&mPosLoop, 0, sizeof(mPosLoop));
630 }
631 
flush()632 void StaticAudioTrackClientProxy::flush()
633 {
634     LOG_ALWAYS_FATAL("static flush");
635 }
636 
stop()637 void StaticAudioTrackClientProxy::stop()
638 {
639     ; // no special handling required for static tracks.
640 }
641 
setLoop(size_t loopStart,size_t loopEnd,int loopCount)642 void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
643 {
644     // This can only happen on a 64-bit client
645     if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
646         // FIXME Should return an error status
647         return;
648     }
649     mState.mLoopStart = (uint32_t) loopStart;
650     mState.mLoopEnd = (uint32_t) loopEnd;
651     mState.mLoopCount = loopCount;
652     mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
653     // set patch-up variables until the mState is acknowledged by the ServerProxy.
654     // observed buffer position and loop count will freeze until then to give the
655     // illusion of a synchronous change.
656     getBufferPositionAndLoopCount(NULL, NULL);
657     // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
658     if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
659         mPosLoop.mBufferPosition = mState.mLoopStart;
660     }
661     mPosLoop.mLoopCount = mState.mLoopCount;
662     (void) mMutator.push(mState);
663 }
664 
setBufferPosition(size_t position)665 void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
666 {
667     // This can only happen on a 64-bit client
668     if (position > UINT32_MAX) {
669         // FIXME Should return an error status
670         return;
671     }
672     mState.mPosition = (uint32_t) position;
673     mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
674     // set patch-up variables until the mState is acknowledged by the ServerProxy.
675     // observed buffer position and loop count will freeze until then to give the
676     // illusion of a synchronous change.
677     if (mState.mLoopCount > 0) {  // only check if loop count is changing
678         getBufferPositionAndLoopCount(NULL, NULL); // get last position
679     }
680     mPosLoop.mBufferPosition = position;
681     if (position >= mState.mLoopEnd) {
682         // no ongoing loop is possible if position is greater than loopEnd.
683         mPosLoop.mLoopCount = 0;
684     }
685     (void) mMutator.push(mState);
686 }
687 
setBufferPositionAndLoop(size_t position,size_t loopStart,size_t loopEnd,int loopCount)688 void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
689         size_t loopEnd, int loopCount)
690 {
691     setLoop(loopStart, loopEnd, loopCount);
692     setBufferPosition(position);
693 }
694 
getBufferPosition()695 size_t StaticAudioTrackClientProxy::getBufferPosition()
696 {
697     getBufferPositionAndLoopCount(NULL, NULL);
698     return mPosLoop.mBufferPosition;
699 }
700 
getBufferPositionAndLoopCount(size_t * position,int * loopCount)701 void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
702         size_t *position, int *loopCount)
703 {
704     if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
705          if (mPosLoopObserver.poll(mPosLoop)) {
706              ; // a valid mPosLoop should be available if ackDone is true.
707          }
708     }
709     if (position != NULL) {
710         *position = mPosLoop.mBufferPosition;
711     }
712     if (loopCount != NULL) {
713         *loopCount = mPosLoop.mLoopCount;
714     }
715 }
716 
717 // ---------------------------------------------------------------------------
718 
ServerProxy(audio_track_cblk_t * cblk,void * buffers,size_t frameCount,size_t frameSize,bool isOut,bool clientInServer)719 ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
720         size_t frameSize, bool isOut, bool clientInServer)
721     : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
722       mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
723     , mTimestampMutator(&cblk->mExtendedTimestampQueue)
724 {
725     cblk->mBufferSizeInFrames = frameCount;
726     cblk->mStartThresholdInFrames = frameCount;
727 }
728 
729 __attribute__((no_sanitize("integer")))
flushBufferIfNeeded()730 void ServerProxy::flushBufferIfNeeded()
731 {
732     audio_track_cblk_t* cblk = mCblk;
733     // The acquire_load is not really required. But since the write is a release_store in the
734     // client, using acquire_load here makes it easier for people to maintain the code,
735     // and the logic for communicating ipc variables seems somewhat standard,
736     // and there really isn't much penalty for 4 or 8 byte atomics.
737     int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
738     if (flush != mFlush) {
739         ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
740                 flush, mFlush);
741         // shouldn't matter, but for range safety use mRear instead of getRear().
742         int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
743         int32_t front = cblk->u.mStreaming.mFront;
744 
745         // effectively obtain then release whatever is in the buffer
746         const size_t overflowBit = mFrameCountP2 << 1;
747         const size_t mask = overflowBit - 1;
748         int32_t newFront = (front & ~mask) | (flush & mask);
749         ssize_t filled = audio_utils::safe_sub_overflow(rear, newFront);
750         if (filled >= (ssize_t)overflowBit) {
751             // front and rear offsets span the overflow bit of the p2 mask
752             // so rebasing newFront on the front offset is off by the overflow bit.
753             // adjust newFront to match rear offset.
754             ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
755             newFront += overflowBit;
756             filled -= overflowBit;
757         }
758         // Rather than shutting down on a corrupt flush, just treat it as a full flush
759         if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
760             ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
761                     "filled %zd=%#x",
762                     mFlush, flush, front, rear,
763                     (unsigned)mask, newFront, filled, (unsigned)filled);
764             newFront = rear;
765         }
766         mFlush = flush;
767         android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
768         // There is no danger from a false positive, so err on the side of caution
769         if (true /*front != newFront*/) {
770             int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
771             if (!(old & CBLK_FUTEX_WAKE)) {
772                 (void) syscall(__NR_futex, &cblk->mFutex,
773                         mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, INT_MAX);
774             }
775         }
776         mFlushed += (newFront - front) & mask;
777     }
778 }
779 
780 __attribute__((no_sanitize("integer")))
getRear() const781 int32_t AudioTrackServerProxy::getRear() const
782 {
783     const int32_t stop = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
784     const int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
785     const int32_t stopLast = mStopLast.load(std::memory_order_acquire);
786     if (stop != stopLast) {
787         const int32_t front = mCblk->u.mStreaming.mFront;
788         const size_t overflowBit = mFrameCountP2 << 1;
789         const size_t mask = overflowBit - 1;
790         int32_t newRear = (rear & ~mask) | (stop & mask);
791         ssize_t filled = audio_utils::safe_sub_overflow(newRear, front);
792         // overflowBit is unsigned, so cast to signed for comparison.
793         if (filled >= (ssize_t)overflowBit) {
794             // front and rear offsets span the overflow bit of the p2 mask
795             // so rebasing newRear on the rear offset is off by the overflow bit.
796             ALOGV("stop wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
797             newRear -= overflowBit;
798             filled -= overflowBit;
799         }
800         if (0 <= filled && (size_t) filled <= mFrameCount) {
801             // we're stopped, return the stop level as newRear
802             return newRear;
803         }
804 
805         // A corrupt stop. Log error and ignore.
806         ALOGE("mStopLast %#x -> stop %#x, front %#x, rear %#x, mask %#x, newRear %#x, "
807                 "filled %zd=%#x",
808                 stopLast, stop, front, rear,
809                 (unsigned)mask, newRear, filled, (unsigned)filled);
810         // Don't reset mStopLast as this is const.
811     }
812     return rear;
813 }
814 
start()815 void AudioTrackServerProxy::start()
816 {
817     mStopLast = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
818 }
819 
820 __attribute__((no_sanitize("integer")))
obtainBuffer(Buffer * buffer,bool ackFlush)821 status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
822 {
823     LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
824             "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
825     if (mIsShutdown) {
826         goto no_init;
827     }
828     {
829     audio_track_cblk_t* cblk = mCblk;
830     // compute number of frames available to write (AudioTrack) or read (AudioRecord),
831     // or use previous cached value from framesReady(), with added barrier if it omits.
832     int32_t front;
833     int32_t rear;
834     // See notes on barriers at ClientProxy::obtainBuffer()
835     if (mIsOut) {
836         flushBufferIfNeeded(); // might modify mFront
837         rear = getRear();
838         front = cblk->u.mStreaming.mFront;
839     } else {
840         front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
841         rear = cblk->u.mStreaming.mRear;
842     }
843     ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
844     // pipe should not already be overfull
845     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
846         ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
847                 filled, mFrameCount);
848         mIsShutdown = true;
849     }
850     if (mIsShutdown) {
851         goto no_init;
852     }
853     // don't allow filling pipe beyond the nominal size
854     size_t availToServer;
855     if (mIsOut) {
856         availToServer = filled;
857         mAvailToClient = mFrameCount - filled;
858     } else {
859         availToServer = mFrameCount - filled;
860         mAvailToClient = filled;
861     }
862     // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
863     size_t part1;
864     if (mIsOut) {
865         front &= mFrameCountP2 - 1;
866         part1 = mFrameCountP2 - front;
867     } else {
868         rear &= mFrameCountP2 - 1;
869         part1 = mFrameCountP2 - rear;
870     }
871     if (part1 > availToServer) {
872         part1 = availToServer;
873     }
874     size_t ask = buffer->mFrameCount;
875     if (part1 > ask) {
876         part1 = ask;
877     }
878     // is assignment redundant in some cases?
879     buffer->mFrameCount = part1;
880     buffer->mRaw = part1 > 0 ?
881             &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
882     buffer->mNonContig = availToServer - part1;
883     // After flush(), allow releaseBuffer() on a previously obtained buffer;
884     // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
885     if (!ackFlush) {
886         mUnreleased = part1;
887     }
888     return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
889     }
890 no_init:
891     buffer->mFrameCount = 0;
892     buffer->mRaw = NULL;
893     buffer->mNonContig = 0;
894     mUnreleased = 0;
895     return NO_INIT;
896 }
897 
898 __attribute__((no_sanitize("integer")))
releaseBuffer(Buffer * buffer)899 void ServerProxy::releaseBuffer(Buffer* buffer)
900 {
901     LOG_ALWAYS_FATAL_IF(buffer == NULL);
902     size_t stepCount = buffer->mFrameCount;
903     if (stepCount == 0 || mIsShutdown) {
904         // prevent accidental re-use of buffer
905         buffer->mFrameCount = 0;
906         buffer->mRaw = NULL;
907         buffer->mNonContig = 0;
908         return;
909     }
910     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
911             "%s: mUnreleased out of range, "
912             "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu)",
913             __func__, stepCount, mUnreleased, mFrameCount);
914     mUnreleased -= stepCount;
915     audio_track_cblk_t* cblk = mCblk;
916     if (mIsOut) {
917         int32_t front = cblk->u.mStreaming.mFront;
918         android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
919     } else {
920         int32_t rear = cblk->u.mStreaming.mRear;
921         android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
922     }
923 
924     cblk->mServer += stepCount;
925     mReleased += stepCount;
926 
927     size_t half = mFrameCount / 2;
928     if (half == 0) {
929         half = 1;
930     }
931     size_t minimum = (size_t) cblk->mMinimum;
932     if (minimum == 0) {
933         minimum = mIsOut ? half : 1;
934     } else if (minimum > half) {
935         minimum = half;
936     }
937     // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
938     if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
939         ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
940         int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
941         if (!(old & CBLK_FUTEX_WAKE)) {
942             (void) syscall(__NR_futex, &cblk->mFutex,
943                     mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, INT_MAX);
944         }
945     }
946 
947     buffer->mFrameCount = 0;
948     buffer->mRaw = NULL;
949     buffer->mNonContig = 0;
950 }
951 
952 // ---------------------------------------------------------------------------
953 
954 __attribute__((no_sanitize("integer")))
framesReady()955 size_t AudioTrackServerProxy::framesReady()
956 {
957     LOG_ALWAYS_FATAL_IF(!mIsOut);
958 
959     if (mIsShutdown) {
960         return 0;
961     }
962     audio_track_cblk_t* cblk = mCblk;
963 
964     flushBufferIfNeeded();
965 
966     const int32_t rear = getRear();
967     ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
968     // pipe should not already be overfull
969     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
970         ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
971                 filled, mFrameCount);
972         mIsShutdown = true;
973         return 0;
974     }
975     //  cache this value for later use by obtainBuffer(), with added barrier
976     //  and racy if called by normal mixer thread
977     // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
978     return filled;
979 }
980 
981 __attribute__((no_sanitize("integer")))
framesReadySafe() const982 size_t AudioTrackServerProxy::framesReadySafe() const
983 {
984     if (mIsShutdown) {
985         return 0;
986     }
987     const audio_track_cblk_t* cblk = mCblk;
988     const int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
989     if (flush != mFlush) {
990         return mFrameCount;
991     }
992     const int32_t rear = getRear();
993     const ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
994     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
995         return 0; // error condition, silently return 0.
996     }
997     return filled;
998 }
999 
setStreamEndDone()1000 bool  AudioTrackServerProxy::setStreamEndDone() {
1001     audio_track_cblk_t* cblk = mCblk;
1002     bool old =
1003             (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
1004     if (!old) {
1005         (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
1006                 1);
1007     }
1008     return old;
1009 }
1010 
1011 __attribute__((no_sanitize("integer")))
tallyUnderrunFrames(uint32_t frameCount)1012 void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
1013 {
1014     audio_track_cblk_t* cblk = mCblk;
1015     if (frameCount > 0) {
1016         cblk->u.mStreaming.mUnderrunFrames += frameCount;
1017 
1018         if (!mUnderrunning) { // start of underrun?
1019             mUnderrunCount++;
1020             cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
1021             mUnderrunning = true;
1022             ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
1023                 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
1024         }
1025 
1026         // FIXME also wake futex so that underrun is noticed more quickly
1027         (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
1028     } else {
1029         ALOGV_IF(mUnderrunning,
1030             "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
1031             frameCount, cblk->u.mStreaming.mUnderrunFrames);
1032         mUnderrunning = false; // so we can detect the next edge
1033     }
1034 }
1035 
getPlaybackRate()1036 AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
1037 {   // do not call from multiple threads without holding lock
1038     mPlaybackRateObserver.poll(mPlaybackRate);
1039     return mPlaybackRate;
1040 }
1041 
1042 // ---------------------------------------------------------------------------
1043 
StaticAudioTrackServerProxy(audio_track_cblk_t * cblk,void * buffers,size_t frameCount,size_t frameSize,uint32_t sampleRate)1044 StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
1045         size_t frameCount, size_t frameSize, uint32_t sampleRate)
1046     : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize, false /*clientInServer*/,
1047                             sampleRate),
1048       mObserver(&cblk->u.mStatic.mSingleStateQueue),
1049       mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
1050       mFramesReadySafe(frameCount), mFramesReady(frameCount),
1051       mFramesReadyIsCalledByMultipleThreads(false)
1052 {
1053     memset(&mState, 0, sizeof(mState));
1054 }
1055 
framesReadyIsCalledByMultipleThreads()1056 void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
1057 {
1058     mFramesReadyIsCalledByMultipleThreads = true;
1059 }
1060 
framesReady()1061 size_t StaticAudioTrackServerProxy::framesReady()
1062 {
1063     // Can't call pollPosition() from multiple threads.
1064     if (!mFramesReadyIsCalledByMultipleThreads) {
1065         (void) pollPosition();
1066     }
1067     return mFramesReadySafe;
1068 }
1069 
framesReadySafe() const1070 size_t StaticAudioTrackServerProxy::framesReadySafe() const
1071 {
1072     return mFramesReadySafe;
1073 }
1074 
updateStateWithLoop(StaticAudioTrackState * localState,const StaticAudioTrackState & update) const1075 status_t StaticAudioTrackServerProxy::updateStateWithLoop(
1076         StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1077 {
1078     if (localState->mLoopSequence != update.mLoopSequence) {
1079         bool valid = false;
1080         const size_t loopStart = update.mLoopStart;
1081         const size_t loopEnd = update.mLoopEnd;
1082         size_t position = localState->mPosition;
1083         if (update.mLoopCount == 0) {
1084             valid = true;
1085         } else if (update.mLoopCount >= -1) {
1086             if (loopStart < loopEnd && loopEnd <= mFrameCount &&
1087                     loopEnd - loopStart >= MIN_LOOP) {
1088                 // If the current position is greater than the end of the loop
1089                 // we "wrap" to the loop start. This might cause an audible pop.
1090                 if (position >= loopEnd) {
1091                     position = loopStart;
1092                 }
1093                 valid = true;
1094             }
1095         }
1096         if (!valid || position > mFrameCount) {
1097             return NO_INIT;
1098         }
1099         localState->mPosition = position;
1100         localState->mLoopCount = update.mLoopCount;
1101         localState->mLoopEnd = loopEnd;
1102         localState->mLoopStart = loopStart;
1103         localState->mLoopSequence = update.mLoopSequence;
1104     }
1105     return OK;
1106 }
1107 
updateStateWithPosition(StaticAudioTrackState * localState,const StaticAudioTrackState & update) const1108 status_t StaticAudioTrackServerProxy::updateStateWithPosition(
1109         StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1110 {
1111     if (localState->mPositionSequence != update.mPositionSequence) {
1112         if (update.mPosition > mFrameCount) {
1113             return NO_INIT;
1114         } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
1115             localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
1116         }
1117         localState->mPosition = update.mPosition;
1118         localState->mPositionSequence = update.mPositionSequence;
1119     }
1120     return OK;
1121 }
1122 
pollPosition()1123 ssize_t StaticAudioTrackServerProxy::pollPosition()
1124 {
1125     StaticAudioTrackState state;
1126     if (mObserver.poll(state)) {
1127         StaticAudioTrackState trystate = mState;
1128         bool result;
1129         const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
1130 
1131         if (diffSeq < 0) {
1132             result = updateStateWithLoop(&trystate, state) == OK &&
1133                     updateStateWithPosition(&trystate, state) == OK;
1134         } else {
1135             result = updateStateWithPosition(&trystate, state) == OK &&
1136                     updateStateWithLoop(&trystate, state) == OK;
1137         }
1138         if (!result) {
1139             mObserver.done();
1140             // caution: no update occurs so server state will be inconsistent with client state.
1141             ALOGE("%s client pushed an invalid state, shutting down", __func__);
1142             mIsShutdown = true;
1143             return (ssize_t) NO_INIT;
1144         }
1145         mState = trystate;
1146         if (mState.mLoopCount == -1) {
1147             mFramesReady = INT64_MAX;
1148         } else if (mState.mLoopCount == 0) {
1149             mFramesReady = mFrameCount - mState.mPosition;
1150         } else if (mState.mLoopCount > 0) {
1151             // TODO: Later consider fixing overflow, but does not seem needed now
1152             // as will not overflow if loopStart and loopEnd are Java "ints".
1153             mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
1154                     + mFrameCount - mState.mPosition;
1155         }
1156         mFramesReadySafe = clampToSize(mFramesReady);
1157         // This may overflow, but client is not supposed to rely on it
1158         StaticAudioTrackPosLoop posLoop;
1159 
1160         posLoop.mLoopCount = (int32_t) mState.mLoopCount;
1161         posLoop.mBufferPosition = (uint32_t) mState.mPosition;
1162         mPosLoopMutator.push(posLoop);
1163         mObserver.done(); // safe to read mStatic variables.
1164     }
1165     return (ssize_t) mState.mPosition;
1166 }
1167 
1168 __attribute__((no_sanitize("integer")))
obtainBuffer(Buffer * buffer,bool ackFlush)1169 status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
1170 {
1171     if (mIsShutdown) {
1172         buffer->mFrameCount = 0;
1173         buffer->mRaw = NULL;
1174         buffer->mNonContig = 0;
1175         mUnreleased = 0;
1176         return NO_INIT;
1177     }
1178     ssize_t positionOrStatus = pollPosition();
1179     if (positionOrStatus < 0) {
1180         buffer->mFrameCount = 0;
1181         buffer->mRaw = NULL;
1182         buffer->mNonContig = 0;
1183         mUnreleased = 0;
1184         return (status_t) positionOrStatus;
1185     }
1186     size_t position = (size_t) positionOrStatus;
1187     size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
1188     size_t avail;
1189     if (position < end) {
1190         avail = end - position;
1191         size_t wanted = buffer->mFrameCount;
1192         if (avail < wanted) {
1193             buffer->mFrameCount = avail;
1194         } else {
1195             avail = wanted;
1196         }
1197         buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1198     } else {
1199         avail = 0;
1200         buffer->mFrameCount = 0;
1201         buffer->mRaw = NULL;
1202     }
1203     // As mFramesReady is the total remaining frames in the static audio track,
1204     // it is always larger or equal to avail.
1205     LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail,
1206             "%s: mFramesReady out of range, mFramesReady:%lld < avail:%zu",
1207             __func__, (long long)mFramesReady, avail);
1208     buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
1209     if (!ackFlush) {
1210         mUnreleased = avail;
1211     }
1212     return NO_ERROR;
1213 }
1214 
1215 __attribute__((no_sanitize("integer")))
releaseBuffer(Buffer * buffer)1216 void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1217 {
1218     size_t stepCount = buffer->mFrameCount;
1219     LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady),
1220             "%s: stepCount out of range, "
1221             "!(stepCount:%zu <= mFramesReady:%lld)",
1222             __func__, stepCount, (long long)mFramesReady);
1223     LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased),
1224             "%s: stepCount out of range, "
1225             "!(stepCount:%zu <= mUnreleased:%zu)",
1226             __func__, stepCount, mUnreleased);
1227     if (stepCount == 0) {
1228         // prevent accidental re-use of buffer
1229         buffer->mRaw = NULL;
1230         buffer->mNonContig = 0;
1231         return;
1232     }
1233     mUnreleased -= stepCount;
1234     audio_track_cblk_t* cblk = mCblk;
1235     size_t position = mState.mPosition;
1236     size_t newPosition = position + stepCount;
1237     int32_t setFlags = 0;
1238     if (!(position <= newPosition && newPosition <= mFrameCount)) {
1239         ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1240                 mFrameCount);
1241         newPosition = mFrameCount;
1242     } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
1243         newPosition = mState.mLoopStart;
1244         if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
1245             setFlags = CBLK_LOOP_CYCLE;
1246         } else {
1247             setFlags = CBLK_LOOP_FINAL;
1248         }
1249     }
1250     if (newPosition == mFrameCount) {
1251         setFlags |= CBLK_BUFFER_END;
1252     }
1253     mState.mPosition = newPosition;
1254     if (mFramesReady != INT64_MAX) {
1255         mFramesReady -= stepCount;
1256     }
1257     mFramesReadySafe = clampToSize(mFramesReady);
1258 
1259     cblk->mServer += stepCount;
1260     mReleased += stepCount;
1261 
1262     // This may overflow, but client is not supposed to rely on it
1263     StaticAudioTrackPosLoop posLoop;
1264     posLoop.mBufferPosition = mState.mPosition;
1265     posLoop.mLoopCount = mState.mLoopCount;
1266     mPosLoopMutator.push(posLoop);
1267     if (setFlags != 0) {
1268         (void) android_atomic_or(setFlags, &cblk->mFlags);
1269         // this would be a good place to wake a futex
1270     }
1271 
1272     buffer->mFrameCount = 0;
1273     buffer->mRaw = NULL;
1274     buffer->mNonContig = 0;
1275 }
1276 
tallyUnderrunFrames(uint32_t frameCount)1277 void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
1278 {
1279     // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1280     // we don't have a location to count underrun frames.  The underrun frame counter
1281     // only exists in AudioTrackSharedStreaming.  Fortunately, underruns are not
1282     // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1283 
1284     // FIXME also wake futex so that underrun is noticed more quickly
1285     if (frameCount > 0) {
1286         (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1287     }
1288 }
1289 
getRear() const1290 int32_t StaticAudioTrackServerProxy::getRear() const
1291 {
1292     LOG_ALWAYS_FATAL("getRear() not permitted for static tracks");
1293     return 0;
1294 }
1295 
1296 __attribute__((no_sanitize("integer")))
framesReadySafe() const1297 size_t AudioRecordServerProxy::framesReadySafe() const
1298 {
1299     if (mIsShutdown) {
1300         return 0;
1301     }
1302     const int32_t front = android_atomic_acquire_load(&mCblk->u.mStreaming.mFront);
1303     const int32_t rear = mCblk->u.mStreaming.mRear;
1304     const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
1305     if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
1306         return 0; // error condition, silently return 0.
1307     }
1308     return filled;
1309 }
1310 
1311 // ---------------------------------------------------------------------------
1312 
1313 }   // namespace android
1314