blob: e2c96988c64648e21062e3eccdcd5b822cd6d023 [file] [log] [blame]
Glenn Kastena8190fc2012-12-03 17:06:56 -08001/*
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
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -070020#include <android-base/macros.h>
Glenn Kastena8190fc2012-12-03 17:06:56 -080021#include <private/media/AudioTrackShared.h>
22#include <utils/Log.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070023#include <audio_utils/safe_math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070024
25#include <linux/futex.h>
26#include <sys/syscall.h>
Glenn Kastena8190fc2012-12-03 17:06:56 -080027
28namespace android {
29
Andy Hungcb2129b2014-11-11 12:17:22 -080030// used to clamp a value to size_t. TODO: move to another file.
31template <typename T>
32size_t clampToSize(T x) {
Andy Hung486a7132014-12-22 16:54:21 -080033 return sizeof(T) > sizeof(size_t) && x > (T) SIZE_MAX ? SIZE_MAX : x < 0 ? 0 : (size_t) x;
Andy Hungcb2129b2014-11-11 12:17:22 -080034}
35
Andy Hung9b461582014-12-01 17:56:29 -080036// incrementSequence is used to determine the next sequence value
37// for the loop and position sequence counters. It should return
38// a value between "other" + 1 and "other" + INT32_MAX, the choice of
39// which needs to be the "least recently used" sequence value for "self".
40// In general, this means (new_self) returned is max(self, other) + 1.
Andy Hungd4ee4db2017-07-12 15:26:04 -070041__attribute__((no_sanitize("integer")))
Andy Hung9b461582014-12-01 17:56:29 -080042static uint32_t incrementSequence(uint32_t self, uint32_t other) {
Chad Brubakercb50c542015-10-07 14:20:10 -070043 int32_t diff = (int32_t) self - (int32_t) other;
Andy Hung9b461582014-12-01 17:56:29 -080044 if (diff >= 0 && diff < INT32_MAX) {
45 return self + 1; // we're already ahead of other.
46 }
47 return other + 1; // we're behind, so move just ahead of other.
48}
49
Glenn Kastena8190fc2012-12-03 17:06:56 -080050audio_track_cblk_t::audio_track_cblk_t()
Phil Burke8972b02016-03-04 11:29:57 -080051 : mServer(0), mFutex(0), mMinimum(0)
52 , mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0)
53 , mBufferSizeInFrames(0)
54 , mFlags(0)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080055{
56 memset(&u, 0, sizeof(u));
57}
58
59// ---------------------------------------------------------------------------
60
61Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
62 bool isOut, bool clientInServer)
63 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
64 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
Glenn Kasten7db7df02013-06-25 16:13:23 -070065 mIsShutdown(false), mUnreleased(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080066{
67}
68
Glenn Kasten9f80dd22012-12-18 15:57:32 -080069// ---------------------------------------------------------------------------
70
71ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
72 size_t frameSize, bool isOut, bool clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080073 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080074 , mEpoch(0)
Andy Hung6ae58432016-02-16 18:32:24 -080075 , mTimestampObserver(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -080076{
Phil Burke8972b02016-03-04 11:29:57 -080077 setBufferSizeInFrames(frameCount);
Glenn Kastena8190fc2012-12-03 17:06:56 -080078}
79
Glenn Kasten9f80dd22012-12-18 15:57:32 -080080const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
81const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
82
83#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
84
85// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
86// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
87// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
88// order of minutes.
89#define MAX_SEC 5
90
Phil Burke8972b02016-03-04 11:29:57 -080091uint32_t ClientProxy::setBufferSizeInFrames(uint32_t size)
92{
Phil Burke8972b02016-03-04 11:29:57 -080093 // The minimum should be greater than zero and less than the size
94 // at which underruns will occur.
Phil Burk26760d12016-03-21 11:53:07 -070095 const uint32_t minimum = 16; // based on AudioMixer::BLOCKSIZE
Phil Burke8972b02016-03-04 11:29:57 -080096 const uint32_t maximum = frameCount();
97 uint32_t clippedSize = size;
Phil Burk26760d12016-03-21 11:53:07 -070098 if (maximum < minimum) {
99 clippedSize = maximum;
100 } else if (clippedSize < minimum) {
Phil Burke8972b02016-03-04 11:29:57 -0800101 clippedSize = minimum;
102 } else if (clippedSize > maximum) {
103 clippedSize = maximum;
104 }
105 // for server to read
106 android_atomic_release_store(clippedSize, (int32_t *)&mCblk->mBufferSizeInFrames);
107 // for client to read
108 mBufferSizeInFrames = clippedSize;
109 return clippedSize;
110}
111
ilewis926b82f2016-03-29 14:50:36 -0700112__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800113status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
114 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800115{
Andy Hung9c64f342017-08-02 18:10:00 -0700116 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
117 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800118 struct timespec total; // total elapsed time spent waiting
119 total.tv_sec = 0;
120 total.tv_nsec = 0;
121 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -0800122
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800123 status_t status;
124 enum {
125 TIMEOUT_ZERO, // requested == NULL || *requested == 0
126 TIMEOUT_INFINITE, // *requested == infinity
127 TIMEOUT_FINITE, // 0 < *requested < infinity
128 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
129 } timeout;
130 if (requested == NULL) {
131 timeout = TIMEOUT_ZERO;
132 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
133 timeout = TIMEOUT_ZERO;
134 } else if (requested->tv_sec == INT_MAX) {
135 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800136 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800137 timeout = TIMEOUT_FINITE;
138 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
139 measure = true;
140 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800141 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800142 struct timespec before;
143 bool beforeIsValid = false;
144 audio_track_cblk_t* cblk = mCblk;
145 bool ignoreInitialPendingInterrupt = true;
146 // check for shared memory corruption
147 if (mIsShutdown) {
148 status = NO_INIT;
149 goto end;
150 }
151 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700152 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800153 // check for track invalidation by server, or server death detection
154 if (flags & CBLK_INVALID) {
155 ALOGV("Track invalidated");
156 status = DEAD_OBJECT;
157 goto end;
158 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800159 if (flags & CBLK_DISABLED) {
160 ALOGV("Track disabled");
161 status = NOT_ENOUGH_DATA;
162 goto end;
163 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800164 // check for obtainBuffer interrupted by client
165 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
166 ALOGV("obtainBuffer() interrupted by client");
167 status = -EINTR;
168 goto end;
169 }
170 ignoreInitialPendingInterrupt = false;
171 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
172 int32_t front;
173 int32_t rear;
174 if (mIsOut) {
175 // The barrier following the read of mFront is probably redundant.
176 // We're about to perform a conditional branch based on 'filled',
177 // which will force the processor to observe the read of mFront
178 // prior to allowing data writes starting at mRaw.
179 // However, the processor may support speculative execution,
180 // and be unable to undo speculative writes into shared memory.
181 // The barrier will prevent such speculative execution.
182 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
183 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800184 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800185 // On the other hand, this barrier is required.
186 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
187 front = cblk->u.mStreaming.mFront;
188 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800189 // write to rear, read from front
Hongwei Wang95e37682019-04-12 11:13:36 -0700190 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800191 // pipe should not be overfull
192 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700193 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700194 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700195 "shutting down", filled, mFrameCount);
196 mIsShutdown = true;
197 status = NO_INIT;
198 goto end;
199 }
200 // for input, sync up on overrun
201 filled = 0;
202 cblk->u.mStreaming.mFront = rear;
203 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800204 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800205 // Don't allow filling pipe beyond the user settable size.
206 // The calculation for avail can go negative if the buffer size
207 // is suddenly dropped below the amount already in the buffer.
208 // So use a signed calculation to prevent a numeric overflow abort.
Phil Burke8972b02016-03-04 11:29:57 -0800209 ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800210 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
211 if (avail < 0) {
212 avail = 0;
213 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800214 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800215 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800216 if (mIsOut) {
217 rear &= mFrameCountP2 - 1;
218 part1 = mFrameCountP2 - rear;
219 } else {
220 front &= mFrameCountP2 - 1;
221 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800222 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800223 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800225 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800226 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800227 part1 = buffer->mFrameCount;
228 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800229 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800230 buffer->mRaw = part1 > 0 ?
231 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
232 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700233 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800234 status = NO_ERROR;
235 break;
236 }
237 struct timespec remaining;
238 const struct timespec *ts;
239 switch (timeout) {
240 case TIMEOUT_ZERO:
241 status = WOULD_BLOCK;
242 goto end;
243 case TIMEOUT_INFINITE:
244 ts = NULL;
245 break;
246 case TIMEOUT_FINITE:
247 timeout = TIMEOUT_CONTINUE;
248 if (MAX_SEC == 0) {
249 ts = requested;
250 break;
251 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -0700252 FALLTHROUGH_INTENDED;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800253 case TIMEOUT_CONTINUE:
254 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
255 if (!measure || requested->tv_sec < total.tv_sec ||
256 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
257 status = TIMED_OUT;
258 goto end;
259 }
260 remaining.tv_sec = requested->tv_sec - total.tv_sec;
261 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
262 remaining.tv_nsec += 1000000000;
263 remaining.tv_sec++;
264 }
265 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
266 remaining.tv_sec = MAX_SEC;
267 remaining.tv_nsec = 0;
268 }
269 ts = &remaining;
270 break;
271 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800272 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800273 ts = NULL;
274 break;
275 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700276 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
277 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800278 if (measure && !beforeIsValid) {
279 clock_gettime(CLOCK_MONOTONIC, &before);
280 beforeIsValid = true;
281 }
Elliott Hughesee499292014-05-21 17:55:51 -0700282 errno = 0;
283 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700284 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800285 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800286 // update total elapsed time spent waiting
287 if (measure) {
288 struct timespec after;
289 clock_gettime(CLOCK_MONOTONIC, &after);
290 total.tv_sec += after.tv_sec - before.tv_sec;
Chih-Hung Hsiehbca74292018-08-10 16:06:07 -0700291 // Use auto instead of long to avoid the google-runtime-int warning.
292 auto deltaNs = after.tv_nsec - before.tv_nsec;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800293 if (deltaNs < 0) {
294 deltaNs += 1000000000;
295 total.tv_sec--;
296 }
297 if ((total.tv_nsec += deltaNs) >= 1000000000) {
298 total.tv_nsec -= 1000000000;
299 total.tv_sec++;
300 }
301 before = after;
302 beforeIsValid = true;
303 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800304 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700305 case 0: // normal wakeup by server, or by binderDied()
306 case EWOULDBLOCK: // benign race condition with server
307 case EINTR: // wait was interrupted by signal or other spurious wakeup
308 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700309 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800310 break;
311 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800312 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700313 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800314 goto end;
315 }
316 }
317 }
318
319end:
320 if (status != NO_ERROR) {
321 buffer->mFrameCount = 0;
322 buffer->mRaw = NULL;
323 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700324 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800325 }
326 if (elapsed != NULL) {
327 *elapsed = total;
328 }
329 if (requested == NULL) {
330 requested = &kNonBlocking;
331 }
332 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100333 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
334 requested->tv_sec, requested->tv_nsec / 1000000,
335 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800336 }
337 return status;
338}
339
ilewis926b82f2016-03-29 14:50:36 -0700340__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800341void ClientProxy::releaseBuffer(Buffer* buffer)
342{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700343 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800344 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700345 if (stepCount == 0 || mIsShutdown) {
346 // prevent accidental re-use of buffer
347 buffer->mFrameCount = 0;
348 buffer->mRaw = NULL;
349 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800350 return;
351 }
Andy Hung9c64f342017-08-02 18:10:00 -0700352 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
353 "%s: mUnreleased out of range, "
354 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu), BufferSizeInFrames:%u",
355 __func__, stepCount, mUnreleased, mFrameCount, getBufferSizeInFrames());
Glenn Kasten7db7df02013-06-25 16:13:23 -0700356 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800357 audio_track_cblk_t* cblk = mCblk;
358 // Both of these barriers are required
359 if (mIsOut) {
360 int32_t rear = cblk->u.mStreaming.mRear;
361 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
362 } else {
363 int32_t front = cblk->u.mStreaming.mFront;
364 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
365 }
366}
367
368void ClientProxy::binderDied()
369{
370 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700371 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900372 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800373 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700374 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
375 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800376 }
377}
378
379void ClientProxy::interrupt()
380{
381 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700382 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900383 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700384 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
385 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800386 }
387}
388
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700389__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800390size_t ClientProxy::getMisalignment()
391{
392 audio_track_cblk_t* cblk = mCblk;
393 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
394 (mFrameCountP2 - 1);
395}
396
397// ---------------------------------------------------------------------------
398
399void AudioTrackClientProxy::flush()
400{
Andy Hung1d3556d2018-03-29 16:30:14 -0700401 sendStreamingFlushStop(true /* flush */);
402}
403
404void AudioTrackClientProxy::stop()
405{
406 sendStreamingFlushStop(false /* flush */);
407}
408
409// Sets the client-written mFlush and mStop positions, which control server behavior.
410//
411// @param flush indicates whether the operation is a flush or stop.
412// A client stop sets mStop to the current write position;
413// the server will not read past this point until start() or subsequent flush().
414// A client flush sets both mStop and mFlush to the current write position.
415// This advances the server read limit (if previously set) and on the next
416// server read advances the server read position to this limit.
417//
418void AudioTrackClientProxy::sendStreamingFlushStop(bool flush)
419{
420 // TODO: Replace this by 64 bit counters - avoids wrap complication.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700421 // This works for mFrameCountP2 <= 2^30
Andy Hunga2d75cd2015-07-15 17:04:20 -0700422 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
423 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
424 // if you want to flush twice to the same rear location after a 32 bit wrap.
Andy Hung1d3556d2018-03-29 16:30:14 -0700425
426 const size_t increment = mFrameCountP2 << 1;
427 const size_t mask = increment - 1;
428 // No need for client atomic synchronization on mRear, mStop, mFlush
429 // as AudioTrack client only read/writes to them under client lock. Server only reads.
430 const int32_t rearMasked = mCblk->u.mStreaming.mRear & mask;
431
432 // update stop before flush so that the server front
433 // never advances beyond a (potential) previous stop's rear limit.
434 int32_t stopBits; // the following add can overflow
435 __builtin_add_overflow(mCblk->u.mStreaming.mStop & ~mask, increment, &stopBits);
436 android_atomic_release_store(rearMasked | stopBits, &mCblk->u.mStreaming.mStop);
437
438 if (flush) {
439 int32_t flushBits; // the following add can overflow
440 __builtin_add_overflow(mCblk->u.mStreaming.mFlush & ~mask, increment, &flushBits);
441 android_atomic_release_store(rearMasked | flushBits, &mCblk->u.mStreaming.mFlush);
442 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800443}
444
Eric Laurentbfb1b832013-01-07 09:53:42 -0800445bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700446 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800447}
448
449bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700450 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800451}
452
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100453status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
454{
455 struct timespec total; // total elapsed time spent waiting
456 total.tv_sec = 0;
457 total.tv_nsec = 0;
458 audio_track_cblk_t* cblk = mCblk;
459 status_t status;
460 enum {
461 TIMEOUT_ZERO, // requested == NULL || *requested == 0
462 TIMEOUT_INFINITE, // *requested == infinity
463 TIMEOUT_FINITE, // 0 < *requested < infinity
464 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
465 } timeout;
466 if (requested == NULL) {
467 timeout = TIMEOUT_ZERO;
468 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
469 timeout = TIMEOUT_ZERO;
470 } else if (requested->tv_sec == INT_MAX) {
471 timeout = TIMEOUT_INFINITE;
472 } else {
473 timeout = TIMEOUT_FINITE;
474 }
475 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700476 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100477 // check for track invalidation by server, or server death detection
478 if (flags & CBLK_INVALID) {
479 ALOGV("Track invalidated");
480 status = DEAD_OBJECT;
481 goto end;
482 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800483 // a track is not supposed to underrun at this stage but consider it done
484 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100485 ALOGV("stream end received");
486 status = NO_ERROR;
487 goto end;
488 }
489 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100490 if (flags & CBLK_INTERRUPT) {
491 ALOGV("waitStreamEndDone() interrupted by client");
492 status = -EINTR;
493 goto end;
494 }
495 struct timespec remaining;
496 const struct timespec *ts;
497 switch (timeout) {
498 case TIMEOUT_ZERO:
499 status = WOULD_BLOCK;
500 goto end;
501 case TIMEOUT_INFINITE:
502 ts = NULL;
503 break;
504 case TIMEOUT_FINITE:
505 timeout = TIMEOUT_CONTINUE;
506 if (MAX_SEC == 0) {
507 ts = requested;
508 break;
509 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -0700510 FALLTHROUGH_INTENDED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100511 case TIMEOUT_CONTINUE:
512 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
513 if (requested->tv_sec < total.tv_sec ||
514 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
515 status = TIMED_OUT;
516 goto end;
517 }
518 remaining.tv_sec = requested->tv_sec - total.tv_sec;
519 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
520 remaining.tv_nsec += 1000000000;
521 remaining.tv_sec++;
522 }
523 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
524 remaining.tv_sec = MAX_SEC;
525 remaining.tv_nsec = 0;
526 }
527 ts = &remaining;
528 break;
529 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800530 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100531 ts = NULL;
532 break;
533 }
534 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
535 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700536 errno = 0;
537 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100538 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700539 switch (errno) {
540 case 0: // normal wakeup by server, or by binderDied()
541 case EWOULDBLOCK: // benign race condition with server
542 case EINTR: // wait was interrupted by signal or other spurious wakeup
543 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100544 break;
545 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700546 status = errno;
547 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100548 goto end;
549 }
550 }
551 }
552
553end:
554 if (requested == NULL) {
555 requested = &kNonBlocking;
556 }
557 return status;
558}
559
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800560// ---------------------------------------------------------------------------
561
562StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
563 size_t frameCount, size_t frameSize)
564 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800565 mMutator(&cblk->u.mStatic.mSingleStateQueue),
566 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567{
Andy Hung9b461582014-12-01 17:56:29 -0800568 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800569 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800570}
571
572void StaticAudioTrackClientProxy::flush()
573{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800574 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800575}
576
Andy Hung1d3556d2018-03-29 16:30:14 -0700577void StaticAudioTrackClientProxy::stop()
578{
579 ; // no special handling required for static tracks.
580}
581
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800582void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
583{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800584 // This can only happen on a 64-bit client
585 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
586 // FIXME Should return an error status
587 return;
588 }
Andy Hung9b461582014-12-01 17:56:29 -0800589 mState.mLoopStart = (uint32_t) loopStart;
590 mState.mLoopEnd = (uint32_t) loopEnd;
591 mState.mLoopCount = loopCount;
592 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
593 // set patch-up variables until the mState is acknowledged by the ServerProxy.
594 // observed buffer position and loop count will freeze until then to give the
595 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800596 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800597 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800598 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
599 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800600 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800601 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800602 (void) mMutator.push(mState);
603}
604
605void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
606{
607 // This can only happen on a 64-bit client
608 if (position > UINT32_MAX) {
609 // FIXME Should return an error status
610 return;
611 }
612 mState.mPosition = (uint32_t) position;
613 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800614 // set patch-up variables until the mState is acknowledged by the ServerProxy.
615 // observed buffer position and loop count will freeze until then to give the
616 // illusion of a synchronous change.
617 if (mState.mLoopCount > 0) { // only check if loop count is changing
618 getBufferPositionAndLoopCount(NULL, NULL); // get last position
619 }
620 mPosLoop.mBufferPosition = position;
621 if (position >= mState.mLoopEnd) {
622 // no ongoing loop is possible if position is greater than loopEnd.
623 mPosLoop.mLoopCount = 0;
624 }
Andy Hung9b461582014-12-01 17:56:29 -0800625 (void) mMutator.push(mState);
626}
627
628void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
629 size_t loopEnd, int loopCount)
630{
631 setLoop(loopStart, loopEnd, loopCount);
632 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800633}
634
635size_t StaticAudioTrackClientProxy::getBufferPosition()
636{
Andy Hung4ede21d2014-12-12 15:37:34 -0800637 getBufferPositionAndLoopCount(NULL, NULL);
638 return mPosLoop.mBufferPosition;
639}
640
641void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
642 size_t *position, int *loopCount)
643{
644 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
645 if (mPosLoopObserver.poll(mPosLoop)) {
646 ; // a valid mPosLoop should be available if ackDone is true.
647 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800648 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800649 if (position != NULL) {
650 *position = mPosLoop.mBufferPosition;
651 }
652 if (loopCount != NULL) {
653 *loopCount = mPosLoop.mLoopCount;
654 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800655}
656
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800657// ---------------------------------------------------------------------------
658
659ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
660 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700661 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hungea2b9c02016-02-12 17:06:53 -0800662 mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800663 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800664{
Phil Burke8972b02016-03-04 11:29:57 -0800665 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800666}
667
ilewis926b82f2016-03-29 14:50:36 -0700668__attribute__((no_sanitize("integer")))
Phil Burk4bb650b2016-09-09 12:11:17 -0700669void ServerProxy::flushBufferIfNeeded()
670{
671 audio_track_cblk_t* cblk = mCblk;
672 // The acquire_load is not really required. But since the write is a release_store in the
673 // client, using acquire_load here makes it easier for people to maintain the code,
674 // and the logic for communicating ipc variables seems somewhat standard,
675 // and there really isn't much penalty for 4 or 8 byte atomics.
676 int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
677 if (flush != mFlush) {
678 ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
679 flush, mFlush);
Andy Hung1d3556d2018-03-29 16:30:14 -0700680 // shouldn't matter, but for range safety use mRear instead of getRear().
Phil Burk4bb650b2016-09-09 12:11:17 -0700681 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
682 int32_t front = cblk->u.mStreaming.mFront;
683
684 // effectively obtain then release whatever is in the buffer
685 const size_t overflowBit = mFrameCountP2 << 1;
686 const size_t mask = overflowBit - 1;
687 int32_t newFront = (front & ~mask) | (flush & mask);
Hongwei Wang95e37682019-04-12 11:13:36 -0700688 ssize_t filled = audio_utils::safe_sub_overflow(rear, newFront);
Phil Burk4bb650b2016-09-09 12:11:17 -0700689 if (filled >= (ssize_t)overflowBit) {
690 // front and rear offsets span the overflow bit of the p2 mask
691 // so rebasing newFront on the front offset is off by the overflow bit.
692 // adjust newFront to match rear offset.
693 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
694 newFront += overflowBit;
695 filled -= overflowBit;
696 }
697 // Rather than shutting down on a corrupt flush, just treat it as a full flush
698 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
699 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
700 "filled %zd=%#x",
701 mFlush, flush, front, rear,
702 (unsigned)mask, newFront, filled, (unsigned)filled);
703 newFront = rear;
704 }
705 mFlush = flush;
706 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
707 // There is no danger from a false positive, so err on the side of caution
708 if (true /*front != newFront*/) {
709 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
710 if (!(old & CBLK_FUTEX_WAKE)) {
711 (void) syscall(__NR_futex, &cblk->mFutex,
712 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
713 }
714 }
715 mFlushed += (newFront - front) & mask;
716 }
717}
718
719__attribute__((no_sanitize("integer")))
Andy Hung1d3556d2018-03-29 16:30:14 -0700720int32_t AudioTrackServerProxy::getRear() const
721{
722 const int32_t stop = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
723 const int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
724 const int32_t stopLast = mStopLast.load(std::memory_order_acquire);
725 if (stop != stopLast) {
726 const int32_t front = mCblk->u.mStreaming.mFront;
727 const size_t overflowBit = mFrameCountP2 << 1;
728 const size_t mask = overflowBit - 1;
729 int32_t newRear = (rear & ~mask) | (stop & mask);
Hongwei Wang95e37682019-04-12 11:13:36 -0700730 ssize_t filled = audio_utils::safe_sub_overflow(newRear, front);
Andy Hung54274032018-04-19 18:16:44 -0700731 // overflowBit is unsigned, so cast to signed for comparison.
732 if (filled >= (ssize_t)overflowBit) {
Andy Hung1d3556d2018-03-29 16:30:14 -0700733 // front and rear offsets span the overflow bit of the p2 mask
Andy Hung54274032018-04-19 18:16:44 -0700734 // so rebasing newRear on the rear offset is off by the overflow bit.
Andy Hung1d3556d2018-03-29 16:30:14 -0700735 ALOGV("stop wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hung54274032018-04-19 18:16:44 -0700736 newRear -= overflowBit;
737 filled -= overflowBit;
Andy Hung1d3556d2018-03-29 16:30:14 -0700738 }
739 if (0 <= filled && (size_t) filled <= mFrameCount) {
740 // we're stopped, return the stop level as newRear
741 return newRear;
742 }
743
744 // A corrupt stop. Log error and ignore.
745 ALOGE("mStopLast %#x -> stop %#x, front %#x, rear %#x, mask %#x, newRear %#x, "
746 "filled %zd=%#x",
747 stopLast, stop, front, rear,
748 (unsigned)mask, newRear, filled, (unsigned)filled);
749 // Don't reset mStopLast as this is const.
750 }
751 return rear;
752}
753
754void AudioTrackServerProxy::start()
755{
756 mStopLast = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
757}
758
759__attribute__((no_sanitize("integer")))
Glenn Kasten2e422c42013-10-18 13:00:29 -0700760status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800761{
Andy Hung9c64f342017-08-02 18:10:00 -0700762 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
763 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800764 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700765 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800766 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700767 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800768 audio_track_cblk_t* cblk = mCblk;
769 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
770 // or use previous cached value from framesReady(), with added barrier if it omits.
771 int32_t front;
772 int32_t rear;
773 // See notes on barriers at ClientProxy::obtainBuffer()
774 if (mIsOut) {
Phil Burk4bb650b2016-09-09 12:11:17 -0700775 flushBufferIfNeeded(); // might modify mFront
Andy Hung1d3556d2018-03-29 16:30:14 -0700776 rear = getRear();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100777 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800778 } else {
779 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
780 rear = cblk->u.mStreaming.mRear;
781 }
Hongwei Wang95e37682019-04-12 11:13:36 -0700782 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800783 // pipe should not already be overfull
784 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800785 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
786 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800787 mIsShutdown = true;
788 }
789 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700790 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800791 }
792 // don't allow filling pipe beyond the nominal size
793 size_t availToServer;
794 if (mIsOut) {
795 availToServer = filled;
796 mAvailToClient = mFrameCount - filled;
797 } else {
798 availToServer = mFrameCount - filled;
799 mAvailToClient = filled;
800 }
801 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
802 size_t part1;
803 if (mIsOut) {
804 front &= mFrameCountP2 - 1;
805 part1 = mFrameCountP2 - front;
806 } else {
807 rear &= mFrameCountP2 - 1;
808 part1 = mFrameCountP2 - rear;
809 }
810 if (part1 > availToServer) {
811 part1 = availToServer;
812 }
813 size_t ask = buffer->mFrameCount;
814 if (part1 > ask) {
815 part1 = ask;
816 }
817 // is assignment redundant in some cases?
818 buffer->mFrameCount = part1;
819 buffer->mRaw = part1 > 0 ?
820 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
821 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700822 // After flush(), allow releaseBuffer() on a previously obtained buffer;
823 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
824 if (!ackFlush) {
825 mUnreleased = part1;
826 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700828 }
829no_init:
830 buffer->mFrameCount = 0;
831 buffer->mRaw = NULL;
832 buffer->mNonContig = 0;
833 mUnreleased = 0;
834 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800835}
836
ilewis926b82f2016-03-29 14:50:36 -0700837__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800838void ServerProxy::releaseBuffer(Buffer* buffer)
839{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700840 LOG_ALWAYS_FATAL_IF(buffer == NULL);
841 size_t stepCount = buffer->mFrameCount;
842 if (stepCount == 0 || mIsShutdown) {
843 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800844 buffer->mFrameCount = 0;
845 buffer->mRaw = NULL;
846 buffer->mNonContig = 0;
847 return;
848 }
Andy Hung9c64f342017-08-02 18:10:00 -0700849 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
850 "%s: mUnreleased out of range, "
851 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu)",
852 __func__, stepCount, mUnreleased, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800853 mUnreleased -= stepCount;
854 audio_track_cblk_t* cblk = mCblk;
855 if (mIsOut) {
856 int32_t front = cblk->u.mStreaming.mFront;
857 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
858 } else {
859 int32_t rear = cblk->u.mStreaming.mRear;
860 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
861 }
862
Glenn Kasten844f88c2014-05-09 13:38:09 -0700863 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800864 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800865
866 size_t half = mFrameCount / 2;
867 if (half == 0) {
868 half = 1;
869 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800870 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800871 if (minimum == 0) {
872 minimum = mIsOut ? half : 1;
873 } else if (minimum > half) {
874 minimum = half;
875 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700876 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700877 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700878 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700879 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
880 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700881 (void) syscall(__NR_futex, &cblk->mFutex,
882 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800883 }
884 }
885
886 buffer->mFrameCount = 0;
887 buffer->mRaw = NULL;
888 buffer->mNonContig = 0;
889}
890
891// ---------------------------------------------------------------------------
892
ilewis926b82f2016-03-29 14:50:36 -0700893__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800894size_t AudioTrackServerProxy::framesReady()
895{
896 LOG_ALWAYS_FATAL_IF(!mIsOut);
897
898 if (mIsShutdown) {
899 return 0;
900 }
901 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100902
Zhou Song1ed46a22020-08-17 15:36:56 +0800903 flushBufferIfNeeded();
904
Andy Hung1d3556d2018-03-29 16:30:14 -0700905 const int32_t rear = getRear();
Hongwei Wang95e37682019-04-12 11:13:36 -0700906 ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800907 // pipe should not already be overfull
908 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800909 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
910 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800911 mIsShutdown = true;
912 return 0;
913 }
914 // cache this value for later use by obtainBuffer(), with added barrier
915 // and racy if called by normal mixer thread
916 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
917 return filled;
918}
919
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700920__attribute__((no_sanitize("integer")))
921size_t AudioTrackServerProxy::framesReadySafe() const
922{
923 if (mIsShutdown) {
924 return 0;
925 }
926 const audio_track_cblk_t* cblk = mCblk;
927 const int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
928 if (flush != mFlush) {
929 return mFrameCount;
930 }
Andy Hung1d3556d2018-03-29 16:30:14 -0700931 const int32_t rear = getRear();
Hongwei Wang95e37682019-04-12 11:13:36 -0700932 const ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700933 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
934 return 0; // error condition, silently return 0.
935 }
936 return filled;
937}
938
Eric Laurentbfb1b832013-01-07 09:53:42 -0800939bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700940 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800941 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700942 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800943 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700944 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700945 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800946 }
947 return old;
948}
949
Andy Hungd4ee4db2017-07-12 15:26:04 -0700950__attribute__((no_sanitize("integer")))
Glenn Kasten82aaf942013-07-17 16:05:07 -0700951void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
952{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700953 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800954 if (frameCount > 0) {
955 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700956
Phil Burk2812d9e2016-01-04 10:34:30 -0800957 if (!mUnderrunning) { // start of underrun?
958 mUnderrunCount++;
959 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
960 mUnderrunning = true;
961 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
962 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
963 }
964
965 // FIXME also wake futex so that underrun is noticed more quickly
966 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
967 } else {
968 ALOGV_IF(mUnderrunning,
969 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
970 frameCount, cblk->u.mStreaming.mUnderrunFrames);
971 mUnderrunning = false; // so we can detect the next edge
972 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700973}
974
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700975AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700976{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700977 mPlaybackRateObserver.poll(mPlaybackRate);
978 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700979}
980
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800981// ---------------------------------------------------------------------------
982
983StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
Kevin Rocard36862032019-10-10 10:52:19 +0100984 size_t frameCount, size_t frameSize, uint32_t sampleRate)
985 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize, false /*clientInServer*/,
986 sampleRate),
Andy Hung4ede21d2014-12-12 15:37:34 -0800987 mObserver(&cblk->u.mStatic.mSingleStateQueue),
988 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800989 mFramesReadySafe(frameCount), mFramesReady(frameCount),
990 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800991{
Andy Hung9b461582014-12-01 17:56:29 -0800992 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800993}
994
995void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
996{
997 mFramesReadyIsCalledByMultipleThreads = true;
998}
999
1000size_t StaticAudioTrackServerProxy::framesReady()
1001{
Andy Hungcb2129b2014-11-11 12:17:22 -08001002 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001003 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001004 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001005 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001006 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001007}
1008
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001009size_t StaticAudioTrackServerProxy::framesReadySafe() const
1010{
1011 return mFramesReadySafe;
1012}
1013
Andy Hung9b461582014-12-01 17:56:29 -08001014status_t StaticAudioTrackServerProxy::updateStateWithLoop(
1015 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001016{
Andy Hung9b461582014-12-01 17:56:29 -08001017 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001018 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -08001019 const size_t loopStart = update.mLoopStart;
1020 const size_t loopEnd = update.mLoopEnd;
1021 size_t position = localState->mPosition;
1022 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001023 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -08001024 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001025 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
1026 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -08001027 // If the current position is greater than the end of the loop
1028 // we "wrap" to the loop start. This might cause an audible pop.
1029 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -08001030 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001031 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001032 valid = true;
1033 }
1034 }
Andy Hung9b461582014-12-01 17:56:29 -08001035 if (!valid || position > mFrameCount) {
1036 return NO_INIT;
1037 }
1038 localState->mPosition = position;
1039 localState->mLoopCount = update.mLoopCount;
1040 localState->mLoopEnd = loopEnd;
1041 localState->mLoopStart = loopStart;
1042 localState->mLoopSequence = update.mLoopSequence;
1043 }
1044 return OK;
1045}
1046
1047status_t StaticAudioTrackServerProxy::updateStateWithPosition(
1048 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1049{
1050 if (localState->mPositionSequence != update.mPositionSequence) {
1051 if (update.mPosition > mFrameCount) {
1052 return NO_INIT;
1053 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
1054 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
1055 }
1056 localState->mPosition = update.mPosition;
1057 localState->mPositionSequence = update.mPositionSequence;
1058 }
1059 return OK;
1060}
1061
1062ssize_t StaticAudioTrackServerProxy::pollPosition()
1063{
1064 StaticAudioTrackState state;
1065 if (mObserver.poll(state)) {
1066 StaticAudioTrackState trystate = mState;
1067 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -07001068 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -08001069
1070 if (diffSeq < 0) {
1071 result = updateStateWithLoop(&trystate, state) == OK &&
1072 updateStateWithPosition(&trystate, state) == OK;
1073 } else {
1074 result = updateStateWithPosition(&trystate, state) == OK &&
1075 updateStateWithLoop(&trystate, state) == OK;
1076 }
1077 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001078 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -08001079 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001080 ALOGE("%s client pushed an invalid state, shutting down", __func__);
1081 mIsShutdown = true;
1082 return (ssize_t) NO_INIT;
1083 }
Andy Hung9b461582014-12-01 17:56:29 -08001084 mState = trystate;
1085 if (mState.mLoopCount == -1) {
1086 mFramesReady = INT64_MAX;
1087 } else if (mState.mLoopCount == 0) {
1088 mFramesReady = mFrameCount - mState.mPosition;
1089 } else if (mState.mLoopCount > 0) {
1090 // TODO: Later consider fixing overflow, but does not seem needed now
1091 // as will not overflow if loopStart and loopEnd are Java "ints".
1092 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
1093 + mFrameCount - mState.mPosition;
1094 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001095 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001096 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001097 StaticAudioTrackPosLoop posLoop;
1098
1099 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
1100 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
1101 mPosLoopMutator.push(posLoop);
1102 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001103 }
Andy Hung9b461582014-12-01 17:56:29 -08001104 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001105}
1106
Andy Hungd4ee4db2017-07-12 15:26:04 -07001107__attribute__((no_sanitize("integer")))
Andy Hung954ca452015-09-09 14:39:02 -07001108status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001109{
1110 if (mIsShutdown) {
1111 buffer->mFrameCount = 0;
1112 buffer->mRaw = NULL;
1113 buffer->mNonContig = 0;
1114 mUnreleased = 0;
1115 return NO_INIT;
1116 }
1117 ssize_t positionOrStatus = pollPosition();
1118 if (positionOrStatus < 0) {
1119 buffer->mFrameCount = 0;
1120 buffer->mRaw = NULL;
1121 buffer->mNonContig = 0;
1122 mUnreleased = 0;
1123 return (status_t) positionOrStatus;
1124 }
1125 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -08001126 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001127 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -08001128 if (position < end) {
1129 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001130 size_t wanted = buffer->mFrameCount;
1131 if (avail < wanted) {
1132 buffer->mFrameCount = avail;
1133 } else {
1134 avail = wanted;
1135 }
1136 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1137 } else {
1138 avail = 0;
1139 buffer->mFrameCount = 0;
1140 buffer->mRaw = NULL;
1141 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001142 // As mFramesReady is the total remaining frames in the static audio track,
1143 // it is always larger or equal to avail.
Andy Hung9c64f342017-08-02 18:10:00 -07001144 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail,
1145 "%s: mFramesReady out of range, mFramesReady:%lld < avail:%zu",
1146 __func__, (long long)mFramesReady, avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001147 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001148 if (!ackFlush) {
1149 mUnreleased = avail;
1150 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001151 return NO_ERROR;
1152}
1153
Andy Hungd4ee4db2017-07-12 15:26:04 -07001154__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001155void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1156{
1157 size_t stepCount = buffer->mFrameCount;
Andy Hung9c64f342017-08-02 18:10:00 -07001158 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady),
1159 "%s: stepCount out of range, "
1160 "!(stepCount:%zu <= mFramesReady:%lld)",
1161 __func__, stepCount, (long long)mFramesReady);
1162 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased),
1163 "%s: stepCount out of range, "
1164 "!(stepCount:%zu <= mUnreleased:%zu)",
1165 __func__, stepCount, mUnreleased);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001166 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001167 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001168 buffer->mRaw = NULL;
1169 buffer->mNonContig = 0;
1170 return;
1171 }
1172 mUnreleased -= stepCount;
1173 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001174 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001175 size_t newPosition = position + stepCount;
1176 int32_t setFlags = 0;
1177 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001178 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1179 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001180 newPosition = mFrameCount;
1181 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001182 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001183 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001184 setFlags = CBLK_LOOP_CYCLE;
1185 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001186 setFlags = CBLK_LOOP_FINAL;
1187 }
1188 }
1189 if (newPosition == mFrameCount) {
1190 setFlags |= CBLK_BUFFER_END;
1191 }
Andy Hung9b461582014-12-01 17:56:29 -08001192 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001193 if (mFramesReady != INT64_MAX) {
1194 mFramesReady -= stepCount;
1195 }
1196 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001197
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001198 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001199 mReleased += stepCount;
1200
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001201 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001202 StaticAudioTrackPosLoop posLoop;
1203 posLoop.mBufferPosition = mState.mPosition;
1204 posLoop.mLoopCount = mState.mLoopCount;
1205 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001206 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001207 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001208 // this would be a good place to wake a futex
1209 }
1210
1211 buffer->mFrameCount = 0;
1212 buffer->mRaw = NULL;
1213 buffer->mNonContig = 0;
1214}
1215
Phil Burk2812d9e2016-01-04 10:34:30 -08001216void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001217{
1218 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1219 // we don't have a location to count underrun frames. The underrun frame counter
1220 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1221 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1222
1223 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001224 if (frameCount > 0) {
1225 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1226 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001227}
1228
Andy Hung1d3556d2018-03-29 16:30:14 -07001229int32_t StaticAudioTrackServerProxy::getRear() const
1230{
1231 LOG_ALWAYS_FATAL("getRear() not permitted for static tracks");
1232 return 0;
1233}
1234
Andy Hung2a4e1612018-06-01 15:06:09 -07001235__attribute__((no_sanitize("integer")))
1236size_t AudioRecordServerProxy::framesReadySafe() const
1237{
1238 if (mIsShutdown) {
1239 return 0;
1240 }
1241 const int32_t front = android_atomic_acquire_load(&mCblk->u.mStreaming.mFront);
1242 const int32_t rear = mCblk->u.mStreaming.mRear;
Hongwei Wang95e37682019-04-12 11:13:36 -07001243 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung2a4e1612018-06-01 15:06:09 -07001244 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
1245 return 0; // error condition, silently return 0.
1246 }
1247 return filled;
1248}
1249
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001250// ---------------------------------------------------------------------------
1251
Glenn Kastena8190fc2012-12-03 17:06:56 -08001252} // namespace android