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