blob: 35719be7d004a38158574c53cc5d8ddd7ab34103 [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
Andy Hung63a35832021-03-16 17:30:09 -070020#include <atomic>
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -070021#include <android-base/macros.h>
Glenn Kastena8190fc2012-12-03 17:06:56 -080022#include <private/media/AudioTrackShared.h>
23#include <utils/Log.h>
Hongwei Wang95e37682019-04-12 11:13:36 -070024#include <audio_utils/safe_math.h>
Elliott Hughesee499292014-05-21 17:55:51 -070025
26#include <linux/futex.h>
27#include <sys/syscall.h>
Glenn Kastena8190fc2012-12-03 17:06:56 -080028
29namespace android {
30
Andy Hungcb2129b2014-11-11 12:17:22 -080031// used to clamp a value to size_t. TODO: move to another file.
32template <typename T>
33size_t clampToSize(T x) {
Andy Hung486a7132014-12-22 16:54:21 -080034 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 -080035}
36
Andy Hung63a35832021-03-16 17:30:09 -070037// compile-time safe atomics. TODO: update all methods to use it
38template <typename T>
39T android_atomic_load(const volatile T* addr) {
40 static_assert(sizeof(T) == sizeof(std::atomic<T>)); // no extra sync data required.
41 static_assert(std::atomic<T>::is_always_lock_free); // no hash lock somewhere.
42 return atomic_load((std::atomic<T>*)addr); // memory_order_seq_cst
43}
44
45template <typename T>
46void android_atomic_store(const volatile T* addr, T value) {
47 static_assert(sizeof(T) == sizeof(std::atomic<T>)); // no extra sync data required.
48 static_assert(std::atomic<T>::is_always_lock_free); // no hash lock somewhere.
49 atomic_store((std::atomic<T>*)addr, value); // memory_order_seq_cst
50}
51
Andy Hung9b461582014-12-01 17:56:29 -080052// incrementSequence is used to determine the next sequence value
53// for the loop and position sequence counters. It should return
54// a value between "other" + 1 and "other" + INT32_MAX, the choice of
55// which needs to be the "least recently used" sequence value for "self".
56// In general, this means (new_self) returned is max(self, other) + 1.
Andy Hungd4ee4db2017-07-12 15:26:04 -070057__attribute__((no_sanitize("integer")))
Andy Hung9b461582014-12-01 17:56:29 -080058static uint32_t incrementSequence(uint32_t self, uint32_t other) {
Chad Brubakercb50c542015-10-07 14:20:10 -070059 int32_t diff = (int32_t) self - (int32_t) other;
Andy Hung9b461582014-12-01 17:56:29 -080060 if (diff >= 0 && diff < INT32_MAX) {
61 return self + 1; // we're already ahead of other.
62 }
63 return other + 1; // we're behind, so move just ahead of other.
64}
65
Glenn Kastena8190fc2012-12-03 17:06:56 -080066audio_track_cblk_t::audio_track_cblk_t()
Phil Burke8972b02016-03-04 11:29:57 -080067 : mServer(0), mFutex(0), mMinimum(0)
68 , mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0)
69 , mBufferSizeInFrames(0)
Andy Hung63a35832021-03-16 17:30:09 -070070 , mStartThresholdInFrames(0) // filled in by the server.
Phil Burke8972b02016-03-04 11:29:57 -080071 , 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
Andy Hung63a35832021-03-16 17:30:09 -070086uint32_t Proxy::getStartThresholdInFrames() const
87{
88 const uint32_t startThresholdInFrames =
89 android_atomic_load(&mCblk->mStartThresholdInFrames);
90 if (startThresholdInFrames == 0 || startThresholdInFrames > mFrameCount) {
91 ALOGD("%s: startThresholdInFrames %u not between 1 and frameCount %zu, "
92 "setting to frameCount",
93 __func__, startThresholdInFrames, mFrameCount);
94 return mFrameCount;
95 }
96 return startThresholdInFrames;
97}
98
99uint32_t Proxy::setStartThresholdInFrames(uint32_t startThresholdInFrames)
100{
101 const uint32_t actual = std::min((size_t)startThresholdInFrames, frameCount());
102 android_atomic_store(&mCblk->mStartThresholdInFrames, actual);
103 return actual;
104}
105
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800106// ---------------------------------------------------------------------------
107
108ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
109 size_t frameSize, bool isOut, bool clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -0800110 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -0800111 , mEpoch(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800112 , mTimestampObserver(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800113{
Phil Burke8972b02016-03-04 11:29:57 -0800114 setBufferSizeInFrames(frameCount);
Glenn Kastena8190fc2012-12-03 17:06:56 -0800115}
116
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800117const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
118const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
119
120#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
121
122// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
123// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
124// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
125// order of minutes.
126#define MAX_SEC 5
127
Phil Burke8972b02016-03-04 11:29:57 -0800128uint32_t ClientProxy::setBufferSizeInFrames(uint32_t size)
129{
Phil Burke8972b02016-03-04 11:29:57 -0800130 // The minimum should be greater than zero and less than the size
131 // at which underruns will occur.
Phil Burk26760d12016-03-21 11:53:07 -0700132 const uint32_t minimum = 16; // based on AudioMixer::BLOCKSIZE
Phil Burke8972b02016-03-04 11:29:57 -0800133 const uint32_t maximum = frameCount();
134 uint32_t clippedSize = size;
Phil Burk26760d12016-03-21 11:53:07 -0700135 if (maximum < minimum) {
136 clippedSize = maximum;
137 } else if (clippedSize < minimum) {
Phil Burke8972b02016-03-04 11:29:57 -0800138 clippedSize = minimum;
139 } else if (clippedSize > maximum) {
140 clippedSize = maximum;
141 }
142 // for server to read
143 android_atomic_release_store(clippedSize, (int32_t *)&mCblk->mBufferSizeInFrames);
144 // for client to read
145 mBufferSizeInFrames = clippedSize;
146 return clippedSize;
147}
148
ilewis926b82f2016-03-29 14:50:36 -0700149__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800150status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
151 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800152{
Andy Hung9c64f342017-08-02 18:10:00 -0700153 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
154 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800155 struct timespec total; // total elapsed time spent waiting
156 total.tv_sec = 0;
157 total.tv_nsec = 0;
158 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -0800159
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800160 status_t status;
161 enum {
162 TIMEOUT_ZERO, // requested == NULL || *requested == 0
163 TIMEOUT_INFINITE, // *requested == infinity
164 TIMEOUT_FINITE, // 0 < *requested < infinity
165 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
166 } timeout;
167 if (requested == NULL) {
168 timeout = TIMEOUT_ZERO;
169 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
170 timeout = TIMEOUT_ZERO;
171 } else if (requested->tv_sec == INT_MAX) {
172 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800173 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174 timeout = TIMEOUT_FINITE;
175 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
176 measure = true;
177 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800178 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800179 struct timespec before;
180 bool beforeIsValid = false;
181 audio_track_cblk_t* cblk = mCblk;
182 bool ignoreInitialPendingInterrupt = true;
183 // check for shared memory corruption
184 if (mIsShutdown) {
185 status = NO_INIT;
186 goto end;
187 }
188 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700189 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800190 // check for track invalidation by server, or server death detection
191 if (flags & CBLK_INVALID) {
192 ALOGV("Track invalidated");
193 status = DEAD_OBJECT;
194 goto end;
195 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800196 if (flags & CBLK_DISABLED) {
197 ALOGV("Track disabled");
198 status = NOT_ENOUGH_DATA;
199 goto end;
200 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800201 // check for obtainBuffer interrupted by client
202 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
203 ALOGV("obtainBuffer() interrupted by client");
204 status = -EINTR;
205 goto end;
206 }
207 ignoreInitialPendingInterrupt = false;
208 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
209 int32_t front;
210 int32_t rear;
211 if (mIsOut) {
212 // The barrier following the read of mFront is probably redundant.
213 // We're about to perform a conditional branch based on 'filled',
214 // which will force the processor to observe the read of mFront
215 // prior to allowing data writes starting at mRaw.
216 // However, the processor may support speculative execution,
217 // and be unable to undo speculative writes into shared memory.
218 // The barrier will prevent such speculative execution.
219 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
220 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800221 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800222 // On the other hand, this barrier is required.
223 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
224 front = cblk->u.mStreaming.mFront;
225 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800226 // write to rear, read from front
Hongwei Wang95e37682019-04-12 11:13:36 -0700227 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800228 // pipe should not be overfull
229 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700230 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700231 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700232 "shutting down", filled, mFrameCount);
233 mIsShutdown = true;
234 status = NO_INIT;
235 goto end;
236 }
237 // for input, sync up on overrun
238 filled = 0;
239 cblk->u.mStreaming.mFront = rear;
240 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800241 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800242 // Don't allow filling pipe beyond the user settable size.
243 // The calculation for avail can go negative if the buffer size
244 // is suddenly dropped below the amount already in the buffer.
245 // So use a signed calculation to prevent a numeric overflow abort.
Phil Burke8972b02016-03-04 11:29:57 -0800246 ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800247 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
248 if (avail < 0) {
249 avail = 0;
250 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800251 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800252 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800253 if (mIsOut) {
254 rear &= mFrameCountP2 - 1;
255 part1 = mFrameCountP2 - rear;
256 } else {
257 front &= mFrameCountP2 - 1;
258 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800259 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800260 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800261 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800262 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800263 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800264 part1 = buffer->mFrameCount;
265 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800266 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800267 buffer->mRaw = part1 > 0 ?
268 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
269 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700270 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800271 status = NO_ERROR;
272 break;
273 }
274 struct timespec remaining;
275 const struct timespec *ts;
276 switch (timeout) {
277 case TIMEOUT_ZERO:
278 status = WOULD_BLOCK;
279 goto end;
280 case TIMEOUT_INFINITE:
281 ts = NULL;
282 break;
283 case TIMEOUT_FINITE:
284 timeout = TIMEOUT_CONTINUE;
285 if (MAX_SEC == 0) {
286 ts = requested;
287 break;
288 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -0700289 FALLTHROUGH_INTENDED;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800290 case TIMEOUT_CONTINUE:
291 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
292 if (!measure || requested->tv_sec < total.tv_sec ||
293 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
294 status = TIMED_OUT;
295 goto end;
296 }
297 remaining.tv_sec = requested->tv_sec - total.tv_sec;
298 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
299 remaining.tv_nsec += 1000000000;
300 remaining.tv_sec++;
301 }
302 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
303 remaining.tv_sec = MAX_SEC;
304 remaining.tv_nsec = 0;
305 }
306 ts = &remaining;
307 break;
308 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800309 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800310 ts = NULL;
311 break;
312 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700313 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
314 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800315 if (measure && !beforeIsValid) {
316 clock_gettime(CLOCK_MONOTONIC, &before);
317 beforeIsValid = true;
318 }
Elliott Hughesee499292014-05-21 17:55:51 -0700319 errno = 0;
320 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700321 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800322 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800323 // update total elapsed time spent waiting
324 if (measure) {
325 struct timespec after;
326 clock_gettime(CLOCK_MONOTONIC, &after);
327 total.tv_sec += after.tv_sec - before.tv_sec;
Chih-Hung Hsiehbca74292018-08-10 16:06:07 -0700328 // Use auto instead of long to avoid the google-runtime-int warning.
329 auto deltaNs = after.tv_nsec - before.tv_nsec;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800330 if (deltaNs < 0) {
331 deltaNs += 1000000000;
332 total.tv_sec--;
333 }
334 if ((total.tv_nsec += deltaNs) >= 1000000000) {
335 total.tv_nsec -= 1000000000;
336 total.tv_sec++;
337 }
338 before = after;
339 beforeIsValid = true;
340 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800341 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700342 case 0: // normal wakeup by server, or by binderDied()
343 case EWOULDBLOCK: // benign race condition with server
344 case EINTR: // wait was interrupted by signal or other spurious wakeup
345 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700346 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800347 break;
348 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800349 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700350 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800351 goto end;
352 }
353 }
354 }
355
356end:
357 if (status != NO_ERROR) {
358 buffer->mFrameCount = 0;
359 buffer->mRaw = NULL;
360 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700361 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800362 }
363 if (elapsed != NULL) {
364 *elapsed = total;
365 }
366 if (requested == NULL) {
367 requested = &kNonBlocking;
368 }
369 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100370 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
371 requested->tv_sec, requested->tv_nsec / 1000000,
372 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800373 }
374 return status;
375}
376
ilewis926b82f2016-03-29 14:50:36 -0700377__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800378void ClientProxy::releaseBuffer(Buffer* buffer)
379{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700380 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800381 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700382 if (stepCount == 0 || mIsShutdown) {
383 // prevent accidental re-use of buffer
384 buffer->mFrameCount = 0;
385 buffer->mRaw = NULL;
386 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800387 return;
388 }
Andy Hung9c64f342017-08-02 18:10:00 -0700389 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
390 "%s: mUnreleased out of range, "
391 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu), BufferSizeInFrames:%u",
392 __func__, stepCount, mUnreleased, mFrameCount, getBufferSizeInFrames());
Glenn Kasten7db7df02013-06-25 16:13:23 -0700393 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800394 audio_track_cblk_t* cblk = mCblk;
395 // Both of these barriers are required
396 if (mIsOut) {
397 int32_t rear = cblk->u.mStreaming.mRear;
398 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
399 } else {
400 int32_t front = cblk->u.mStreaming.mFront;
401 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
402 }
403}
404
405void ClientProxy::binderDied()
406{
407 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700408 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900409 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800410 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700411 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
412 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800413 }
414}
415
416void ClientProxy::interrupt()
417{
418 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700419 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900420 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700421 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
422 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800423 }
424}
425
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700426__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800427size_t ClientProxy::getMisalignment()
428{
429 audio_track_cblk_t* cblk = mCblk;
430 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
431 (mFrameCountP2 - 1);
432}
433
434// ---------------------------------------------------------------------------
435
436void AudioTrackClientProxy::flush()
437{
Andy Hung1d3556d2018-03-29 16:30:14 -0700438 sendStreamingFlushStop(true /* flush */);
439}
440
441void AudioTrackClientProxy::stop()
442{
443 sendStreamingFlushStop(false /* flush */);
444}
445
446// Sets the client-written mFlush and mStop positions, which control server behavior.
447//
448// @param flush indicates whether the operation is a flush or stop.
449// A client stop sets mStop to the current write position;
450// the server will not read past this point until start() or subsequent flush().
451// A client flush sets both mStop and mFlush to the current write position.
452// This advances the server read limit (if previously set) and on the next
453// server read advances the server read position to this limit.
454//
455void AudioTrackClientProxy::sendStreamingFlushStop(bool flush)
456{
457 // TODO: Replace this by 64 bit counters - avoids wrap complication.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700458 // This works for mFrameCountP2 <= 2^30
Andy Hunga2d75cd2015-07-15 17:04:20 -0700459 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
460 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
461 // if you want to flush twice to the same rear location after a 32 bit wrap.
Andy Hung1d3556d2018-03-29 16:30:14 -0700462
463 const size_t increment = mFrameCountP2 << 1;
464 const size_t mask = increment - 1;
465 // No need for client atomic synchronization on mRear, mStop, mFlush
466 // as AudioTrack client only read/writes to them under client lock. Server only reads.
467 const int32_t rearMasked = mCblk->u.mStreaming.mRear & mask;
468
469 // update stop before flush so that the server front
470 // never advances beyond a (potential) previous stop's rear limit.
471 int32_t stopBits; // the following add can overflow
472 __builtin_add_overflow(mCblk->u.mStreaming.mStop & ~mask, increment, &stopBits);
473 android_atomic_release_store(rearMasked | stopBits, &mCblk->u.mStreaming.mStop);
474
475 if (flush) {
476 int32_t flushBits; // the following add can overflow
477 __builtin_add_overflow(mCblk->u.mStreaming.mFlush & ~mask, increment, &flushBits);
478 android_atomic_release_store(rearMasked | flushBits, &mCblk->u.mStreaming.mFlush);
479 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800480}
481
Eric Laurentbfb1b832013-01-07 09:53:42 -0800482bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700483 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800484}
485
486bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700487 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800488}
489
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100490status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
491{
492 struct timespec total; // total elapsed time spent waiting
493 total.tv_sec = 0;
494 total.tv_nsec = 0;
495 audio_track_cblk_t* cblk = mCblk;
496 status_t status;
497 enum {
498 TIMEOUT_ZERO, // requested == NULL || *requested == 0
499 TIMEOUT_INFINITE, // *requested == infinity
500 TIMEOUT_FINITE, // 0 < *requested < infinity
501 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
502 } timeout;
503 if (requested == NULL) {
504 timeout = TIMEOUT_ZERO;
505 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
506 timeout = TIMEOUT_ZERO;
507 } else if (requested->tv_sec == INT_MAX) {
508 timeout = TIMEOUT_INFINITE;
509 } else {
510 timeout = TIMEOUT_FINITE;
511 }
512 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700513 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100514 // check for track invalidation by server, or server death detection
515 if (flags & CBLK_INVALID) {
516 ALOGV("Track invalidated");
517 status = DEAD_OBJECT;
518 goto end;
519 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800520 // a track is not supposed to underrun at this stage but consider it done
521 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100522 ALOGV("stream end received");
523 status = NO_ERROR;
524 goto end;
525 }
526 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100527 if (flags & CBLK_INTERRUPT) {
528 ALOGV("waitStreamEndDone() interrupted by client");
529 status = -EINTR;
530 goto end;
531 }
532 struct timespec remaining;
533 const struct timespec *ts;
534 switch (timeout) {
535 case TIMEOUT_ZERO:
536 status = WOULD_BLOCK;
537 goto end;
538 case TIMEOUT_INFINITE:
539 ts = NULL;
540 break;
541 case TIMEOUT_FINITE:
542 timeout = TIMEOUT_CONTINUE;
543 if (MAX_SEC == 0) {
544 ts = requested;
545 break;
546 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -0700547 FALLTHROUGH_INTENDED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100548 case TIMEOUT_CONTINUE:
549 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
550 if (requested->tv_sec < total.tv_sec ||
551 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
552 status = TIMED_OUT;
553 goto end;
554 }
555 remaining.tv_sec = requested->tv_sec - total.tv_sec;
556 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
557 remaining.tv_nsec += 1000000000;
558 remaining.tv_sec++;
559 }
560 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
561 remaining.tv_sec = MAX_SEC;
562 remaining.tv_nsec = 0;
563 }
564 ts = &remaining;
565 break;
566 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800567 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100568 ts = NULL;
569 break;
570 }
571 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
572 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700573 errno = 0;
574 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100575 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700576 switch (errno) {
577 case 0: // normal wakeup by server, or by binderDied()
578 case EWOULDBLOCK: // benign race condition with server
579 case EINTR: // wait was interrupted by signal or other spurious wakeup
580 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100581 break;
582 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700583 status = errno;
584 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100585 goto end;
586 }
587 }
588 }
589
590end:
591 if (requested == NULL) {
592 requested = &kNonBlocking;
593 }
594 return status;
595}
596
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800597// ---------------------------------------------------------------------------
598
599StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
600 size_t frameCount, size_t frameSize)
601 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800602 mMutator(&cblk->u.mStatic.mSingleStateQueue),
603 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604{
Andy Hung9b461582014-12-01 17:56:29 -0800605 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800606 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800607}
608
609void StaticAudioTrackClientProxy::flush()
610{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800611 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800612}
613
Andy Hung1d3556d2018-03-29 16:30:14 -0700614void StaticAudioTrackClientProxy::stop()
615{
616 ; // no special handling required for static tracks.
617}
618
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800619void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
620{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800621 // This can only happen on a 64-bit client
622 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
623 // FIXME Should return an error status
624 return;
625 }
Andy Hung9b461582014-12-01 17:56:29 -0800626 mState.mLoopStart = (uint32_t) loopStart;
627 mState.mLoopEnd = (uint32_t) loopEnd;
628 mState.mLoopCount = loopCount;
629 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
630 // set patch-up variables until the mState is acknowledged by the ServerProxy.
631 // observed buffer position and loop count will freeze until then to give the
632 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800633 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800634 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800635 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
636 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800637 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800638 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800639 (void) mMutator.push(mState);
640}
641
642void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
643{
644 // This can only happen on a 64-bit client
645 if (position > UINT32_MAX) {
646 // FIXME Should return an error status
647 return;
648 }
649 mState.mPosition = (uint32_t) position;
650 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800651 // set patch-up variables until the mState is acknowledged by the ServerProxy.
652 // observed buffer position and loop count will freeze until then to give the
653 // illusion of a synchronous change.
654 if (mState.mLoopCount > 0) { // only check if loop count is changing
655 getBufferPositionAndLoopCount(NULL, NULL); // get last position
656 }
657 mPosLoop.mBufferPosition = position;
658 if (position >= mState.mLoopEnd) {
659 // no ongoing loop is possible if position is greater than loopEnd.
660 mPosLoop.mLoopCount = 0;
661 }
Andy Hung9b461582014-12-01 17:56:29 -0800662 (void) mMutator.push(mState);
663}
664
665void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
666 size_t loopEnd, int loopCount)
667{
668 setLoop(loopStart, loopEnd, loopCount);
669 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800670}
671
672size_t StaticAudioTrackClientProxy::getBufferPosition()
673{
Andy Hung4ede21d2014-12-12 15:37:34 -0800674 getBufferPositionAndLoopCount(NULL, NULL);
675 return mPosLoop.mBufferPosition;
676}
677
678void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
679 size_t *position, int *loopCount)
680{
681 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
682 if (mPosLoopObserver.poll(mPosLoop)) {
683 ; // a valid mPosLoop should be available if ackDone is true.
684 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800685 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800686 if (position != NULL) {
687 *position = mPosLoop.mBufferPosition;
688 }
689 if (loopCount != NULL) {
690 *loopCount = mPosLoop.mLoopCount;
691 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800692}
693
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800694// ---------------------------------------------------------------------------
695
696ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
697 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700698 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hungea2b9c02016-02-12 17:06:53 -0800699 mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800700 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800701{
Phil Burke8972b02016-03-04 11:29:57 -0800702 cblk->mBufferSizeInFrames = frameCount;
Andy Hung63a35832021-03-16 17:30:09 -0700703 cblk->mStartThresholdInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800704}
705
ilewis926b82f2016-03-29 14:50:36 -0700706__attribute__((no_sanitize("integer")))
Phil Burk4bb650b2016-09-09 12:11:17 -0700707void ServerProxy::flushBufferIfNeeded()
708{
709 audio_track_cblk_t* cblk = mCblk;
710 // The acquire_load is not really required. But since the write is a release_store in the
711 // client, using acquire_load here makes it easier for people to maintain the code,
712 // and the logic for communicating ipc variables seems somewhat standard,
713 // and there really isn't much penalty for 4 or 8 byte atomics.
714 int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
715 if (flush != mFlush) {
716 ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
717 flush, mFlush);
Andy Hung1d3556d2018-03-29 16:30:14 -0700718 // shouldn't matter, but for range safety use mRear instead of getRear().
Phil Burk4bb650b2016-09-09 12:11:17 -0700719 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
720 int32_t front = cblk->u.mStreaming.mFront;
721
722 // effectively obtain then release whatever is in the buffer
723 const size_t overflowBit = mFrameCountP2 << 1;
724 const size_t mask = overflowBit - 1;
725 int32_t newFront = (front & ~mask) | (flush & mask);
Hongwei Wang95e37682019-04-12 11:13:36 -0700726 ssize_t filled = audio_utils::safe_sub_overflow(rear, newFront);
Phil Burk4bb650b2016-09-09 12:11:17 -0700727 if (filled >= (ssize_t)overflowBit) {
728 // front and rear offsets span the overflow bit of the p2 mask
729 // so rebasing newFront on the front offset is off by the overflow bit.
730 // adjust newFront to match rear offset.
731 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
732 newFront += overflowBit;
733 filled -= overflowBit;
734 }
735 // Rather than shutting down on a corrupt flush, just treat it as a full flush
736 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
737 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
738 "filled %zd=%#x",
739 mFlush, flush, front, rear,
740 (unsigned)mask, newFront, filled, (unsigned)filled);
741 newFront = rear;
742 }
743 mFlush = flush;
744 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
745 // There is no danger from a false positive, so err on the side of caution
746 if (true /*front != newFront*/) {
747 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
748 if (!(old & CBLK_FUTEX_WAKE)) {
749 (void) syscall(__NR_futex, &cblk->mFutex,
750 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
751 }
752 }
753 mFlushed += (newFront - front) & mask;
754 }
755}
756
757__attribute__((no_sanitize("integer")))
Andy Hung1d3556d2018-03-29 16:30:14 -0700758int32_t AudioTrackServerProxy::getRear() const
759{
760 const int32_t stop = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
761 const int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
762 const int32_t stopLast = mStopLast.load(std::memory_order_acquire);
763 if (stop != stopLast) {
764 const int32_t front = mCblk->u.mStreaming.mFront;
765 const size_t overflowBit = mFrameCountP2 << 1;
766 const size_t mask = overflowBit - 1;
767 int32_t newRear = (rear & ~mask) | (stop & mask);
Hongwei Wang95e37682019-04-12 11:13:36 -0700768 ssize_t filled = audio_utils::safe_sub_overflow(newRear, front);
Andy Hung54274032018-04-19 18:16:44 -0700769 // overflowBit is unsigned, so cast to signed for comparison.
770 if (filled >= (ssize_t)overflowBit) {
Andy Hung1d3556d2018-03-29 16:30:14 -0700771 // front and rear offsets span the overflow bit of the p2 mask
Andy Hung54274032018-04-19 18:16:44 -0700772 // so rebasing newRear on the rear offset is off by the overflow bit.
Andy Hung1d3556d2018-03-29 16:30:14 -0700773 ALOGV("stop wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hung54274032018-04-19 18:16:44 -0700774 newRear -= overflowBit;
775 filled -= overflowBit;
Andy Hung1d3556d2018-03-29 16:30:14 -0700776 }
777 if (0 <= filled && (size_t) filled <= mFrameCount) {
778 // we're stopped, return the stop level as newRear
779 return newRear;
780 }
781
782 // A corrupt stop. Log error and ignore.
783 ALOGE("mStopLast %#x -> stop %#x, front %#x, rear %#x, mask %#x, newRear %#x, "
784 "filled %zd=%#x",
785 stopLast, stop, front, rear,
786 (unsigned)mask, newRear, filled, (unsigned)filled);
787 // Don't reset mStopLast as this is const.
788 }
789 return rear;
790}
791
792void AudioTrackServerProxy::start()
793{
794 mStopLast = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
795}
796
797__attribute__((no_sanitize("integer")))
Glenn Kasten2e422c42013-10-18 13:00:29 -0700798status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800799{
Andy Hung9c64f342017-08-02 18:10:00 -0700800 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
801 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800802 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700803 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800804 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700805 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800806 audio_track_cblk_t* cblk = mCblk;
807 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
808 // or use previous cached value from framesReady(), with added barrier if it omits.
809 int32_t front;
810 int32_t rear;
811 // See notes on barriers at ClientProxy::obtainBuffer()
812 if (mIsOut) {
Phil Burk4bb650b2016-09-09 12:11:17 -0700813 flushBufferIfNeeded(); // might modify mFront
Andy Hung1d3556d2018-03-29 16:30:14 -0700814 rear = getRear();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100815 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800816 } else {
817 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
818 rear = cblk->u.mStreaming.mRear;
819 }
Hongwei Wang95e37682019-04-12 11:13:36 -0700820 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800821 // pipe should not already be overfull
822 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800823 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
824 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800825 mIsShutdown = true;
826 }
827 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700828 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800829 }
830 // don't allow filling pipe beyond the nominal size
831 size_t availToServer;
832 if (mIsOut) {
833 availToServer = filled;
834 mAvailToClient = mFrameCount - filled;
835 } else {
836 availToServer = mFrameCount - filled;
837 mAvailToClient = filled;
838 }
839 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
840 size_t part1;
841 if (mIsOut) {
842 front &= mFrameCountP2 - 1;
843 part1 = mFrameCountP2 - front;
844 } else {
845 rear &= mFrameCountP2 - 1;
846 part1 = mFrameCountP2 - rear;
847 }
848 if (part1 > availToServer) {
849 part1 = availToServer;
850 }
851 size_t ask = buffer->mFrameCount;
852 if (part1 > ask) {
853 part1 = ask;
854 }
855 // is assignment redundant in some cases?
856 buffer->mFrameCount = part1;
857 buffer->mRaw = part1 > 0 ?
858 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
859 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700860 // After flush(), allow releaseBuffer() on a previously obtained buffer;
861 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
862 if (!ackFlush) {
863 mUnreleased = part1;
864 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800865 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700866 }
867no_init:
868 buffer->mFrameCount = 0;
869 buffer->mRaw = NULL;
870 buffer->mNonContig = 0;
871 mUnreleased = 0;
872 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800873}
874
ilewis926b82f2016-03-29 14:50:36 -0700875__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800876void ServerProxy::releaseBuffer(Buffer* buffer)
877{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700878 LOG_ALWAYS_FATAL_IF(buffer == NULL);
879 size_t stepCount = buffer->mFrameCount;
880 if (stepCount == 0 || mIsShutdown) {
881 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882 buffer->mFrameCount = 0;
883 buffer->mRaw = NULL;
884 buffer->mNonContig = 0;
885 return;
886 }
Andy Hung9c64f342017-08-02 18:10:00 -0700887 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
888 "%s: mUnreleased out of range, "
889 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu)",
890 __func__, stepCount, mUnreleased, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800891 mUnreleased -= stepCount;
892 audio_track_cblk_t* cblk = mCblk;
893 if (mIsOut) {
894 int32_t front = cblk->u.mStreaming.mFront;
895 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
896 } else {
897 int32_t rear = cblk->u.mStreaming.mRear;
898 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
899 }
900
Glenn Kasten844f88c2014-05-09 13:38:09 -0700901 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800902 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800903
904 size_t half = mFrameCount / 2;
905 if (half == 0) {
906 half = 1;
907 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800908 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800909 if (minimum == 0) {
910 minimum = mIsOut ? half : 1;
911 } else if (minimum > half) {
912 minimum = half;
913 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700914 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700915 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700916 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700917 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
918 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700919 (void) syscall(__NR_futex, &cblk->mFutex,
920 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800921 }
922 }
923
924 buffer->mFrameCount = 0;
925 buffer->mRaw = NULL;
926 buffer->mNonContig = 0;
927}
928
929// ---------------------------------------------------------------------------
930
ilewis926b82f2016-03-29 14:50:36 -0700931__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800932size_t AudioTrackServerProxy::framesReady()
933{
934 LOG_ALWAYS_FATAL_IF(!mIsOut);
935
936 if (mIsShutdown) {
937 return 0;
938 }
939 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100940
Zhou Song8735d0d2020-08-17 15:36:56 +0800941 flushBufferIfNeeded();
942
Andy Hung1d3556d2018-03-29 16:30:14 -0700943 const int32_t rear = getRear();
Hongwei Wang95e37682019-04-12 11:13:36 -0700944 ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800945 // pipe should not already be overfull
946 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800947 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
948 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800949 mIsShutdown = true;
950 return 0;
951 }
952 // cache this value for later use by obtainBuffer(), with added barrier
953 // and racy if called by normal mixer thread
954 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
955 return filled;
956}
957
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700958__attribute__((no_sanitize("integer")))
959size_t AudioTrackServerProxy::framesReadySafe() const
960{
961 if (mIsShutdown) {
962 return 0;
963 }
964 const audio_track_cblk_t* cblk = mCblk;
965 const int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
966 if (flush != mFlush) {
967 return mFrameCount;
968 }
Andy Hung1d3556d2018-03-29 16:30:14 -0700969 const int32_t rear = getRear();
Hongwei Wang95e37682019-04-12 11:13:36 -0700970 const ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700971 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
972 return 0; // error condition, silently return 0.
973 }
974 return filled;
975}
976
Eric Laurentbfb1b832013-01-07 09:53:42 -0800977bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700978 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800979 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700980 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800981 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700982 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700983 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800984 }
985 return old;
986}
987
Andy Hungd4ee4db2017-07-12 15:26:04 -0700988__attribute__((no_sanitize("integer")))
Glenn Kasten82aaf942013-07-17 16:05:07 -0700989void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
990{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700991 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800992 if (frameCount > 0) {
993 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700994
Phil Burk2812d9e2016-01-04 10:34:30 -0800995 if (!mUnderrunning) { // start of underrun?
996 mUnderrunCount++;
997 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
998 mUnderrunning = true;
999 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
1000 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
1001 }
1002
1003 // FIXME also wake futex so that underrun is noticed more quickly
1004 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
1005 } else {
1006 ALOGV_IF(mUnderrunning,
1007 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
1008 frameCount, cblk->u.mStreaming.mUnderrunFrames);
1009 mUnderrunning = false; // so we can detect the next edge
1010 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001011}
1012
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001013AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -07001014{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001015 mPlaybackRateObserver.poll(mPlaybackRate);
1016 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001017}
1018
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001019// ---------------------------------------------------------------------------
1020
1021StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
Kevin Rocard36862032019-10-10 10:52:19 +01001022 size_t frameCount, size_t frameSize, uint32_t sampleRate)
1023 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize, false /*clientInServer*/,
1024 sampleRate),
Andy Hung4ede21d2014-12-12 15:37:34 -08001025 mObserver(&cblk->u.mStatic.mSingleStateQueue),
1026 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -08001027 mFramesReadySafe(frameCount), mFramesReady(frameCount),
1028 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001029{
Andy Hung9b461582014-12-01 17:56:29 -08001030 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001031}
1032
1033void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
1034{
1035 mFramesReadyIsCalledByMultipleThreads = true;
1036}
1037
1038size_t StaticAudioTrackServerProxy::framesReady()
1039{
Andy Hungcb2129b2014-11-11 12:17:22 -08001040 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001041 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001042 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001043 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001044 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001045}
1046
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001047size_t StaticAudioTrackServerProxy::framesReadySafe() const
1048{
1049 return mFramesReadySafe;
1050}
1051
Andy Hung9b461582014-12-01 17:56:29 -08001052status_t StaticAudioTrackServerProxy::updateStateWithLoop(
1053 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001054{
Andy Hung9b461582014-12-01 17:56:29 -08001055 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001056 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -08001057 const size_t loopStart = update.mLoopStart;
1058 const size_t loopEnd = update.mLoopEnd;
1059 size_t position = localState->mPosition;
1060 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001061 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -08001062 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001063 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
1064 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -08001065 // If the current position is greater than the end of the loop
1066 // we "wrap" to the loop start. This might cause an audible pop.
1067 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -08001068 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001069 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001070 valid = true;
1071 }
1072 }
Andy Hung9b461582014-12-01 17:56:29 -08001073 if (!valid || position > mFrameCount) {
1074 return NO_INIT;
1075 }
1076 localState->mPosition = position;
1077 localState->mLoopCount = update.mLoopCount;
1078 localState->mLoopEnd = loopEnd;
1079 localState->mLoopStart = loopStart;
1080 localState->mLoopSequence = update.mLoopSequence;
1081 }
1082 return OK;
1083}
1084
1085status_t StaticAudioTrackServerProxy::updateStateWithPosition(
1086 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1087{
1088 if (localState->mPositionSequence != update.mPositionSequence) {
1089 if (update.mPosition > mFrameCount) {
1090 return NO_INIT;
1091 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
1092 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
1093 }
1094 localState->mPosition = update.mPosition;
1095 localState->mPositionSequence = update.mPositionSequence;
1096 }
1097 return OK;
1098}
1099
1100ssize_t StaticAudioTrackServerProxy::pollPosition()
1101{
1102 StaticAudioTrackState state;
1103 if (mObserver.poll(state)) {
1104 StaticAudioTrackState trystate = mState;
1105 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -07001106 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -08001107
1108 if (diffSeq < 0) {
1109 result = updateStateWithLoop(&trystate, state) == OK &&
1110 updateStateWithPosition(&trystate, state) == OK;
1111 } else {
1112 result = updateStateWithPosition(&trystate, state) == OK &&
1113 updateStateWithLoop(&trystate, state) == OK;
1114 }
1115 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001116 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -08001117 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001118 ALOGE("%s client pushed an invalid state, shutting down", __func__);
1119 mIsShutdown = true;
1120 return (ssize_t) NO_INIT;
1121 }
Andy Hung9b461582014-12-01 17:56:29 -08001122 mState = trystate;
1123 if (mState.mLoopCount == -1) {
1124 mFramesReady = INT64_MAX;
1125 } else if (mState.mLoopCount == 0) {
1126 mFramesReady = mFrameCount - mState.mPosition;
1127 } else if (mState.mLoopCount > 0) {
1128 // TODO: Later consider fixing overflow, but does not seem needed now
1129 // as will not overflow if loopStart and loopEnd are Java "ints".
1130 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
1131 + mFrameCount - mState.mPosition;
1132 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001133 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001134 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001135 StaticAudioTrackPosLoop posLoop;
1136
1137 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
1138 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
1139 mPosLoopMutator.push(posLoop);
1140 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001141 }
Andy Hung9b461582014-12-01 17:56:29 -08001142 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001143}
1144
Andy Hungd4ee4db2017-07-12 15:26:04 -07001145__attribute__((no_sanitize("integer")))
Andy Hung954ca452015-09-09 14:39:02 -07001146status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001147{
1148 if (mIsShutdown) {
1149 buffer->mFrameCount = 0;
1150 buffer->mRaw = NULL;
1151 buffer->mNonContig = 0;
1152 mUnreleased = 0;
1153 return NO_INIT;
1154 }
1155 ssize_t positionOrStatus = pollPosition();
1156 if (positionOrStatus < 0) {
1157 buffer->mFrameCount = 0;
1158 buffer->mRaw = NULL;
1159 buffer->mNonContig = 0;
1160 mUnreleased = 0;
1161 return (status_t) positionOrStatus;
1162 }
1163 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -08001164 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001165 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -08001166 if (position < end) {
1167 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001168 size_t wanted = buffer->mFrameCount;
1169 if (avail < wanted) {
1170 buffer->mFrameCount = avail;
1171 } else {
1172 avail = wanted;
1173 }
1174 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1175 } else {
1176 avail = 0;
1177 buffer->mFrameCount = 0;
1178 buffer->mRaw = NULL;
1179 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001180 // As mFramesReady is the total remaining frames in the static audio track,
1181 // it is always larger or equal to avail.
Andy Hung9c64f342017-08-02 18:10:00 -07001182 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail,
1183 "%s: mFramesReady out of range, mFramesReady:%lld < avail:%zu",
1184 __func__, (long long)mFramesReady, avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001185 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001186 if (!ackFlush) {
1187 mUnreleased = avail;
1188 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001189 return NO_ERROR;
1190}
1191
Andy Hungd4ee4db2017-07-12 15:26:04 -07001192__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001193void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1194{
1195 size_t stepCount = buffer->mFrameCount;
Andy Hung9c64f342017-08-02 18:10:00 -07001196 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady),
1197 "%s: stepCount out of range, "
1198 "!(stepCount:%zu <= mFramesReady:%lld)",
1199 __func__, stepCount, (long long)mFramesReady);
1200 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased),
1201 "%s: stepCount out of range, "
1202 "!(stepCount:%zu <= mUnreleased:%zu)",
1203 __func__, stepCount, mUnreleased);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001204 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001205 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001206 buffer->mRaw = NULL;
1207 buffer->mNonContig = 0;
1208 return;
1209 }
1210 mUnreleased -= stepCount;
1211 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001212 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001213 size_t newPosition = position + stepCount;
1214 int32_t setFlags = 0;
1215 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001216 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1217 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001218 newPosition = mFrameCount;
1219 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001220 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001221 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001222 setFlags = CBLK_LOOP_CYCLE;
1223 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224 setFlags = CBLK_LOOP_FINAL;
1225 }
1226 }
1227 if (newPosition == mFrameCount) {
1228 setFlags |= CBLK_BUFFER_END;
1229 }
Andy Hung9b461582014-12-01 17:56:29 -08001230 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001231 if (mFramesReady != INT64_MAX) {
1232 mFramesReady -= stepCount;
1233 }
1234 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001235
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001236 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001237 mReleased += stepCount;
1238
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001239 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001240 StaticAudioTrackPosLoop posLoop;
1241 posLoop.mBufferPosition = mState.mPosition;
1242 posLoop.mLoopCount = mState.mLoopCount;
1243 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001244 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001245 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001246 // this would be a good place to wake a futex
1247 }
1248
1249 buffer->mFrameCount = 0;
1250 buffer->mRaw = NULL;
1251 buffer->mNonContig = 0;
1252}
1253
Phil Burk2812d9e2016-01-04 10:34:30 -08001254void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001255{
1256 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1257 // we don't have a location to count underrun frames. The underrun frame counter
1258 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1259 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1260
1261 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001262 if (frameCount > 0) {
1263 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1264 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001265}
1266
Andy Hung1d3556d2018-03-29 16:30:14 -07001267int32_t StaticAudioTrackServerProxy::getRear() const
1268{
1269 LOG_ALWAYS_FATAL("getRear() not permitted for static tracks");
1270 return 0;
1271}
1272
Andy Hung2a4e1612018-06-01 15:06:09 -07001273__attribute__((no_sanitize("integer")))
1274size_t AudioRecordServerProxy::framesReadySafe() const
1275{
1276 if (mIsShutdown) {
1277 return 0;
1278 }
1279 const int32_t front = android_atomic_acquire_load(&mCblk->u.mStreaming.mFront);
1280 const int32_t rear = mCblk->u.mStreaming.mRear;
Hongwei Wang95e37682019-04-12 11:13:36 -07001281 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung2a4e1612018-06-01 15:06:09 -07001282 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
1283 return 0; // error condition, silently return 0.
1284 }
1285 return filled;
1286}
1287
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001288// ---------------------------------------------------------------------------
1289
Glenn Kastena8190fc2012-12-03 17:06:56 -08001290} // namespace android