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