blob: c997cfa59e41088b1ef126bd50c1d67ab620315d [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>
Elliott Hughesee499292014-05-21 17:55:51 -070023
24#include <linux/futex.h>
25#include <sys/syscall.h>
Glenn Kastena8190fc2012-12-03 17:06:56 -080026
27namespace android {
28
Andy Hung99e9db72018-09-14 15:17:36 -070029// TODO: consider pulling this into a shared header.
30// safe_sub_overflow is used ensure that subtraction occurs in the same native type
31// with proper 2's complement overflow. Without calling this function, it is possible,
32// for example, that optimizing compilers may elect to treat 32 bit subtraction
33// as 64 bit subtraction when storing into a 64 bit destination as integer overflow is
34// technically undefined.
35template<typename T,
36 typename U,
37 typename = std::enable_if_t<std::is_same<std::decay_t<T>,
38 std::decay_t<U>>{}>>
39 // ensure arguments are same type (ignoring volatile, which is used in cblk variables).
40auto safe_sub_overflow(const T& a, const U& b) {
41 std::decay_t<T> result;
42 (void)__builtin_sub_overflow(a, b, &result);
43 // note if __builtin_sub_overflow returns true, an overflow occurred.
44 return result;
45}
46
Andy Hungcb2129b2014-11-11 12:17:22 -080047// used to clamp a value to size_t. TODO: move to another file.
48template <typename T>
49size_t clampToSize(T x) {
Andy Hung486a7132014-12-22 16:54:21 -080050 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 -080051}
52
Andy Hung9b461582014-12-01 17:56:29 -080053// incrementSequence is used to determine the next sequence value
54// for the loop and position sequence counters. It should return
55// a value between "other" + 1 and "other" + INT32_MAX, the choice of
56// which needs to be the "least recently used" sequence value for "self".
57// In general, this means (new_self) returned is max(self, other) + 1.
Andy Hungd4ee4db2017-07-12 15:26:04 -070058__attribute__((no_sanitize("integer")))
Andy Hung9b461582014-12-01 17:56:29 -080059static uint32_t incrementSequence(uint32_t self, uint32_t other) {
Chad Brubakercb50c542015-10-07 14:20:10 -070060 int32_t diff = (int32_t) self - (int32_t) other;
Andy Hung9b461582014-12-01 17:56:29 -080061 if (diff >= 0 && diff < INT32_MAX) {
62 return self + 1; // we're already ahead of other.
63 }
64 return other + 1; // we're behind, so move just ahead of other.
65}
66
Glenn Kastena8190fc2012-12-03 17:06:56 -080067audio_track_cblk_t::audio_track_cblk_t()
Phil Burke8972b02016-03-04 11:29:57 -080068 : mServer(0), mFutex(0), mMinimum(0)
69 , mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0)
70 , mBufferSizeInFrames(0)
71 , mFlags(0)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080072{
73 memset(&u, 0, sizeof(u));
74}
75
76// ---------------------------------------------------------------------------
77
78Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
79 bool isOut, bool clientInServer)
80 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
81 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
Glenn Kasten7db7df02013-06-25 16:13:23 -070082 mIsShutdown(false), mUnreleased(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080083{
84}
85
Glenn Kasten9f80dd22012-12-18 15:57:32 -080086// ---------------------------------------------------------------------------
87
88ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
89 size_t frameSize, bool isOut, bool clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080090 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080091 , mEpoch(0)
Andy Hung6ae58432016-02-16 18:32:24 -080092 , mTimestampObserver(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -080093{
Phil Burke8972b02016-03-04 11:29:57 -080094 setBufferSizeInFrames(frameCount);
Glenn Kastena8190fc2012-12-03 17:06:56 -080095}
96
Glenn Kasten9f80dd22012-12-18 15:57:32 -080097const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
98const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
99
100#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
101
102// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
103// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
104// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
105// order of minutes.
106#define MAX_SEC 5
107
Phil Burke8972b02016-03-04 11:29:57 -0800108uint32_t ClientProxy::setBufferSizeInFrames(uint32_t size)
109{
Phil Burke8972b02016-03-04 11:29:57 -0800110 // The minimum should be greater than zero and less than the size
111 // at which underruns will occur.
Phil Burk26760d12016-03-21 11:53:07 -0700112 const uint32_t minimum = 16; // based on AudioMixer::BLOCKSIZE
Phil Burke8972b02016-03-04 11:29:57 -0800113 const uint32_t maximum = frameCount();
114 uint32_t clippedSize = size;
Phil Burk26760d12016-03-21 11:53:07 -0700115 if (maximum < minimum) {
116 clippedSize = maximum;
117 } else if (clippedSize < minimum) {
Phil Burke8972b02016-03-04 11:29:57 -0800118 clippedSize = minimum;
119 } else if (clippedSize > maximum) {
120 clippedSize = maximum;
121 }
122 // for server to read
123 android_atomic_release_store(clippedSize, (int32_t *)&mCblk->mBufferSizeInFrames);
124 // for client to read
125 mBufferSizeInFrames = clippedSize;
126 return clippedSize;
127}
128
ilewis926b82f2016-03-29 14:50:36 -0700129__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800130status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
131 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800132{
Andy Hung9c64f342017-08-02 18:10:00 -0700133 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
134 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800135 struct timespec total; // total elapsed time spent waiting
136 total.tv_sec = 0;
137 total.tv_nsec = 0;
138 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -0800139
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800140 status_t status;
141 enum {
142 TIMEOUT_ZERO, // requested == NULL || *requested == 0
143 TIMEOUT_INFINITE, // *requested == infinity
144 TIMEOUT_FINITE, // 0 < *requested < infinity
145 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
146 } timeout;
147 if (requested == NULL) {
148 timeout = TIMEOUT_ZERO;
149 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
150 timeout = TIMEOUT_ZERO;
151 } else if (requested->tv_sec == INT_MAX) {
152 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800153 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800154 timeout = TIMEOUT_FINITE;
155 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
156 measure = true;
157 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800158 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800159 struct timespec before;
160 bool beforeIsValid = false;
161 audio_track_cblk_t* cblk = mCblk;
162 bool ignoreInitialPendingInterrupt = true;
163 // check for shared memory corruption
164 if (mIsShutdown) {
165 status = NO_INIT;
166 goto end;
167 }
168 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700169 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800170 // check for track invalidation by server, or server death detection
171 if (flags & CBLK_INVALID) {
172 ALOGV("Track invalidated");
173 status = DEAD_OBJECT;
174 goto end;
175 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800176 if (flags & CBLK_DISABLED) {
177 ALOGV("Track disabled");
178 status = NOT_ENOUGH_DATA;
179 goto end;
180 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800181 // check for obtainBuffer interrupted by client
182 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
183 ALOGV("obtainBuffer() interrupted by client");
184 status = -EINTR;
185 goto end;
186 }
187 ignoreInitialPendingInterrupt = false;
188 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
189 int32_t front;
190 int32_t rear;
191 if (mIsOut) {
192 // The barrier following the read of mFront is probably redundant.
193 // We're about to perform a conditional branch based on 'filled',
194 // which will force the processor to observe the read of mFront
195 // prior to allowing data writes starting at mRaw.
196 // However, the processor may support speculative execution,
197 // and be unable to undo speculative writes into shared memory.
198 // The barrier will prevent such speculative execution.
199 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
200 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800201 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800202 // On the other hand, this barrier is required.
203 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
204 front = cblk->u.mStreaming.mFront;
205 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800206 // write to rear, read from front
Andy Hung99e9db72018-09-14 15:17:36 -0700207 ssize_t filled = safe_sub_overflow(rear, front);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800208 // pipe should not be overfull
209 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700210 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700211 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700212 "shutting down", filled, mFrameCount);
213 mIsShutdown = true;
214 status = NO_INIT;
215 goto end;
216 }
217 // for input, sync up on overrun
218 filled = 0;
219 cblk->u.mStreaming.mFront = rear;
220 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800221 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800222 // Don't allow filling pipe beyond the user settable size.
223 // The calculation for avail can go negative if the buffer size
224 // is suddenly dropped below the amount already in the buffer.
225 // So use a signed calculation to prevent a numeric overflow abort.
Phil Burke8972b02016-03-04 11:29:57 -0800226 ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800227 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
228 if (avail < 0) {
229 avail = 0;
230 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800231 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800232 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800233 if (mIsOut) {
234 rear &= mFrameCountP2 - 1;
235 part1 = mFrameCountP2 - rear;
236 } else {
237 front &= mFrameCountP2 - 1;
238 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800239 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800240 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800241 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800242 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800243 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800244 part1 = buffer->mFrameCount;
245 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800246 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800247 buffer->mRaw = part1 > 0 ?
248 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
249 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700250 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800251 status = NO_ERROR;
252 break;
253 }
254 struct timespec remaining;
255 const struct timespec *ts;
256 switch (timeout) {
257 case TIMEOUT_ZERO:
258 status = WOULD_BLOCK;
259 goto end;
260 case TIMEOUT_INFINITE:
261 ts = NULL;
262 break;
263 case TIMEOUT_FINITE:
264 timeout = TIMEOUT_CONTINUE;
265 if (MAX_SEC == 0) {
266 ts = requested;
267 break;
268 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -0700269 FALLTHROUGH_INTENDED;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800270 case TIMEOUT_CONTINUE:
271 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
272 if (!measure || requested->tv_sec < total.tv_sec ||
273 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
274 status = TIMED_OUT;
275 goto end;
276 }
277 remaining.tv_sec = requested->tv_sec - total.tv_sec;
278 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
279 remaining.tv_nsec += 1000000000;
280 remaining.tv_sec++;
281 }
282 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
283 remaining.tv_sec = MAX_SEC;
284 remaining.tv_nsec = 0;
285 }
286 ts = &remaining;
287 break;
288 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800289 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800290 ts = NULL;
291 break;
292 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700293 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
294 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800295 if (measure && !beforeIsValid) {
296 clock_gettime(CLOCK_MONOTONIC, &before);
297 beforeIsValid = true;
298 }
Elliott Hughesee499292014-05-21 17:55:51 -0700299 errno = 0;
300 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700301 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800302 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800303 // update total elapsed time spent waiting
304 if (measure) {
305 struct timespec after;
306 clock_gettime(CLOCK_MONOTONIC, &after);
307 total.tv_sec += after.tv_sec - before.tv_sec;
Chih-Hung Hsiehbca74292018-08-10 16:06:07 -0700308 // Use auto instead of long to avoid the google-runtime-int warning.
309 auto deltaNs = after.tv_nsec - before.tv_nsec;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800310 if (deltaNs < 0) {
311 deltaNs += 1000000000;
312 total.tv_sec--;
313 }
314 if ((total.tv_nsec += deltaNs) >= 1000000000) {
315 total.tv_nsec -= 1000000000;
316 total.tv_sec++;
317 }
318 before = after;
319 beforeIsValid = true;
320 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800321 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700322 case 0: // normal wakeup by server, or by binderDied()
323 case EWOULDBLOCK: // benign race condition with server
324 case EINTR: // wait was interrupted by signal or other spurious wakeup
325 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700326 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800327 break;
328 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800329 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700330 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800331 goto end;
332 }
333 }
334 }
335
336end:
337 if (status != NO_ERROR) {
338 buffer->mFrameCount = 0;
339 buffer->mRaw = NULL;
340 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700341 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800342 }
343 if (elapsed != NULL) {
344 *elapsed = total;
345 }
346 if (requested == NULL) {
347 requested = &kNonBlocking;
348 }
349 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100350 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
351 requested->tv_sec, requested->tv_nsec / 1000000,
352 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800353 }
354 return status;
355}
356
ilewis926b82f2016-03-29 14:50:36 -0700357__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800358void ClientProxy::releaseBuffer(Buffer* buffer)
359{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700360 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800361 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700362 if (stepCount == 0 || mIsShutdown) {
363 // prevent accidental re-use of buffer
364 buffer->mFrameCount = 0;
365 buffer->mRaw = NULL;
366 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800367 return;
368 }
Andy Hung9c64f342017-08-02 18:10:00 -0700369 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
370 "%s: mUnreleased out of range, "
371 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu), BufferSizeInFrames:%u",
372 __func__, stepCount, mUnreleased, mFrameCount, getBufferSizeInFrames());
Glenn Kasten7db7df02013-06-25 16:13:23 -0700373 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800374 audio_track_cblk_t* cblk = mCblk;
375 // Both of these barriers are required
376 if (mIsOut) {
377 int32_t rear = cblk->u.mStreaming.mRear;
378 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
379 } else {
380 int32_t front = cblk->u.mStreaming.mFront;
381 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
382 }
383}
384
385void ClientProxy::binderDied()
386{
387 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700388 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900389 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800390 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700391 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
392 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800393 }
394}
395
396void ClientProxy::interrupt()
397{
398 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700399 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900400 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700401 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
402 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800403 }
404}
405
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700406__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800407size_t ClientProxy::getMisalignment()
408{
409 audio_track_cblk_t* cblk = mCblk;
410 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
411 (mFrameCountP2 - 1);
412}
413
414// ---------------------------------------------------------------------------
415
416void AudioTrackClientProxy::flush()
417{
Andy Hung1d3556d2018-03-29 16:30:14 -0700418 sendStreamingFlushStop(true /* flush */);
419}
420
421void AudioTrackClientProxy::stop()
422{
423 sendStreamingFlushStop(false /* flush */);
424}
425
426// Sets the client-written mFlush and mStop positions, which control server behavior.
427//
428// @param flush indicates whether the operation is a flush or stop.
429// A client stop sets mStop to the current write position;
430// the server will not read past this point until start() or subsequent flush().
431// A client flush sets both mStop and mFlush to the current write position.
432// This advances the server read limit (if previously set) and on the next
433// server read advances the server read position to this limit.
434//
435void AudioTrackClientProxy::sendStreamingFlushStop(bool flush)
436{
437 // TODO: Replace this by 64 bit counters - avoids wrap complication.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700438 // This works for mFrameCountP2 <= 2^30
Andy Hunga2d75cd2015-07-15 17:04:20 -0700439 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
440 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
441 // if you want to flush twice to the same rear location after a 32 bit wrap.
Andy Hung1d3556d2018-03-29 16:30:14 -0700442
443 const size_t increment = mFrameCountP2 << 1;
444 const size_t mask = increment - 1;
445 // No need for client atomic synchronization on mRear, mStop, mFlush
446 // as AudioTrack client only read/writes to them under client lock. Server only reads.
447 const int32_t rearMasked = mCblk->u.mStreaming.mRear & mask;
448
449 // update stop before flush so that the server front
450 // never advances beyond a (potential) previous stop's rear limit.
451 int32_t stopBits; // the following add can overflow
452 __builtin_add_overflow(mCblk->u.mStreaming.mStop & ~mask, increment, &stopBits);
453 android_atomic_release_store(rearMasked | stopBits, &mCblk->u.mStreaming.mStop);
454
455 if (flush) {
456 int32_t flushBits; // the following add can overflow
457 __builtin_add_overflow(mCblk->u.mStreaming.mFlush & ~mask, increment, &flushBits);
458 android_atomic_release_store(rearMasked | flushBits, &mCblk->u.mStreaming.mFlush);
459 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800460}
461
Eric Laurentbfb1b832013-01-07 09:53:42 -0800462bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700463 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800464}
465
466bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700467 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800468}
469
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100470status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
471{
472 struct timespec total; // total elapsed time spent waiting
473 total.tv_sec = 0;
474 total.tv_nsec = 0;
475 audio_track_cblk_t* cblk = mCblk;
476 status_t status;
477 enum {
478 TIMEOUT_ZERO, // requested == NULL || *requested == 0
479 TIMEOUT_INFINITE, // *requested == infinity
480 TIMEOUT_FINITE, // 0 < *requested < infinity
481 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
482 } timeout;
483 if (requested == NULL) {
484 timeout = TIMEOUT_ZERO;
485 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
486 timeout = TIMEOUT_ZERO;
487 } else if (requested->tv_sec == INT_MAX) {
488 timeout = TIMEOUT_INFINITE;
489 } else {
490 timeout = TIMEOUT_FINITE;
491 }
492 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700493 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100494 // check for track invalidation by server, or server death detection
495 if (flags & CBLK_INVALID) {
496 ALOGV("Track invalidated");
497 status = DEAD_OBJECT;
498 goto end;
499 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800500 // a track is not supposed to underrun at this stage but consider it done
501 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100502 ALOGV("stream end received");
503 status = NO_ERROR;
504 goto end;
505 }
506 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100507 if (flags & CBLK_INTERRUPT) {
508 ALOGV("waitStreamEndDone() interrupted by client");
509 status = -EINTR;
510 goto end;
511 }
512 struct timespec remaining;
513 const struct timespec *ts;
514 switch (timeout) {
515 case TIMEOUT_ZERO:
516 status = WOULD_BLOCK;
517 goto end;
518 case TIMEOUT_INFINITE:
519 ts = NULL;
520 break;
521 case TIMEOUT_FINITE:
522 timeout = TIMEOUT_CONTINUE;
523 if (MAX_SEC == 0) {
524 ts = requested;
525 break;
526 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -0700527 FALLTHROUGH_INTENDED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100528 case TIMEOUT_CONTINUE:
529 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
530 if (requested->tv_sec < total.tv_sec ||
531 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
532 status = TIMED_OUT;
533 goto end;
534 }
535 remaining.tv_sec = requested->tv_sec - total.tv_sec;
536 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
537 remaining.tv_nsec += 1000000000;
538 remaining.tv_sec++;
539 }
540 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
541 remaining.tv_sec = MAX_SEC;
542 remaining.tv_nsec = 0;
543 }
544 ts = &remaining;
545 break;
546 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800547 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100548 ts = NULL;
549 break;
550 }
551 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
552 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700553 errno = 0;
554 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100555 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700556 switch (errno) {
557 case 0: // normal wakeup by server, or by binderDied()
558 case EWOULDBLOCK: // benign race condition with server
559 case EINTR: // wait was interrupted by signal or other spurious wakeup
560 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100561 break;
562 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700563 status = errno;
564 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100565 goto end;
566 }
567 }
568 }
569
570end:
571 if (requested == NULL) {
572 requested = &kNonBlocking;
573 }
574 return status;
575}
576
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800577// ---------------------------------------------------------------------------
578
579StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
580 size_t frameCount, size_t frameSize)
581 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800582 mMutator(&cblk->u.mStatic.mSingleStateQueue),
583 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800584{
Andy Hung9b461582014-12-01 17:56:29 -0800585 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800586 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587}
588
589void StaticAudioTrackClientProxy::flush()
590{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800591 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800592}
593
Andy Hung1d3556d2018-03-29 16:30:14 -0700594void StaticAudioTrackClientProxy::stop()
595{
596 ; // no special handling required for static tracks.
597}
598
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800599void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
600{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800601 // This can only happen on a 64-bit client
602 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
603 // FIXME Should return an error status
604 return;
605 }
Andy Hung9b461582014-12-01 17:56:29 -0800606 mState.mLoopStart = (uint32_t) loopStart;
607 mState.mLoopEnd = (uint32_t) loopEnd;
608 mState.mLoopCount = loopCount;
609 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
610 // set patch-up variables until the mState is acknowledged by the ServerProxy.
611 // observed buffer position and loop count will freeze until then to give the
612 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800613 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800614 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800615 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
616 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800617 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800618 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800619 (void) mMutator.push(mState);
620}
621
622void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
623{
624 // This can only happen on a 64-bit client
625 if (position > UINT32_MAX) {
626 // FIXME Should return an error status
627 return;
628 }
629 mState.mPosition = (uint32_t) position;
630 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800631 // set patch-up variables until the mState is acknowledged by the ServerProxy.
632 // observed buffer position and loop count will freeze until then to give the
633 // illusion of a synchronous change.
634 if (mState.mLoopCount > 0) { // only check if loop count is changing
635 getBufferPositionAndLoopCount(NULL, NULL); // get last position
636 }
637 mPosLoop.mBufferPosition = position;
638 if (position >= mState.mLoopEnd) {
639 // no ongoing loop is possible if position is greater than loopEnd.
640 mPosLoop.mLoopCount = 0;
641 }
Andy Hung9b461582014-12-01 17:56:29 -0800642 (void) mMutator.push(mState);
643}
644
645void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
646 size_t loopEnd, int loopCount)
647{
648 setLoop(loopStart, loopEnd, loopCount);
649 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800650}
651
652size_t StaticAudioTrackClientProxy::getBufferPosition()
653{
Andy Hung4ede21d2014-12-12 15:37:34 -0800654 getBufferPositionAndLoopCount(NULL, NULL);
655 return mPosLoop.mBufferPosition;
656}
657
658void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
659 size_t *position, int *loopCount)
660{
661 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
662 if (mPosLoopObserver.poll(mPosLoop)) {
663 ; // a valid mPosLoop should be available if ackDone is true.
664 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800665 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800666 if (position != NULL) {
667 *position = mPosLoop.mBufferPosition;
668 }
669 if (loopCount != NULL) {
670 *loopCount = mPosLoop.mLoopCount;
671 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800672}
673
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800674// ---------------------------------------------------------------------------
675
676ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
677 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700678 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hungea2b9c02016-02-12 17:06:53 -0800679 mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800680 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800681{
Phil Burke8972b02016-03-04 11:29:57 -0800682 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800683}
684
ilewis926b82f2016-03-29 14:50:36 -0700685__attribute__((no_sanitize("integer")))
Phil Burk4bb650b2016-09-09 12:11:17 -0700686void ServerProxy::flushBufferIfNeeded()
687{
688 audio_track_cblk_t* cblk = mCblk;
689 // The acquire_load is not really required. But since the write is a release_store in the
690 // client, using acquire_load here makes it easier for people to maintain the code,
691 // and the logic for communicating ipc variables seems somewhat standard,
692 // and there really isn't much penalty for 4 or 8 byte atomics.
693 int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
694 if (flush != mFlush) {
695 ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
696 flush, mFlush);
Andy Hung1d3556d2018-03-29 16:30:14 -0700697 // shouldn't matter, but for range safety use mRear instead of getRear().
Phil Burk4bb650b2016-09-09 12:11:17 -0700698 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
699 int32_t front = cblk->u.mStreaming.mFront;
700
701 // effectively obtain then release whatever is in the buffer
702 const size_t overflowBit = mFrameCountP2 << 1;
703 const size_t mask = overflowBit - 1;
704 int32_t newFront = (front & ~mask) | (flush & mask);
Andy Hung99e9db72018-09-14 15:17:36 -0700705 ssize_t filled = safe_sub_overflow(rear, newFront);
Phil Burk4bb650b2016-09-09 12:11:17 -0700706 if (filled >= (ssize_t)overflowBit) {
707 // front and rear offsets span the overflow bit of the p2 mask
708 // so rebasing newFront on the front offset is off by the overflow bit.
709 // adjust newFront to match rear offset.
710 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
711 newFront += overflowBit;
712 filled -= overflowBit;
713 }
714 // Rather than shutting down on a corrupt flush, just treat it as a full flush
715 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
716 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
717 "filled %zd=%#x",
718 mFlush, flush, front, rear,
719 (unsigned)mask, newFront, filled, (unsigned)filled);
720 newFront = rear;
721 }
722 mFlush = flush;
723 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
724 // There is no danger from a false positive, so err on the side of caution
725 if (true /*front != newFront*/) {
726 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
727 if (!(old & CBLK_FUTEX_WAKE)) {
728 (void) syscall(__NR_futex, &cblk->mFutex,
729 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
730 }
731 }
732 mFlushed += (newFront - front) & mask;
733 }
734}
735
736__attribute__((no_sanitize("integer")))
Andy Hung1d3556d2018-03-29 16:30:14 -0700737int32_t AudioTrackServerProxy::getRear() const
738{
739 const int32_t stop = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
740 const int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
741 const int32_t stopLast = mStopLast.load(std::memory_order_acquire);
742 if (stop != stopLast) {
743 const int32_t front = mCblk->u.mStreaming.mFront;
744 const size_t overflowBit = mFrameCountP2 << 1;
745 const size_t mask = overflowBit - 1;
746 int32_t newRear = (rear & ~mask) | (stop & mask);
Andy Hung99e9db72018-09-14 15:17:36 -0700747 ssize_t filled = safe_sub_overflow(newRear, front);
Andy Hung54274032018-04-19 18:16:44 -0700748 // overflowBit is unsigned, so cast to signed for comparison.
749 if (filled >= (ssize_t)overflowBit) {
Andy Hung1d3556d2018-03-29 16:30:14 -0700750 // front and rear offsets span the overflow bit of the p2 mask
Andy Hung54274032018-04-19 18:16:44 -0700751 // so rebasing newRear on the rear offset is off by the overflow bit.
Andy Hung1d3556d2018-03-29 16:30:14 -0700752 ALOGV("stop wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hung54274032018-04-19 18:16:44 -0700753 newRear -= overflowBit;
754 filled -= overflowBit;
Andy Hung1d3556d2018-03-29 16:30:14 -0700755 }
756 if (0 <= filled && (size_t) filled <= mFrameCount) {
757 // we're stopped, return the stop level as newRear
758 return newRear;
759 }
760
761 // A corrupt stop. Log error and ignore.
762 ALOGE("mStopLast %#x -> stop %#x, front %#x, rear %#x, mask %#x, newRear %#x, "
763 "filled %zd=%#x",
764 stopLast, stop, front, rear,
765 (unsigned)mask, newRear, filled, (unsigned)filled);
766 // Don't reset mStopLast as this is const.
767 }
768 return rear;
769}
770
771void AudioTrackServerProxy::start()
772{
773 mStopLast = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
774}
775
776__attribute__((no_sanitize("integer")))
Glenn Kasten2e422c42013-10-18 13:00:29 -0700777status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800778{
Andy Hung9c64f342017-08-02 18:10:00 -0700779 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
780 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800781 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700782 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800783 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700784 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800785 audio_track_cblk_t* cblk = mCblk;
786 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
787 // or use previous cached value from framesReady(), with added barrier if it omits.
788 int32_t front;
789 int32_t rear;
790 // See notes on barriers at ClientProxy::obtainBuffer()
791 if (mIsOut) {
Phil Burk4bb650b2016-09-09 12:11:17 -0700792 flushBufferIfNeeded(); // might modify mFront
Andy Hung1d3556d2018-03-29 16:30:14 -0700793 rear = getRear();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100794 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800795 } else {
796 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
797 rear = cblk->u.mStreaming.mRear;
798 }
Andy Hung99e9db72018-09-14 15:17:36 -0700799 ssize_t filled = safe_sub_overflow(rear, front);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800800 // pipe should not already be overfull
801 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800802 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
803 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800804 mIsShutdown = true;
805 }
806 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700807 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 }
809 // don't allow filling pipe beyond the nominal size
810 size_t availToServer;
811 if (mIsOut) {
812 availToServer = filled;
813 mAvailToClient = mFrameCount - filled;
814 } else {
815 availToServer = mFrameCount - filled;
816 mAvailToClient = filled;
817 }
818 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
819 size_t part1;
820 if (mIsOut) {
821 front &= mFrameCountP2 - 1;
822 part1 = mFrameCountP2 - front;
823 } else {
824 rear &= mFrameCountP2 - 1;
825 part1 = mFrameCountP2 - rear;
826 }
827 if (part1 > availToServer) {
828 part1 = availToServer;
829 }
830 size_t ask = buffer->mFrameCount;
831 if (part1 > ask) {
832 part1 = ask;
833 }
834 // is assignment redundant in some cases?
835 buffer->mFrameCount = part1;
836 buffer->mRaw = part1 > 0 ?
837 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
838 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700839 // After flush(), allow releaseBuffer() on a previously obtained buffer;
840 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
841 if (!ackFlush) {
842 mUnreleased = part1;
843 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800844 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700845 }
846no_init:
847 buffer->mFrameCount = 0;
848 buffer->mRaw = NULL;
849 buffer->mNonContig = 0;
850 mUnreleased = 0;
851 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800852}
853
ilewis926b82f2016-03-29 14:50:36 -0700854__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800855void ServerProxy::releaseBuffer(Buffer* buffer)
856{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700857 LOG_ALWAYS_FATAL_IF(buffer == NULL);
858 size_t stepCount = buffer->mFrameCount;
859 if (stepCount == 0 || mIsShutdown) {
860 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800861 buffer->mFrameCount = 0;
862 buffer->mRaw = NULL;
863 buffer->mNonContig = 0;
864 return;
865 }
Andy Hung9c64f342017-08-02 18:10:00 -0700866 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
867 "%s: mUnreleased out of range, "
868 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu)",
869 __func__, stepCount, mUnreleased, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800870 mUnreleased -= stepCount;
871 audio_track_cblk_t* cblk = mCblk;
872 if (mIsOut) {
873 int32_t front = cblk->u.mStreaming.mFront;
874 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
875 } else {
876 int32_t rear = cblk->u.mStreaming.mRear;
877 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
878 }
879
Glenn Kasten844f88c2014-05-09 13:38:09 -0700880 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800881 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882
883 size_t half = mFrameCount / 2;
884 if (half == 0) {
885 half = 1;
886 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800887 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800888 if (minimum == 0) {
889 minimum = mIsOut ? half : 1;
890 } else if (minimum > half) {
891 minimum = half;
892 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700893 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700894 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700895 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700896 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
897 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700898 (void) syscall(__NR_futex, &cblk->mFutex,
899 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800900 }
901 }
902
903 buffer->mFrameCount = 0;
904 buffer->mRaw = NULL;
905 buffer->mNonContig = 0;
906}
907
908// ---------------------------------------------------------------------------
909
ilewis926b82f2016-03-29 14:50:36 -0700910__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800911size_t AudioTrackServerProxy::framesReady()
912{
913 LOG_ALWAYS_FATAL_IF(!mIsOut);
914
915 if (mIsShutdown) {
916 return 0;
917 }
918 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100919
920 int32_t flush = cblk->u.mStreaming.mFlush;
921 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700922 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100923 return mFrameCount;
924 }
Andy Hung1d3556d2018-03-29 16:30:14 -0700925 const int32_t rear = getRear();
Andy Hung99e9db72018-09-14 15:17:36 -0700926 ssize_t filled = safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800927 // pipe should not already be overfull
928 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800929 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
930 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800931 mIsShutdown = true;
932 return 0;
933 }
934 // cache this value for later use by obtainBuffer(), with added barrier
935 // and racy if called by normal mixer thread
936 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
937 return filled;
938}
939
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700940__attribute__((no_sanitize("integer")))
941size_t AudioTrackServerProxy::framesReadySafe() const
942{
943 if (mIsShutdown) {
944 return 0;
945 }
946 const audio_track_cblk_t* cblk = mCblk;
947 const int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
948 if (flush != mFlush) {
949 return mFrameCount;
950 }
Andy Hung1d3556d2018-03-29 16:30:14 -0700951 const int32_t rear = getRear();
Andy Hung99e9db72018-09-14 15:17:36 -0700952 const ssize_t filled = safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700953 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
954 return 0; // error condition, silently return 0.
955 }
956 return filled;
957}
958
Eric Laurentbfb1b832013-01-07 09:53:42 -0800959bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700960 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800961 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700962 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800963 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700964 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700965 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800966 }
967 return old;
968}
969
Andy Hungd4ee4db2017-07-12 15:26:04 -0700970__attribute__((no_sanitize("integer")))
Glenn Kasten82aaf942013-07-17 16:05:07 -0700971void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
972{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700973 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800974 if (frameCount > 0) {
975 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700976
Phil Burk2812d9e2016-01-04 10:34:30 -0800977 if (!mUnderrunning) { // start of underrun?
978 mUnderrunCount++;
979 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
980 mUnderrunning = true;
981 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
982 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
983 }
984
985 // FIXME also wake futex so that underrun is noticed more quickly
986 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
987 } else {
988 ALOGV_IF(mUnderrunning,
989 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
990 frameCount, cblk->u.mStreaming.mUnderrunFrames);
991 mUnderrunning = false; // so we can detect the next edge
992 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700993}
994
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700995AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700996{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700997 mPlaybackRateObserver.poll(mPlaybackRate);
998 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700999}
1000
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001001// ---------------------------------------------------------------------------
1002
1003StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
1004 size_t frameCount, size_t frameSize)
1005 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -08001006 mObserver(&cblk->u.mStatic.mSingleStateQueue),
1007 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -08001008 mFramesReadySafe(frameCount), mFramesReady(frameCount),
1009 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001010{
Andy Hung9b461582014-12-01 17:56:29 -08001011 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001012}
1013
1014void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
1015{
1016 mFramesReadyIsCalledByMultipleThreads = true;
1017}
1018
1019size_t StaticAudioTrackServerProxy::framesReady()
1020{
Andy Hungcb2129b2014-11-11 12:17:22 -08001021 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001022 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001023 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001024 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001025 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026}
1027
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001028size_t StaticAudioTrackServerProxy::framesReadySafe() const
1029{
1030 return mFramesReadySafe;
1031}
1032
Andy Hung9b461582014-12-01 17:56:29 -08001033status_t StaticAudioTrackServerProxy::updateStateWithLoop(
1034 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001035{
Andy Hung9b461582014-12-01 17:56:29 -08001036 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001037 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -08001038 const size_t loopStart = update.mLoopStart;
1039 const size_t loopEnd = update.mLoopEnd;
1040 size_t position = localState->mPosition;
1041 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001042 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -08001043 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001044 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
1045 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -08001046 // If the current position is greater than the end of the loop
1047 // we "wrap" to the loop start. This might cause an audible pop.
1048 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -08001049 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001050 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001051 valid = true;
1052 }
1053 }
Andy Hung9b461582014-12-01 17:56:29 -08001054 if (!valid || position > mFrameCount) {
1055 return NO_INIT;
1056 }
1057 localState->mPosition = position;
1058 localState->mLoopCount = update.mLoopCount;
1059 localState->mLoopEnd = loopEnd;
1060 localState->mLoopStart = loopStart;
1061 localState->mLoopSequence = update.mLoopSequence;
1062 }
1063 return OK;
1064}
1065
1066status_t StaticAudioTrackServerProxy::updateStateWithPosition(
1067 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1068{
1069 if (localState->mPositionSequence != update.mPositionSequence) {
1070 if (update.mPosition > mFrameCount) {
1071 return NO_INIT;
1072 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
1073 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
1074 }
1075 localState->mPosition = update.mPosition;
1076 localState->mPositionSequence = update.mPositionSequence;
1077 }
1078 return OK;
1079}
1080
1081ssize_t StaticAudioTrackServerProxy::pollPosition()
1082{
1083 StaticAudioTrackState state;
1084 if (mObserver.poll(state)) {
1085 StaticAudioTrackState trystate = mState;
1086 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -07001087 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -08001088
1089 if (diffSeq < 0) {
1090 result = updateStateWithLoop(&trystate, state) == OK &&
1091 updateStateWithPosition(&trystate, state) == OK;
1092 } else {
1093 result = updateStateWithPosition(&trystate, state) == OK &&
1094 updateStateWithLoop(&trystate, state) == OK;
1095 }
1096 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001097 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -08001098 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001099 ALOGE("%s client pushed an invalid state, shutting down", __func__);
1100 mIsShutdown = true;
1101 return (ssize_t) NO_INIT;
1102 }
Andy Hung9b461582014-12-01 17:56:29 -08001103 mState = trystate;
1104 if (mState.mLoopCount == -1) {
1105 mFramesReady = INT64_MAX;
1106 } else if (mState.mLoopCount == 0) {
1107 mFramesReady = mFrameCount - mState.mPosition;
1108 } else if (mState.mLoopCount > 0) {
1109 // TODO: Later consider fixing overflow, but does not seem needed now
1110 // as will not overflow if loopStart and loopEnd are Java "ints".
1111 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
1112 + mFrameCount - mState.mPosition;
1113 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001114 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001115 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001116 StaticAudioTrackPosLoop posLoop;
1117
1118 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
1119 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
1120 mPosLoopMutator.push(posLoop);
1121 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001122 }
Andy Hung9b461582014-12-01 17:56:29 -08001123 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001124}
1125
Andy Hungd4ee4db2017-07-12 15:26:04 -07001126__attribute__((no_sanitize("integer")))
Andy Hung954ca452015-09-09 14:39:02 -07001127status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001128{
1129 if (mIsShutdown) {
1130 buffer->mFrameCount = 0;
1131 buffer->mRaw = NULL;
1132 buffer->mNonContig = 0;
1133 mUnreleased = 0;
1134 return NO_INIT;
1135 }
1136 ssize_t positionOrStatus = pollPosition();
1137 if (positionOrStatus < 0) {
1138 buffer->mFrameCount = 0;
1139 buffer->mRaw = NULL;
1140 buffer->mNonContig = 0;
1141 mUnreleased = 0;
1142 return (status_t) positionOrStatus;
1143 }
1144 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -08001145 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001146 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -08001147 if (position < end) {
1148 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001149 size_t wanted = buffer->mFrameCount;
1150 if (avail < wanted) {
1151 buffer->mFrameCount = avail;
1152 } else {
1153 avail = wanted;
1154 }
1155 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1156 } else {
1157 avail = 0;
1158 buffer->mFrameCount = 0;
1159 buffer->mRaw = NULL;
1160 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001161 // As mFramesReady is the total remaining frames in the static audio track,
1162 // it is always larger or equal to avail.
Andy Hung9c64f342017-08-02 18:10:00 -07001163 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail,
1164 "%s: mFramesReady out of range, mFramesReady:%lld < avail:%zu",
1165 __func__, (long long)mFramesReady, avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001166 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001167 if (!ackFlush) {
1168 mUnreleased = avail;
1169 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001170 return NO_ERROR;
1171}
1172
Andy Hungd4ee4db2017-07-12 15:26:04 -07001173__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001174void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1175{
1176 size_t stepCount = buffer->mFrameCount;
Andy Hung9c64f342017-08-02 18:10:00 -07001177 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady),
1178 "%s: stepCount out of range, "
1179 "!(stepCount:%zu <= mFramesReady:%lld)",
1180 __func__, stepCount, (long long)mFramesReady);
1181 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased),
1182 "%s: stepCount out of range, "
1183 "!(stepCount:%zu <= mUnreleased:%zu)",
1184 __func__, stepCount, mUnreleased);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001185 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001186 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001187 buffer->mRaw = NULL;
1188 buffer->mNonContig = 0;
1189 return;
1190 }
1191 mUnreleased -= stepCount;
1192 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001193 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001194 size_t newPosition = position + stepCount;
1195 int32_t setFlags = 0;
1196 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001197 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1198 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001199 newPosition = mFrameCount;
1200 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001201 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001202 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001203 setFlags = CBLK_LOOP_CYCLE;
1204 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001205 setFlags = CBLK_LOOP_FINAL;
1206 }
1207 }
1208 if (newPosition == mFrameCount) {
1209 setFlags |= CBLK_BUFFER_END;
1210 }
Andy Hung9b461582014-12-01 17:56:29 -08001211 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001212 if (mFramesReady != INT64_MAX) {
1213 mFramesReady -= stepCount;
1214 }
1215 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001216
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001217 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001218 mReleased += stepCount;
1219
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001220 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001221 StaticAudioTrackPosLoop posLoop;
1222 posLoop.mBufferPosition = mState.mPosition;
1223 posLoop.mLoopCount = mState.mLoopCount;
1224 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001225 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001226 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001227 // this would be a good place to wake a futex
1228 }
1229
1230 buffer->mFrameCount = 0;
1231 buffer->mRaw = NULL;
1232 buffer->mNonContig = 0;
1233}
1234
Phil Burk2812d9e2016-01-04 10:34:30 -08001235void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001236{
1237 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1238 // we don't have a location to count underrun frames. The underrun frame counter
1239 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1240 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1241
1242 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001243 if (frameCount > 0) {
1244 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1245 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001246}
1247
Andy Hung1d3556d2018-03-29 16:30:14 -07001248int32_t StaticAudioTrackServerProxy::getRear() const
1249{
1250 LOG_ALWAYS_FATAL("getRear() not permitted for static tracks");
1251 return 0;
1252}
1253
Andy Hung2a4e1612018-06-01 15:06:09 -07001254__attribute__((no_sanitize("integer")))
1255size_t AudioRecordServerProxy::framesReadySafe() const
1256{
1257 if (mIsShutdown) {
1258 return 0;
1259 }
1260 const int32_t front = android_atomic_acquire_load(&mCblk->u.mStreaming.mFront);
1261 const int32_t rear = mCblk->u.mStreaming.mRear;
Andy Hung99e9db72018-09-14 15:17:36 -07001262 const ssize_t filled = safe_sub_overflow(rear, front);
Andy Hung2a4e1612018-06-01 15:06:09 -07001263 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
1264 return 0; // error condition, silently return 0.
1265 }
1266 return filled;
1267}
1268
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001269// ---------------------------------------------------------------------------
1270
Glenn Kastena8190fc2012-12-03 17:06:56 -08001271} // namespace android