blob: 359f3c1ff21d14970c728ccb43e80bfd5d3e6c92 [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 }
youfa.song5a36f932024-11-20 14:41:20 +0800313
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700314 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
youfa.song5a36f932024-11-20 14:41:20 +0800315
316 // Check inactive to prevent waiting if the track has been disabled due to underrun
317 // (or invalidated). The subsequent call to obtainBufer will return NOT_ENOUGH_DATA
318 // (or DEAD_OBJECT) and restart (or restore) the track.
319 const int32_t current_flags = android_atomic_acquire_load(&cblk->mFlags);
320 const bool inactive = current_flags & (CBLK_INVALID | CBLK_DISABLED);
321
322 if (!(old & CBLK_FUTEX_WAKE) && !inactive) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800323 if (measure && !beforeIsValid) {
324 clock_gettime(CLOCK_MONOTONIC, &before);
325 beforeIsValid = true;
326 }
Elliott Hughesee499292014-05-21 17:55:51 -0700327 errno = 0;
328 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700329 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800330 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800331 // update total elapsed time spent waiting
332 if (measure) {
333 struct timespec after;
334 clock_gettime(CLOCK_MONOTONIC, &after);
335 total.tv_sec += after.tv_sec - before.tv_sec;
Chih-Hung Hsiehbca74292018-08-10 16:06:07 -0700336 // Use auto instead of long to avoid the google-runtime-int warning.
337 auto deltaNs = after.tv_nsec - before.tv_nsec;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800338 if (deltaNs < 0) {
339 deltaNs += 1000000000;
340 total.tv_sec--;
341 }
342 if ((total.tv_nsec += deltaNs) >= 1000000000) {
343 total.tv_nsec -= 1000000000;
344 total.tv_sec++;
345 }
346 before = after;
347 beforeIsValid = true;
348 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800349 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700350 case 0: // normal wakeup by server, or by binderDied()
351 case EWOULDBLOCK: // benign race condition with server
352 case EINTR: // wait was interrupted by signal or other spurious wakeup
353 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700354 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800355 break;
356 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800357 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700358 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800359 goto end;
360 }
361 }
362 }
363
364end:
365 if (status != NO_ERROR) {
366 buffer->mFrameCount = 0;
367 buffer->mRaw = NULL;
368 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700369 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800370 }
371 if (elapsed != NULL) {
372 *elapsed = total;
373 }
374 if (requested == NULL) {
375 requested = &kNonBlocking;
376 }
377 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100378 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
379 requested->tv_sec, requested->tv_nsec / 1000000,
380 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800381 }
382 return status;
383}
384
ilewis926b82f2016-03-29 14:50:36 -0700385__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800386void ClientProxy::releaseBuffer(Buffer* buffer)
387{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700388 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800389 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700390 if (stepCount == 0 || mIsShutdown) {
391 // prevent accidental re-use of buffer
392 buffer->mFrameCount = 0;
393 buffer->mRaw = NULL;
394 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800395 return;
396 }
Andy Hung9c64f342017-08-02 18:10:00 -0700397 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
398 "%s: mUnreleased out of range, "
399 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu), BufferSizeInFrames:%u",
400 __func__, stepCount, mUnreleased, mFrameCount, getBufferSizeInFrames());
Glenn Kasten7db7df02013-06-25 16:13:23 -0700401 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800402 audio_track_cblk_t* cblk = mCblk;
403 // Both of these barriers are required
404 if (mIsOut) {
405 int32_t rear = cblk->u.mStreaming.mRear;
406 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
407 } else {
408 int32_t front = cblk->u.mStreaming.mFront;
409 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
410 }
411}
412
413void ClientProxy::binderDied()
414{
415 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700416 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900417 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800418 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700419 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
zhenjun.zhange2f8b602021-12-07 19:31:05 +0800420 INT_MAX);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800421 }
422}
423
424void ClientProxy::interrupt()
425{
426 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700427 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900428 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700429 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
zhenjun.zhange2f8b602021-12-07 19:31:05 +0800430 INT_MAX);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800431 }
432}
433
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700434__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800435size_t ClientProxy::getMisalignment()
436{
437 audio_track_cblk_t* cblk = mCblk;
438 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
439 (mFrameCountP2 - 1);
440}
441
442// ---------------------------------------------------------------------------
443
444void AudioTrackClientProxy::flush()
445{
Andy Hung1d3556d2018-03-29 16:30:14 -0700446 sendStreamingFlushStop(true /* flush */);
447}
448
449void AudioTrackClientProxy::stop()
450{
451 sendStreamingFlushStop(false /* flush */);
452}
453
454// Sets the client-written mFlush and mStop positions, which control server behavior.
455//
456// @param flush indicates whether the operation is a flush or stop.
457// A client stop sets mStop to the current write position;
458// the server will not read past this point until start() or subsequent flush().
459// A client flush sets both mStop and mFlush to the current write position.
460// This advances the server read limit (if previously set) and on the next
461// server read advances the server read position to this limit.
462//
463void AudioTrackClientProxy::sendStreamingFlushStop(bool flush)
464{
465 // TODO: Replace this by 64 bit counters - avoids wrap complication.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700466 // This works for mFrameCountP2 <= 2^30
Andy Hunga2d75cd2015-07-15 17:04:20 -0700467 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
468 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
469 // if you want to flush twice to the same rear location after a 32 bit wrap.
Andy Hung1d3556d2018-03-29 16:30:14 -0700470
471 const size_t increment = mFrameCountP2 << 1;
472 const size_t mask = increment - 1;
473 // No need for client atomic synchronization on mRear, mStop, mFlush
474 // as AudioTrack client only read/writes to them under client lock. Server only reads.
475 const int32_t rearMasked = mCblk->u.mStreaming.mRear & mask;
476
477 // update stop before flush so that the server front
478 // never advances beyond a (potential) previous stop's rear limit.
479 int32_t stopBits; // the following add can overflow
480 __builtin_add_overflow(mCblk->u.mStreaming.mStop & ~mask, increment, &stopBits);
481 android_atomic_release_store(rearMasked | stopBits, &mCblk->u.mStreaming.mStop);
482
483 if (flush) {
484 int32_t flushBits; // the following add can overflow
485 __builtin_add_overflow(mCblk->u.mStreaming.mFlush & ~mask, increment, &flushBits);
486 android_atomic_release_store(rearMasked | flushBits, &mCblk->u.mStreaming.mFlush);
487 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800488}
489
Eric Laurentbfb1b832013-01-07 09:53:42 -0800490bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700491 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800492}
493
494bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700495 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800496}
497
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100498status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
499{
500 struct timespec total; // total elapsed time spent waiting
Matthew Bouyack7fd95182021-12-20 10:34:39 -0800501 struct timespec before;
502 bool beforeIsValid = false;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100503 total.tv_sec = 0;
504 total.tv_nsec = 0;
505 audio_track_cblk_t* cblk = mCblk;
506 status_t status;
507 enum {
508 TIMEOUT_ZERO, // requested == NULL || *requested == 0
509 TIMEOUT_INFINITE, // *requested == infinity
510 TIMEOUT_FINITE, // 0 < *requested < infinity
511 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
512 } timeout;
513 if (requested == NULL) {
514 timeout = TIMEOUT_ZERO;
515 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
516 timeout = TIMEOUT_ZERO;
517 } else if (requested->tv_sec == INT_MAX) {
518 timeout = TIMEOUT_INFINITE;
519 } else {
520 timeout = TIMEOUT_FINITE;
521 }
522 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700523 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100524 // check for track invalidation by server, or server death detection
525 if (flags & CBLK_INVALID) {
526 ALOGV("Track invalidated");
527 status = DEAD_OBJECT;
528 goto end;
529 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800530 // a track is not supposed to underrun at this stage but consider it done
531 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100532 ALOGV("stream end received");
533 status = NO_ERROR;
534 goto end;
535 }
536 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100537 if (flags & CBLK_INTERRUPT) {
538 ALOGV("waitStreamEndDone() interrupted by client");
539 status = -EINTR;
540 goto end;
541 }
542 struct timespec remaining;
543 const struct timespec *ts;
544 switch (timeout) {
545 case TIMEOUT_ZERO:
546 status = WOULD_BLOCK;
547 goto end;
548 case TIMEOUT_INFINITE:
549 ts = NULL;
550 break;
551 case TIMEOUT_FINITE:
552 timeout = TIMEOUT_CONTINUE;
553 if (MAX_SEC == 0) {
554 ts = requested;
555 break;
556 }
Chih-Hung Hsiehffe35582018-09-13 13:59:28 -0700557 FALLTHROUGH_INTENDED;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100558 case TIMEOUT_CONTINUE:
559 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
560 if (requested->tv_sec < total.tv_sec ||
561 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
562 status = TIMED_OUT;
563 goto end;
564 }
565 remaining.tv_sec = requested->tv_sec - total.tv_sec;
566 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
567 remaining.tv_nsec += 1000000000;
568 remaining.tv_sec++;
569 }
570 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
571 remaining.tv_sec = MAX_SEC;
572 remaining.tv_nsec = 0;
573 }
574 ts = &remaining;
575 break;
576 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800577 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100578 ts = NULL;
579 break;
580 }
581 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
582 if (!(old & CBLK_FUTEX_WAKE)) {
Matthew Bouyack7fd95182021-12-20 10:34:39 -0800583 if (!beforeIsValid) {
584 clock_gettime(CLOCK_MONOTONIC, &before);
585 beforeIsValid = true;
586 }
Elliott Hughesee499292014-05-21 17:55:51 -0700587 errno = 0;
588 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100589 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Matthew Bouyack7fd95182021-12-20 10:34:39 -0800590 status_t error = errno; // clock_gettime can affect errno
591 {
592 struct timespec after;
593 clock_gettime(CLOCK_MONOTONIC, &after);
594 total.tv_sec += after.tv_sec - before.tv_sec;
595 // Use auto instead of long to avoid the google-runtime-int warning.
596 auto deltaNs = after.tv_nsec - before.tv_nsec;
597 if (deltaNs < 0) {
598 deltaNs += 1000000000;
599 total.tv_sec--;
600 }
601 if ((total.tv_nsec += deltaNs) >= 1000000000) {
602 total.tv_nsec -= 1000000000;
603 total.tv_sec++;
604 }
605 before = after;
606 }
607 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700608 case 0: // normal wakeup by server, or by binderDied()
609 case EWOULDBLOCK: // benign race condition with server
610 case EINTR: // wait was interrupted by signal or other spurious wakeup
611 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100612 break;
613 default:
Matthew Bouyack7fd95182021-12-20 10:34:39 -0800614 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700615 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100616 goto end;
617 }
618 }
619 }
620
621end:
622 if (requested == NULL) {
623 requested = &kNonBlocking;
624 }
625 return status;
626}
627
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800628// ---------------------------------------------------------------------------
629
630StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
631 size_t frameCount, size_t frameSize)
632 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800633 mMutator(&cblk->u.mStatic.mSingleStateQueue),
634 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800635{
Andy Hung9b461582014-12-01 17:56:29 -0800636 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800637 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800638}
639
640void StaticAudioTrackClientProxy::flush()
641{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800642 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800643}
644
Andy Hung1d3556d2018-03-29 16:30:14 -0700645void StaticAudioTrackClientProxy::stop()
646{
647 ; // no special handling required for static tracks.
648}
649
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800650void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
651{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800652 // This can only happen on a 64-bit client
653 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
654 // FIXME Should return an error status
655 return;
656 }
Andy Hung9b461582014-12-01 17:56:29 -0800657 mState.mLoopStart = (uint32_t) loopStart;
658 mState.mLoopEnd = (uint32_t) loopEnd;
659 mState.mLoopCount = loopCount;
660 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
661 // set patch-up variables until the mState is acknowledged by the ServerProxy.
662 // observed buffer position and loop count will freeze until then to give the
663 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800664 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800665 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800666 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
667 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800668 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800669 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800670 (void) mMutator.push(mState);
671}
672
673void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
674{
675 // This can only happen on a 64-bit client
676 if (position > UINT32_MAX) {
677 // FIXME Should return an error status
678 return;
679 }
680 mState.mPosition = (uint32_t) position;
681 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800682 // set patch-up variables until the mState is acknowledged by the ServerProxy.
683 // observed buffer position and loop count will freeze until then to give the
684 // illusion of a synchronous change.
685 if (mState.mLoopCount > 0) { // only check if loop count is changing
686 getBufferPositionAndLoopCount(NULL, NULL); // get last position
687 }
688 mPosLoop.mBufferPosition = position;
689 if (position >= mState.mLoopEnd) {
690 // no ongoing loop is possible if position is greater than loopEnd.
691 mPosLoop.mLoopCount = 0;
692 }
Andy Hung9b461582014-12-01 17:56:29 -0800693 (void) mMutator.push(mState);
694}
695
696void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
697 size_t loopEnd, int loopCount)
698{
699 setLoop(loopStart, loopEnd, loopCount);
700 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800701}
702
703size_t StaticAudioTrackClientProxy::getBufferPosition()
704{
Andy Hung4ede21d2014-12-12 15:37:34 -0800705 getBufferPositionAndLoopCount(NULL, NULL);
706 return mPosLoop.mBufferPosition;
707}
708
709void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
710 size_t *position, int *loopCount)
711{
712 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
713 if (mPosLoopObserver.poll(mPosLoop)) {
714 ; // a valid mPosLoop should be available if ackDone is true.
715 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800716 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800717 if (position != NULL) {
718 *position = mPosLoop.mBufferPosition;
719 }
720 if (loopCount != NULL) {
721 *loopCount = mPosLoop.mLoopCount;
722 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800723}
724
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800725// ---------------------------------------------------------------------------
726
727ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
728 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700729 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hungea2b9c02016-02-12 17:06:53 -0800730 mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800731 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800732{
Phil Burke8972b02016-03-04 11:29:57 -0800733 cblk->mBufferSizeInFrames = frameCount;
Andy Hung63a35832021-03-16 17:30:09 -0700734 cblk->mStartThresholdInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800735}
736
ilewis926b82f2016-03-29 14:50:36 -0700737__attribute__((no_sanitize("integer")))
Phil Burk4bb650b2016-09-09 12:11:17 -0700738void ServerProxy::flushBufferIfNeeded()
739{
740 audio_track_cblk_t* cblk = mCblk;
741 // The acquire_load is not really required. But since the write is a release_store in the
742 // client, using acquire_load here makes it easier for people to maintain the code,
743 // and the logic for communicating ipc variables seems somewhat standard,
744 // and there really isn't much penalty for 4 or 8 byte atomics.
745 int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
746 if (flush != mFlush) {
747 ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
748 flush, mFlush);
Andy Hung1d3556d2018-03-29 16:30:14 -0700749 // shouldn't matter, but for range safety use mRear instead of getRear().
Phil Burk4bb650b2016-09-09 12:11:17 -0700750 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
751 int32_t front = cblk->u.mStreaming.mFront;
752
753 // effectively obtain then release whatever is in the buffer
754 const size_t overflowBit = mFrameCountP2 << 1;
755 const size_t mask = overflowBit - 1;
756 int32_t newFront = (front & ~mask) | (flush & mask);
Hongwei Wang95e37682019-04-12 11:13:36 -0700757 ssize_t filled = audio_utils::safe_sub_overflow(rear, newFront);
Phil Burk4bb650b2016-09-09 12:11:17 -0700758 if (filled >= (ssize_t)overflowBit) {
759 // front and rear offsets span the overflow bit of the p2 mask
760 // so rebasing newFront on the front offset is off by the overflow bit.
761 // adjust newFront to match rear offset.
762 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
763 newFront += overflowBit;
764 filled -= overflowBit;
765 }
766 // Rather than shutting down on a corrupt flush, just treat it as a full flush
767 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
768 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
769 "filled %zd=%#x",
770 mFlush, flush, front, rear,
771 (unsigned)mask, newFront, filled, (unsigned)filled);
772 newFront = rear;
773 }
774 mFlush = flush;
775 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
776 // There is no danger from a false positive, so err on the side of caution
777 if (true /*front != newFront*/) {
778 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
779 if (!(old & CBLK_FUTEX_WAKE)) {
780 (void) syscall(__NR_futex, &cblk->mFutex,
zhenjun.zhange2f8b602021-12-07 19:31:05 +0800781 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, INT_MAX);
Phil Burk4bb650b2016-09-09 12:11:17 -0700782 }
783 }
784 mFlushed += (newFront - front) & mask;
785 }
786}
787
788__attribute__((no_sanitize("integer")))
Andy Hung1d3556d2018-03-29 16:30:14 -0700789int32_t AudioTrackServerProxy::getRear() const
790{
791 const int32_t stop = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
792 const int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
793 const int32_t stopLast = mStopLast.load(std::memory_order_acquire);
794 if (stop != stopLast) {
795 const int32_t front = mCblk->u.mStreaming.mFront;
796 const size_t overflowBit = mFrameCountP2 << 1;
797 const size_t mask = overflowBit - 1;
798 int32_t newRear = (rear & ~mask) | (stop & mask);
Hongwei Wang95e37682019-04-12 11:13:36 -0700799 ssize_t filled = audio_utils::safe_sub_overflow(newRear, front);
Andy Hung54274032018-04-19 18:16:44 -0700800 // overflowBit is unsigned, so cast to signed for comparison.
801 if (filled >= (ssize_t)overflowBit) {
Andy Hung1d3556d2018-03-29 16:30:14 -0700802 // front and rear offsets span the overflow bit of the p2 mask
Andy Hung54274032018-04-19 18:16:44 -0700803 // so rebasing newRear on the rear offset is off by the overflow bit.
Andy Hung1d3556d2018-03-29 16:30:14 -0700804 ALOGV("stop wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hung54274032018-04-19 18:16:44 -0700805 newRear -= overflowBit;
806 filled -= overflowBit;
Andy Hung1d3556d2018-03-29 16:30:14 -0700807 }
808 if (0 <= filled && (size_t) filled <= mFrameCount) {
809 // we're stopped, return the stop level as newRear
810 return newRear;
811 }
812
813 // A corrupt stop. Log error and ignore.
814 ALOGE("mStopLast %#x -> stop %#x, front %#x, rear %#x, mask %#x, newRear %#x, "
815 "filled %zd=%#x",
816 stopLast, stop, front, rear,
817 (unsigned)mask, newRear, filled, (unsigned)filled);
818 // Don't reset mStopLast as this is const.
819 }
820 return rear;
821}
822
823void AudioTrackServerProxy::start()
824{
825 mStopLast = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
826}
827
828__attribute__((no_sanitize("integer")))
Glenn Kasten2e422c42013-10-18 13:00:29 -0700829status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800830{
Andy Hung9c64f342017-08-02 18:10:00 -0700831 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
832 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800833 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700834 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800835 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700836 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800837 audio_track_cblk_t* cblk = mCblk;
838 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
839 // or use previous cached value from framesReady(), with added barrier if it omits.
840 int32_t front;
841 int32_t rear;
842 // See notes on barriers at ClientProxy::obtainBuffer()
843 if (mIsOut) {
Phil Burk4bb650b2016-09-09 12:11:17 -0700844 flushBufferIfNeeded(); // might modify mFront
Andy Hung1d3556d2018-03-29 16:30:14 -0700845 rear = getRear();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100846 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800847 } else {
848 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
849 rear = cblk->u.mStreaming.mRear;
850 }
Hongwei Wang95e37682019-04-12 11:13:36 -0700851 ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800852 // pipe should not already be overfull
853 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800854 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
855 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800856 mIsShutdown = true;
857 }
858 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700859 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800860 }
861 // don't allow filling pipe beyond the nominal size
862 size_t availToServer;
863 if (mIsOut) {
864 availToServer = filled;
865 mAvailToClient = mFrameCount - filled;
866 } else {
867 availToServer = mFrameCount - filled;
868 mAvailToClient = filled;
869 }
870 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
871 size_t part1;
872 if (mIsOut) {
873 front &= mFrameCountP2 - 1;
874 part1 = mFrameCountP2 - front;
875 } else {
876 rear &= mFrameCountP2 - 1;
877 part1 = mFrameCountP2 - rear;
878 }
879 if (part1 > availToServer) {
880 part1 = availToServer;
881 }
882 size_t ask = buffer->mFrameCount;
883 if (part1 > ask) {
884 part1 = ask;
885 }
886 // is assignment redundant in some cases?
887 buffer->mFrameCount = part1;
888 buffer->mRaw = part1 > 0 ?
889 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
890 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700891 // After flush(), allow releaseBuffer() on a previously obtained buffer;
892 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
893 if (!ackFlush) {
894 mUnreleased = part1;
895 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800896 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700897 }
898no_init:
899 buffer->mFrameCount = 0;
900 buffer->mRaw = NULL;
901 buffer->mNonContig = 0;
902 mUnreleased = 0;
903 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800904}
905
ilewis926b82f2016-03-29 14:50:36 -0700906__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800907void ServerProxy::releaseBuffer(Buffer* buffer)
908{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700909 LOG_ALWAYS_FATAL_IF(buffer == NULL);
910 size_t stepCount = buffer->mFrameCount;
911 if (stepCount == 0 || mIsShutdown) {
912 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800913 buffer->mFrameCount = 0;
914 buffer->mRaw = NULL;
915 buffer->mNonContig = 0;
916 return;
917 }
Andy Hung9c64f342017-08-02 18:10:00 -0700918 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
919 "%s: mUnreleased out of range, "
920 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu)",
921 __func__, stepCount, mUnreleased, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800922 mUnreleased -= stepCount;
923 audio_track_cblk_t* cblk = mCblk;
924 if (mIsOut) {
925 int32_t front = cblk->u.mStreaming.mFront;
926 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
927 } else {
928 int32_t rear = cblk->u.mStreaming.mRear;
929 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
930 }
931
Glenn Kasten844f88c2014-05-09 13:38:09 -0700932 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800933 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800934
935 size_t half = mFrameCount / 2;
936 if (half == 0) {
937 half = 1;
938 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800939 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800940 if (minimum == 0) {
941 minimum = mIsOut ? half : 1;
942 } else if (minimum > half) {
943 minimum = half;
944 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700945 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700946 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700947 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700948 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
949 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700950 (void) syscall(__NR_futex, &cblk->mFutex,
zhenjun.zhange2f8b602021-12-07 19:31:05 +0800951 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, INT_MAX);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800952 }
953 }
954
955 buffer->mFrameCount = 0;
956 buffer->mRaw = NULL;
957 buffer->mNonContig = 0;
958}
959
960// ---------------------------------------------------------------------------
961
ilewis926b82f2016-03-29 14:50:36 -0700962__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800963size_t AudioTrackServerProxy::framesReady()
964{
965 LOG_ALWAYS_FATAL_IF(!mIsOut);
966
967 if (mIsShutdown) {
968 return 0;
969 }
970 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100971
Zhou Song8735d0d2020-08-17 15:36:56 +0800972 flushBufferIfNeeded();
973
Andy Hung1d3556d2018-03-29 16:30:14 -0700974 const int32_t rear = getRear();
Hongwei Wang95e37682019-04-12 11:13:36 -0700975 ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800976 // pipe should not already be overfull
977 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800978 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
979 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800980 mIsShutdown = true;
981 return 0;
982 }
983 // cache this value for later use by obtainBuffer(), with added barrier
984 // and racy if called by normal mixer thread
985 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
986 return filled;
987}
988
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700989__attribute__((no_sanitize("integer")))
990size_t AudioTrackServerProxy::framesReadySafe() const
991{
992 if (mIsShutdown) {
993 return 0;
994 }
995 const audio_track_cblk_t* cblk = mCblk;
996 const int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
997 if (flush != mFlush) {
998 return mFrameCount;
999 }
Andy Hung1d3556d2018-03-29 16:30:14 -07001000 const int32_t rear = getRear();
Hongwei Wang95e37682019-04-12 11:13:36 -07001001 const ssize_t filled = audio_utils::safe_sub_overflow(rear, cblk->u.mStreaming.mFront);
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001002 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
1003 return 0; // error condition, silently return 0.
1004 }
1005 return filled;
1006}
1007
Eric Laurentbfb1b832013-01-07 09:53:42 -08001008bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -07001009 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001010 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -07001011 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -08001012 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -07001013 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -07001014 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -08001015 }
1016 return old;
1017}
1018
Andy Hungd4ee4db2017-07-12 15:26:04 -07001019__attribute__((no_sanitize("integer")))
Glenn Kasten82aaf942013-07-17 16:05:07 -07001020void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
1021{
Glenn Kasten844f88c2014-05-09 13:38:09 -07001022 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -08001023 if (frameCount > 0) {
1024 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -07001025
Phil Burk2812d9e2016-01-04 10:34:30 -08001026 if (!mUnderrunning) { // start of underrun?
1027 mUnderrunCount++;
1028 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
1029 mUnderrunning = true;
1030 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
1031 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
1032 }
1033
1034 // FIXME also wake futex so that underrun is noticed more quickly
1035 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
1036 } else {
1037 ALOGV_IF(mUnderrunning,
1038 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
1039 frameCount, cblk->u.mStreaming.mUnderrunFrames);
1040 mUnderrunning = false; // so we can detect the next edge
1041 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001042}
1043
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001044AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -07001045{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -07001046 mPlaybackRateObserver.poll(mPlaybackRate);
1047 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -07001048}
1049
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001050// ---------------------------------------------------------------------------
1051
1052StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
Kevin Rocard36862032019-10-10 10:52:19 +01001053 size_t frameCount, size_t frameSize, uint32_t sampleRate)
1054 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize, false /*clientInServer*/,
1055 sampleRate),
Andy Hung4ede21d2014-12-12 15:37:34 -08001056 mObserver(&cblk->u.mStatic.mSingleStateQueue),
1057 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -08001058 mFramesReadySafe(frameCount), mFramesReady(frameCount),
1059 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001060{
Andy Hung9b461582014-12-01 17:56:29 -08001061 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001062}
1063
1064void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
1065{
1066 mFramesReadyIsCalledByMultipleThreads = true;
1067}
1068
1069size_t StaticAudioTrackServerProxy::framesReady()
1070{
Andy Hungcb2129b2014-11-11 12:17:22 -08001071 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001072 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001073 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001074 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001075 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001076}
1077
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001078size_t StaticAudioTrackServerProxy::framesReadySafe() const
1079{
1080 return mFramesReadySafe;
1081}
1082
Andy Hung9b461582014-12-01 17:56:29 -08001083status_t StaticAudioTrackServerProxy::updateStateWithLoop(
1084 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001085{
Andy Hung9b461582014-12-01 17:56:29 -08001086 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001087 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -08001088 const size_t loopStart = update.mLoopStart;
1089 const size_t loopEnd = update.mLoopEnd;
1090 size_t position = localState->mPosition;
1091 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001092 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -08001093 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001094 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
1095 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -08001096 // If the current position is greater than the end of the loop
1097 // we "wrap" to the loop start. This might cause an audible pop.
1098 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -08001099 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001100 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001101 valid = true;
1102 }
1103 }
Andy Hung9b461582014-12-01 17:56:29 -08001104 if (!valid || position > mFrameCount) {
1105 return NO_INIT;
1106 }
1107 localState->mPosition = position;
1108 localState->mLoopCount = update.mLoopCount;
1109 localState->mLoopEnd = loopEnd;
1110 localState->mLoopStart = loopStart;
1111 localState->mLoopSequence = update.mLoopSequence;
1112 }
1113 return OK;
1114}
1115
1116status_t StaticAudioTrackServerProxy::updateStateWithPosition(
1117 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1118{
1119 if (localState->mPositionSequence != update.mPositionSequence) {
1120 if (update.mPosition > mFrameCount) {
1121 return NO_INIT;
1122 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
1123 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
1124 }
1125 localState->mPosition = update.mPosition;
1126 localState->mPositionSequence = update.mPositionSequence;
1127 }
1128 return OK;
1129}
1130
1131ssize_t StaticAudioTrackServerProxy::pollPosition()
1132{
1133 StaticAudioTrackState state;
1134 if (mObserver.poll(state)) {
1135 StaticAudioTrackState trystate = mState;
1136 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -07001137 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -08001138
1139 if (diffSeq < 0) {
1140 result = updateStateWithLoop(&trystate, state) == OK &&
1141 updateStateWithPosition(&trystate, state) == OK;
1142 } else {
1143 result = updateStateWithPosition(&trystate, state) == OK &&
1144 updateStateWithLoop(&trystate, state) == OK;
1145 }
1146 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001147 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -08001148 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001149 ALOGE("%s client pushed an invalid state, shutting down", __func__);
1150 mIsShutdown = true;
1151 return (ssize_t) NO_INIT;
1152 }
Andy Hung9b461582014-12-01 17:56:29 -08001153 mState = trystate;
1154 if (mState.mLoopCount == -1) {
1155 mFramesReady = INT64_MAX;
1156 } else if (mState.mLoopCount == 0) {
1157 mFramesReady = mFrameCount - mState.mPosition;
1158 } else if (mState.mLoopCount > 0) {
1159 // TODO: Later consider fixing overflow, but does not seem needed now
1160 // as will not overflow if loopStart and loopEnd are Java "ints".
1161 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
1162 + mFrameCount - mState.mPosition;
1163 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001164 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001165 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001166 StaticAudioTrackPosLoop posLoop;
1167
1168 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
1169 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
1170 mPosLoopMutator.push(posLoop);
1171 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001172 }
Andy Hung9b461582014-12-01 17:56:29 -08001173 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001174}
1175
Andy Hungd4ee4db2017-07-12 15:26:04 -07001176__attribute__((no_sanitize("integer")))
Andy Hung954ca452015-09-09 14:39:02 -07001177status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001178{
1179 if (mIsShutdown) {
1180 buffer->mFrameCount = 0;
1181 buffer->mRaw = NULL;
1182 buffer->mNonContig = 0;
1183 mUnreleased = 0;
1184 return NO_INIT;
1185 }
1186 ssize_t positionOrStatus = pollPosition();
1187 if (positionOrStatus < 0) {
1188 buffer->mFrameCount = 0;
1189 buffer->mRaw = NULL;
1190 buffer->mNonContig = 0;
1191 mUnreleased = 0;
1192 return (status_t) positionOrStatus;
1193 }
1194 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -08001195 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001196 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -08001197 if (position < end) {
1198 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001199 size_t wanted = buffer->mFrameCount;
1200 if (avail < wanted) {
1201 buffer->mFrameCount = avail;
1202 } else {
1203 avail = wanted;
1204 }
1205 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1206 } else {
1207 avail = 0;
1208 buffer->mFrameCount = 0;
1209 buffer->mRaw = NULL;
1210 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001211 // As mFramesReady is the total remaining frames in the static audio track,
1212 // it is always larger or equal to avail.
Andy Hung9c64f342017-08-02 18:10:00 -07001213 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail,
1214 "%s: mFramesReady out of range, mFramesReady:%lld < avail:%zu",
1215 __func__, (long long)mFramesReady, avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001216 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001217 if (!ackFlush) {
1218 mUnreleased = avail;
1219 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001220 return NO_ERROR;
1221}
1222
Andy Hungd4ee4db2017-07-12 15:26:04 -07001223__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001224void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1225{
1226 size_t stepCount = buffer->mFrameCount;
Andy Hung9c64f342017-08-02 18:10:00 -07001227 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady),
1228 "%s: stepCount out of range, "
1229 "!(stepCount:%zu <= mFramesReady:%lld)",
1230 __func__, stepCount, (long long)mFramesReady);
1231 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased),
1232 "%s: stepCount out of range, "
1233 "!(stepCount:%zu <= mUnreleased:%zu)",
1234 __func__, stepCount, mUnreleased);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001235 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001236 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001237 buffer->mRaw = NULL;
1238 buffer->mNonContig = 0;
1239 return;
1240 }
1241 mUnreleased -= stepCount;
1242 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001243 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001244 size_t newPosition = position + stepCount;
1245 int32_t setFlags = 0;
1246 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001247 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1248 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001249 newPosition = mFrameCount;
1250 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001251 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001252 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001253 setFlags = CBLK_LOOP_CYCLE;
1254 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001255 setFlags = CBLK_LOOP_FINAL;
1256 }
1257 }
1258 if (newPosition == mFrameCount) {
1259 setFlags |= CBLK_BUFFER_END;
1260 }
Andy Hung9b461582014-12-01 17:56:29 -08001261 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001262 if (mFramesReady != INT64_MAX) {
1263 mFramesReady -= stepCount;
1264 }
1265 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001266
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001267 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001268 mReleased += stepCount;
1269
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001270 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001271 StaticAudioTrackPosLoop posLoop;
1272 posLoop.mBufferPosition = mState.mPosition;
1273 posLoop.mLoopCount = mState.mLoopCount;
1274 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001275 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001276 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001277 // this would be a good place to wake a futex
1278 }
1279
1280 buffer->mFrameCount = 0;
1281 buffer->mRaw = NULL;
1282 buffer->mNonContig = 0;
1283}
1284
Phil Burk2812d9e2016-01-04 10:34:30 -08001285void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001286{
1287 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1288 // we don't have a location to count underrun frames. The underrun frame counter
1289 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1290 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1291
1292 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001293 if (frameCount > 0) {
1294 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1295 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001296}
1297
Andy Hung1d3556d2018-03-29 16:30:14 -07001298int32_t StaticAudioTrackServerProxy::getRear() const
1299{
1300 LOG_ALWAYS_FATAL("getRear() not permitted for static tracks");
1301 return 0;
1302}
1303
Andy Hung2a4e1612018-06-01 15:06:09 -07001304__attribute__((no_sanitize("integer")))
1305size_t AudioRecordServerProxy::framesReadySafe() const
1306{
1307 if (mIsShutdown) {
1308 return 0;
1309 }
1310 const int32_t front = android_atomic_acquire_load(&mCblk->u.mStreaming.mFront);
1311 const int32_t rear = mCblk->u.mStreaming.mRear;
Hongwei Wang95e37682019-04-12 11:13:36 -07001312 const ssize_t filled = audio_utils::safe_sub_overflow(rear, front);
Andy Hung2a4e1612018-06-01 15:06:09 -07001313 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
1314 return 0; // error condition, silently return 0.
1315 }
1316 return filled;
1317}
1318
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001319// ---------------------------------------------------------------------------
1320
Glenn Kastena8190fc2012-12-03 17:06:56 -08001321} // namespace android