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