blob: b4c179d1db1402917b14b7b20568437a62597437 [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
20#include <private/media/AudioTrackShared.h>
21#include <utils/Log.h>
Elliott Hughesee499292014-05-21 17:55:51 -070022
23#include <linux/futex.h>
24#include <sys/syscall.h>
Glenn Kastena8190fc2012-12-03 17:06:56 -080025
26namespace android {
27
Andy Hungcb2129b2014-11-11 12:17:22 -080028// used to clamp a value to size_t. TODO: move to another file.
29template <typename T>
30size_t clampToSize(T x) {
Andy Hung486a7132014-12-22 16:54:21 -080031 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 -080032}
33
Andy Hung9b461582014-12-01 17:56:29 -080034// incrementSequence is used to determine the next sequence value
35// for the loop and position sequence counters. It should return
36// a value between "other" + 1 and "other" + INT32_MAX, the choice of
37// which needs to be the "least recently used" sequence value for "self".
38// In general, this means (new_self) returned is max(self, other) + 1.
Andy Hungd4ee4db2017-07-12 15:26:04 -070039__attribute__((no_sanitize("integer")))
Andy Hung9b461582014-12-01 17:56:29 -080040static uint32_t incrementSequence(uint32_t self, uint32_t other) {
Chad Brubakercb50c542015-10-07 14:20:10 -070041 int32_t diff = (int32_t) self - (int32_t) other;
Andy Hung9b461582014-12-01 17:56:29 -080042 if (diff >= 0 && diff < INT32_MAX) {
43 return self + 1; // we're already ahead of other.
44 }
45 return other + 1; // we're behind, so move just ahead of other.
46}
47
Glenn Kastena8190fc2012-12-03 17:06:56 -080048audio_track_cblk_t::audio_track_cblk_t()
Phil Burke8972b02016-03-04 11:29:57 -080049 : mServer(0), mFutex(0), mMinimum(0)
50 , mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0)
51 , mBufferSizeInFrames(0)
52 , mFlags(0)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080053{
54 memset(&u, 0, sizeof(u));
55}
56
57// ---------------------------------------------------------------------------
58
59Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
60 bool isOut, bool clientInServer)
61 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
62 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
Glenn Kasten7db7df02013-06-25 16:13:23 -070063 mIsShutdown(false), mUnreleased(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080064{
65}
66
Glenn Kasten9f80dd22012-12-18 15:57:32 -080067// ---------------------------------------------------------------------------
68
69ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
70 size_t frameSize, bool isOut, bool clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080071 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080072 , mEpoch(0)
Andy Hung6ae58432016-02-16 18:32:24 -080073 , mTimestampObserver(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -080074{
Phil Burke8972b02016-03-04 11:29:57 -080075 setBufferSizeInFrames(frameCount);
Glenn Kastena8190fc2012-12-03 17:06:56 -080076}
77
Glenn Kasten9f80dd22012-12-18 15:57:32 -080078const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
79const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
80
81#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
82
83// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
84// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
85// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
86// order of minutes.
87#define MAX_SEC 5
88
Phil Burke8972b02016-03-04 11:29:57 -080089uint32_t ClientProxy::setBufferSizeInFrames(uint32_t size)
90{
Phil Burke8972b02016-03-04 11:29:57 -080091 // The minimum should be greater than zero and less than the size
92 // at which underruns will occur.
Phil Burk26760d12016-03-21 11:53:07 -070093 const uint32_t minimum = 16; // based on AudioMixer::BLOCKSIZE
Phil Burke8972b02016-03-04 11:29:57 -080094 const uint32_t maximum = frameCount();
95 uint32_t clippedSize = size;
Phil Burk26760d12016-03-21 11:53:07 -070096 if (maximum < minimum) {
97 clippedSize = maximum;
98 } else if (clippedSize < minimum) {
Phil Burke8972b02016-03-04 11:29:57 -080099 clippedSize = minimum;
100 } else if (clippedSize > maximum) {
101 clippedSize = maximum;
102 }
103 // for server to read
104 android_atomic_release_store(clippedSize, (int32_t *)&mCblk->mBufferSizeInFrames);
105 // for client to read
106 mBufferSizeInFrames = clippedSize;
107 return clippedSize;
108}
109
ilewis926b82f2016-03-29 14:50:36 -0700110__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800111status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
112 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800113{
Andy Hung9c64f342017-08-02 18:10:00 -0700114 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
115 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800116 struct timespec total; // total elapsed time spent waiting
117 total.tv_sec = 0;
118 total.tv_nsec = 0;
119 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -0800120
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800121 status_t status;
122 enum {
123 TIMEOUT_ZERO, // requested == NULL || *requested == 0
124 TIMEOUT_INFINITE, // *requested == infinity
125 TIMEOUT_FINITE, // 0 < *requested < infinity
126 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
127 } timeout;
128 if (requested == NULL) {
129 timeout = TIMEOUT_ZERO;
130 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
131 timeout = TIMEOUT_ZERO;
132 } else if (requested->tv_sec == INT_MAX) {
133 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800134 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800135 timeout = TIMEOUT_FINITE;
136 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
137 measure = true;
138 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800139 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800140 struct timespec before;
141 bool beforeIsValid = false;
142 audio_track_cblk_t* cblk = mCblk;
143 bool ignoreInitialPendingInterrupt = true;
144 // check for shared memory corruption
145 if (mIsShutdown) {
146 status = NO_INIT;
147 goto end;
148 }
149 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700150 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800151 // check for track invalidation by server, or server death detection
152 if (flags & CBLK_INVALID) {
153 ALOGV("Track invalidated");
154 status = DEAD_OBJECT;
155 goto end;
156 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800157 if (flags & CBLK_DISABLED) {
158 ALOGV("Track disabled");
159 status = NOT_ENOUGH_DATA;
160 goto end;
161 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800162 // check for obtainBuffer interrupted by client
163 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
164 ALOGV("obtainBuffer() interrupted by client");
165 status = -EINTR;
166 goto end;
167 }
168 ignoreInitialPendingInterrupt = false;
169 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
170 int32_t front;
171 int32_t rear;
172 if (mIsOut) {
173 // The barrier following the read of mFront is probably redundant.
174 // We're about to perform a conditional branch based on 'filled',
175 // which will force the processor to observe the read of mFront
176 // prior to allowing data writes starting at mRaw.
177 // However, the processor may support speculative execution,
178 // and be unable to undo speculative writes into shared memory.
179 // The barrier will prevent such speculative execution.
180 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
181 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800182 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800183 // On the other hand, this barrier is required.
184 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
185 front = cblk->u.mStreaming.mFront;
186 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800187 // write to rear, read from front
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800188 ssize_t filled = rear - front;
189 // pipe should not be overfull
190 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700191 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700192 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700193 "shutting down", filled, mFrameCount);
194 mIsShutdown = true;
195 status = NO_INIT;
196 goto end;
197 }
198 // for input, sync up on overrun
199 filled = 0;
200 cblk->u.mStreaming.mFront = rear;
201 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800202 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800203 // Don't allow filling pipe beyond the user settable size.
204 // The calculation for avail can go negative if the buffer size
205 // is suddenly dropped below the amount already in the buffer.
206 // So use a signed calculation to prevent a numeric overflow abort.
Phil Burke8972b02016-03-04 11:29:57 -0800207 ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800208 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
209 if (avail < 0) {
210 avail = 0;
211 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800212 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800213 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800214 if (mIsOut) {
215 rear &= mFrameCountP2 - 1;
216 part1 = mFrameCountP2 - rear;
217 } else {
218 front &= mFrameCountP2 - 1;
219 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800220 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800221 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800222 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800223 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800224 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800225 part1 = buffer->mFrameCount;
226 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800227 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800228 buffer->mRaw = part1 > 0 ?
229 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
230 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700231 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800232 status = NO_ERROR;
233 break;
234 }
235 struct timespec remaining;
236 const struct timespec *ts;
237 switch (timeout) {
238 case TIMEOUT_ZERO:
239 status = WOULD_BLOCK;
240 goto end;
241 case TIMEOUT_INFINITE:
242 ts = NULL;
243 break;
244 case TIMEOUT_FINITE:
245 timeout = TIMEOUT_CONTINUE;
246 if (MAX_SEC == 0) {
247 ts = requested;
248 break;
249 }
250 // fall through
251 case TIMEOUT_CONTINUE:
252 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
253 if (!measure || requested->tv_sec < total.tv_sec ||
254 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
255 status = TIMED_OUT;
256 goto end;
257 }
258 remaining.tv_sec = requested->tv_sec - total.tv_sec;
259 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
260 remaining.tv_nsec += 1000000000;
261 remaining.tv_sec++;
262 }
263 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
264 remaining.tv_sec = MAX_SEC;
265 remaining.tv_nsec = 0;
266 }
267 ts = &remaining;
268 break;
269 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800270 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800271 ts = NULL;
272 break;
273 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700274 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
275 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800276 if (measure && !beforeIsValid) {
277 clock_gettime(CLOCK_MONOTONIC, &before);
278 beforeIsValid = true;
279 }
Elliott Hughesee499292014-05-21 17:55:51 -0700280 errno = 0;
281 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700282 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800283 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800284 // update total elapsed time spent waiting
285 if (measure) {
286 struct timespec after;
287 clock_gettime(CLOCK_MONOTONIC, &after);
288 total.tv_sec += after.tv_sec - before.tv_sec;
289 long deltaNs = after.tv_nsec - before.tv_nsec;
290 if (deltaNs < 0) {
291 deltaNs += 1000000000;
292 total.tv_sec--;
293 }
294 if ((total.tv_nsec += deltaNs) >= 1000000000) {
295 total.tv_nsec -= 1000000000;
296 total.tv_sec++;
297 }
298 before = after;
299 beforeIsValid = true;
300 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800301 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700302 case 0: // normal wakeup by server, or by binderDied()
303 case EWOULDBLOCK: // benign race condition with server
304 case EINTR: // wait was interrupted by signal or other spurious wakeup
305 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700306 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800307 break;
308 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800309 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700310 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800311 goto end;
312 }
313 }
314 }
315
316end:
317 if (status != NO_ERROR) {
318 buffer->mFrameCount = 0;
319 buffer->mRaw = NULL;
320 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700321 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800322 }
323 if (elapsed != NULL) {
324 *elapsed = total;
325 }
326 if (requested == NULL) {
327 requested = &kNonBlocking;
328 }
329 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100330 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
331 requested->tv_sec, requested->tv_nsec / 1000000,
332 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800333 }
334 return status;
335}
336
ilewis926b82f2016-03-29 14:50:36 -0700337__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800338void ClientProxy::releaseBuffer(Buffer* buffer)
339{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700340 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800341 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700342 if (stepCount == 0 || mIsShutdown) {
343 // prevent accidental re-use of buffer
344 buffer->mFrameCount = 0;
345 buffer->mRaw = NULL;
346 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800347 return;
348 }
Andy Hung9c64f342017-08-02 18:10:00 -0700349 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
350 "%s: mUnreleased out of range, "
351 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu), BufferSizeInFrames:%u",
352 __func__, stepCount, mUnreleased, mFrameCount, getBufferSizeInFrames());
Glenn Kasten7db7df02013-06-25 16:13:23 -0700353 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800354 audio_track_cblk_t* cblk = mCblk;
355 // Both of these barriers are required
356 if (mIsOut) {
357 int32_t rear = cblk->u.mStreaming.mRear;
358 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
359 } else {
360 int32_t front = cblk->u.mStreaming.mFront;
361 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
362 }
363}
364
365void ClientProxy::binderDied()
366{
367 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700368 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900369 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800370 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700371 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
372 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800373 }
374}
375
376void ClientProxy::interrupt()
377{
378 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700379 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900380 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700381 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
382 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800383 }
384}
385
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700386__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800387size_t ClientProxy::getMisalignment()
388{
389 audio_track_cblk_t* cblk = mCblk;
390 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
391 (mFrameCountP2 - 1);
392}
393
394// ---------------------------------------------------------------------------
395
396void AudioTrackClientProxy::flush()
397{
Andy Hung1d3556d2018-03-29 16:30:14 -0700398 sendStreamingFlushStop(true /* flush */);
399}
400
401void AudioTrackClientProxy::stop()
402{
403 sendStreamingFlushStop(false /* flush */);
404}
405
406// Sets the client-written mFlush and mStop positions, which control server behavior.
407//
408// @param flush indicates whether the operation is a flush or stop.
409// A client stop sets mStop to the current write position;
410// the server will not read past this point until start() or subsequent flush().
411// A client flush sets both mStop and mFlush to the current write position.
412// This advances the server read limit (if previously set) and on the next
413// server read advances the server read position to this limit.
414//
415void AudioTrackClientProxy::sendStreamingFlushStop(bool flush)
416{
417 // TODO: Replace this by 64 bit counters - avoids wrap complication.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700418 // This works for mFrameCountP2 <= 2^30
Andy Hunga2d75cd2015-07-15 17:04:20 -0700419 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
420 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
421 // if you want to flush twice to the same rear location after a 32 bit wrap.
Andy Hung1d3556d2018-03-29 16:30:14 -0700422
423 const size_t increment = mFrameCountP2 << 1;
424 const size_t mask = increment - 1;
425 // No need for client atomic synchronization on mRear, mStop, mFlush
426 // as AudioTrack client only read/writes to them under client lock. Server only reads.
427 const int32_t rearMasked = mCblk->u.mStreaming.mRear & mask;
428
429 // update stop before flush so that the server front
430 // never advances beyond a (potential) previous stop's rear limit.
431 int32_t stopBits; // the following add can overflow
432 __builtin_add_overflow(mCblk->u.mStreaming.mStop & ~mask, increment, &stopBits);
433 android_atomic_release_store(rearMasked | stopBits, &mCblk->u.mStreaming.mStop);
434
435 if (flush) {
436 int32_t flushBits; // the following add can overflow
437 __builtin_add_overflow(mCblk->u.mStreaming.mFlush & ~mask, increment, &flushBits);
438 android_atomic_release_store(rearMasked | flushBits, &mCblk->u.mStreaming.mFlush);
439 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800440}
441
Eric Laurentbfb1b832013-01-07 09:53:42 -0800442bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700443 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800444}
445
446bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700447 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800448}
449
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100450status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
451{
452 struct timespec total; // total elapsed time spent waiting
453 total.tv_sec = 0;
454 total.tv_nsec = 0;
455 audio_track_cblk_t* cblk = mCblk;
456 status_t status;
457 enum {
458 TIMEOUT_ZERO, // requested == NULL || *requested == 0
459 TIMEOUT_INFINITE, // *requested == infinity
460 TIMEOUT_FINITE, // 0 < *requested < infinity
461 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
462 } timeout;
463 if (requested == NULL) {
464 timeout = TIMEOUT_ZERO;
465 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
466 timeout = TIMEOUT_ZERO;
467 } else if (requested->tv_sec == INT_MAX) {
468 timeout = TIMEOUT_INFINITE;
469 } else {
470 timeout = TIMEOUT_FINITE;
471 }
472 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700473 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100474 // check for track invalidation by server, or server death detection
475 if (flags & CBLK_INVALID) {
476 ALOGV("Track invalidated");
477 status = DEAD_OBJECT;
478 goto end;
479 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800480 // a track is not supposed to underrun at this stage but consider it done
481 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100482 ALOGV("stream end received");
483 status = NO_ERROR;
484 goto end;
485 }
486 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100487 if (flags & CBLK_INTERRUPT) {
488 ALOGV("waitStreamEndDone() interrupted by client");
489 status = -EINTR;
490 goto end;
491 }
492 struct timespec remaining;
493 const struct timespec *ts;
494 switch (timeout) {
495 case TIMEOUT_ZERO:
496 status = WOULD_BLOCK;
497 goto end;
498 case TIMEOUT_INFINITE:
499 ts = NULL;
500 break;
501 case TIMEOUT_FINITE:
502 timeout = TIMEOUT_CONTINUE;
503 if (MAX_SEC == 0) {
504 ts = requested;
505 break;
506 }
507 // fall through
508 case TIMEOUT_CONTINUE:
509 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
510 if (requested->tv_sec < total.tv_sec ||
511 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
512 status = TIMED_OUT;
513 goto end;
514 }
515 remaining.tv_sec = requested->tv_sec - total.tv_sec;
516 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
517 remaining.tv_nsec += 1000000000;
518 remaining.tv_sec++;
519 }
520 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
521 remaining.tv_sec = MAX_SEC;
522 remaining.tv_nsec = 0;
523 }
524 ts = &remaining;
525 break;
526 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800527 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100528 ts = NULL;
529 break;
530 }
531 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
532 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700533 errno = 0;
534 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100535 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700536 switch (errno) {
537 case 0: // normal wakeup by server, or by binderDied()
538 case EWOULDBLOCK: // benign race condition with server
539 case EINTR: // wait was interrupted by signal or other spurious wakeup
540 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100541 break;
542 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700543 status = errno;
544 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100545 goto end;
546 }
547 }
548 }
549
550end:
551 if (requested == NULL) {
552 requested = &kNonBlocking;
553 }
554 return status;
555}
556
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800557// ---------------------------------------------------------------------------
558
559StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
560 size_t frameCount, size_t frameSize)
561 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800562 mMutator(&cblk->u.mStatic.mSingleStateQueue),
563 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800564{
Andy Hung9b461582014-12-01 17:56:29 -0800565 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800566 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567}
568
569void StaticAudioTrackClientProxy::flush()
570{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800571 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572}
573
Andy Hung1d3556d2018-03-29 16:30:14 -0700574void StaticAudioTrackClientProxy::stop()
575{
576 ; // no special handling required for static tracks.
577}
578
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
580{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800581 // This can only happen on a 64-bit client
582 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
583 // FIXME Should return an error status
584 return;
585 }
Andy Hung9b461582014-12-01 17:56:29 -0800586 mState.mLoopStart = (uint32_t) loopStart;
587 mState.mLoopEnd = (uint32_t) loopEnd;
588 mState.mLoopCount = loopCount;
589 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
590 // set patch-up variables until the mState is acknowledged by the ServerProxy.
591 // observed buffer position and loop count will freeze until then to give the
592 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800593 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800594 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800595 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
596 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800597 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800598 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800599 (void) mMutator.push(mState);
600}
601
602void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
603{
604 // This can only happen on a 64-bit client
605 if (position > UINT32_MAX) {
606 // FIXME Should return an error status
607 return;
608 }
609 mState.mPosition = (uint32_t) position;
610 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800611 // set patch-up variables until the mState is acknowledged by the ServerProxy.
612 // observed buffer position and loop count will freeze until then to give the
613 // illusion of a synchronous change.
614 if (mState.mLoopCount > 0) { // only check if loop count is changing
615 getBufferPositionAndLoopCount(NULL, NULL); // get last position
616 }
617 mPosLoop.mBufferPosition = position;
618 if (position >= mState.mLoopEnd) {
619 // no ongoing loop is possible if position is greater than loopEnd.
620 mPosLoop.mLoopCount = 0;
621 }
Andy Hung9b461582014-12-01 17:56:29 -0800622 (void) mMutator.push(mState);
623}
624
625void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
626 size_t loopEnd, int loopCount)
627{
628 setLoop(loopStart, loopEnd, loopCount);
629 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800630}
631
632size_t StaticAudioTrackClientProxy::getBufferPosition()
633{
Andy Hung4ede21d2014-12-12 15:37:34 -0800634 getBufferPositionAndLoopCount(NULL, NULL);
635 return mPosLoop.mBufferPosition;
636}
637
638void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
639 size_t *position, int *loopCount)
640{
641 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
642 if (mPosLoopObserver.poll(mPosLoop)) {
643 ; // a valid mPosLoop should be available if ackDone is true.
644 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800645 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800646 if (position != NULL) {
647 *position = mPosLoop.mBufferPosition;
648 }
649 if (loopCount != NULL) {
650 *loopCount = mPosLoop.mLoopCount;
651 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800652}
653
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800654// ---------------------------------------------------------------------------
655
656ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
657 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700658 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hungea2b9c02016-02-12 17:06:53 -0800659 mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800660 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800661{
Phil Burke8972b02016-03-04 11:29:57 -0800662 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800663}
664
ilewis926b82f2016-03-29 14:50:36 -0700665__attribute__((no_sanitize("integer")))
Phil Burk4bb650b2016-09-09 12:11:17 -0700666void ServerProxy::flushBufferIfNeeded()
667{
668 audio_track_cblk_t* cblk = mCblk;
669 // The acquire_load is not really required. But since the write is a release_store in the
670 // client, using acquire_load here makes it easier for people to maintain the code,
671 // and the logic for communicating ipc variables seems somewhat standard,
672 // and there really isn't much penalty for 4 or 8 byte atomics.
673 int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
674 if (flush != mFlush) {
675 ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
676 flush, mFlush);
Andy Hung1d3556d2018-03-29 16:30:14 -0700677 // shouldn't matter, but for range safety use mRear instead of getRear().
Phil Burk4bb650b2016-09-09 12:11:17 -0700678 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
679 int32_t front = cblk->u.mStreaming.mFront;
680
681 // effectively obtain then release whatever is in the buffer
682 const size_t overflowBit = mFrameCountP2 << 1;
683 const size_t mask = overflowBit - 1;
684 int32_t newFront = (front & ~mask) | (flush & mask);
685 ssize_t filled = rear - newFront;
686 if (filled >= (ssize_t)overflowBit) {
687 // front and rear offsets span the overflow bit of the p2 mask
688 // so rebasing newFront on the front offset is off by the overflow bit.
689 // adjust newFront to match rear offset.
690 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
691 newFront += overflowBit;
692 filled -= overflowBit;
693 }
694 // Rather than shutting down on a corrupt flush, just treat it as a full flush
695 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
696 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
697 "filled %zd=%#x",
698 mFlush, flush, front, rear,
699 (unsigned)mask, newFront, filled, (unsigned)filled);
700 newFront = rear;
701 }
702 mFlush = flush;
703 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
704 // There is no danger from a false positive, so err on the side of caution
705 if (true /*front != newFront*/) {
706 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
707 if (!(old & CBLK_FUTEX_WAKE)) {
708 (void) syscall(__NR_futex, &cblk->mFutex,
709 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
710 }
711 }
712 mFlushed += (newFront - front) & mask;
713 }
714}
715
716__attribute__((no_sanitize("integer")))
Andy Hung1d3556d2018-03-29 16:30:14 -0700717int32_t AudioTrackServerProxy::getRear() const
718{
719 const int32_t stop = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
720 const int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
721 const int32_t stopLast = mStopLast.load(std::memory_order_acquire);
722 if (stop != stopLast) {
723 const int32_t front = mCblk->u.mStreaming.mFront;
724 const size_t overflowBit = mFrameCountP2 << 1;
725 const size_t mask = overflowBit - 1;
726 int32_t newRear = (rear & ~mask) | (stop & mask);
727 ssize_t filled = newRear - front;
728 if (filled < 0) {
729 // front and rear offsets span the overflow bit of the p2 mask
730 // so rebasing newrear.
731 ALOGV("stop wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
732 newRear += overflowBit;
733 filled += overflowBit;
734 }
735 if (0 <= filled && (size_t) filled <= mFrameCount) {
736 // we're stopped, return the stop level as newRear
737 return newRear;
738 }
739
740 // A corrupt stop. Log error and ignore.
741 ALOGE("mStopLast %#x -> stop %#x, front %#x, rear %#x, mask %#x, newRear %#x, "
742 "filled %zd=%#x",
743 stopLast, stop, front, rear,
744 (unsigned)mask, newRear, filled, (unsigned)filled);
745 // Don't reset mStopLast as this is const.
746 }
747 return rear;
748}
749
750void AudioTrackServerProxy::start()
751{
752 mStopLast = android_atomic_acquire_load(&mCblk->u.mStreaming.mStop);
753}
754
755__attribute__((no_sanitize("integer")))
Glenn Kasten2e422c42013-10-18 13:00:29 -0700756status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800757{
Andy Hung9c64f342017-08-02 18:10:00 -0700758 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
759 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800760 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700761 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800762 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700763 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800764 audio_track_cblk_t* cblk = mCblk;
765 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
766 // or use previous cached value from framesReady(), with added barrier if it omits.
767 int32_t front;
768 int32_t rear;
769 // See notes on barriers at ClientProxy::obtainBuffer()
770 if (mIsOut) {
Phil Burk4bb650b2016-09-09 12:11:17 -0700771 flushBufferIfNeeded(); // might modify mFront
Andy Hung1d3556d2018-03-29 16:30:14 -0700772 rear = getRear();
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100773 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800774 } else {
775 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
776 rear = cblk->u.mStreaming.mRear;
777 }
778 ssize_t filled = rear - front;
779 // pipe should not already be overfull
780 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800781 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
782 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800783 mIsShutdown = true;
784 }
785 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700786 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800787 }
788 // don't allow filling pipe beyond the nominal size
789 size_t availToServer;
790 if (mIsOut) {
791 availToServer = filled;
792 mAvailToClient = mFrameCount - filled;
793 } else {
794 availToServer = mFrameCount - filled;
795 mAvailToClient = filled;
796 }
797 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
798 size_t part1;
799 if (mIsOut) {
800 front &= mFrameCountP2 - 1;
801 part1 = mFrameCountP2 - front;
802 } else {
803 rear &= mFrameCountP2 - 1;
804 part1 = mFrameCountP2 - rear;
805 }
806 if (part1 > availToServer) {
807 part1 = availToServer;
808 }
809 size_t ask = buffer->mFrameCount;
810 if (part1 > ask) {
811 part1 = ask;
812 }
813 // is assignment redundant in some cases?
814 buffer->mFrameCount = part1;
815 buffer->mRaw = part1 > 0 ?
816 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
817 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700818 // After flush(), allow releaseBuffer() on a previously obtained buffer;
819 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
820 if (!ackFlush) {
821 mUnreleased = part1;
822 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800823 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700824 }
825no_init:
826 buffer->mFrameCount = 0;
827 buffer->mRaw = NULL;
828 buffer->mNonContig = 0;
829 mUnreleased = 0;
830 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800831}
832
ilewis926b82f2016-03-29 14:50:36 -0700833__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800834void ServerProxy::releaseBuffer(Buffer* buffer)
835{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700836 LOG_ALWAYS_FATAL_IF(buffer == NULL);
837 size_t stepCount = buffer->mFrameCount;
838 if (stepCount == 0 || mIsShutdown) {
839 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840 buffer->mFrameCount = 0;
841 buffer->mRaw = NULL;
842 buffer->mNonContig = 0;
843 return;
844 }
Andy Hung9c64f342017-08-02 18:10:00 -0700845 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
846 "%s: mUnreleased out of range, "
847 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu)",
848 __func__, stepCount, mUnreleased, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800849 mUnreleased -= stepCount;
850 audio_track_cblk_t* cblk = mCblk;
851 if (mIsOut) {
852 int32_t front = cblk->u.mStreaming.mFront;
853 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
854 } else {
855 int32_t rear = cblk->u.mStreaming.mRear;
856 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
857 }
858
Glenn Kasten844f88c2014-05-09 13:38:09 -0700859 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800860 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800861
862 size_t half = mFrameCount / 2;
863 if (half == 0) {
864 half = 1;
865 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800866 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800867 if (minimum == 0) {
868 minimum = mIsOut ? half : 1;
869 } else if (minimum > half) {
870 minimum = half;
871 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700872 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700873 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700874 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700875 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
876 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700877 (void) syscall(__NR_futex, &cblk->mFutex,
878 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800879 }
880 }
881
882 buffer->mFrameCount = 0;
883 buffer->mRaw = NULL;
884 buffer->mNonContig = 0;
885}
886
887// ---------------------------------------------------------------------------
888
ilewis926b82f2016-03-29 14:50:36 -0700889__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890size_t AudioTrackServerProxy::framesReady()
891{
892 LOG_ALWAYS_FATAL_IF(!mIsOut);
893
894 if (mIsShutdown) {
895 return 0;
896 }
897 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100898
899 int32_t flush = cblk->u.mStreaming.mFlush;
900 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700901 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100902 return mFrameCount;
903 }
Andy Hung1d3556d2018-03-29 16:30:14 -0700904 const int32_t rear = getRear();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800905 ssize_t filled = rear - cblk->u.mStreaming.mFront;
906 // pipe should not already be overfull
907 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800908 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
909 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800910 mIsShutdown = true;
911 return 0;
912 }
913 // cache this value for later use by obtainBuffer(), with added barrier
914 // and racy if called by normal mixer thread
915 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
916 return filled;
917}
918
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700919__attribute__((no_sanitize("integer")))
920size_t AudioTrackServerProxy::framesReadySafe() const
921{
922 if (mIsShutdown) {
923 return 0;
924 }
925 const audio_track_cblk_t* cblk = mCblk;
926 const int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
927 if (flush != mFlush) {
928 return mFrameCount;
929 }
Andy Hung1d3556d2018-03-29 16:30:14 -0700930 const int32_t rear = getRear();
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700931 const ssize_t filled = rear - cblk->u.mStreaming.mFront;
932 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
933 return 0; // error condition, silently return 0.
934 }
935 return filled;
936}
937
Eric Laurentbfb1b832013-01-07 09:53:42 -0800938bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700939 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800940 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700941 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800942 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700943 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700944 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800945 }
946 return old;
947}
948
Andy Hungd4ee4db2017-07-12 15:26:04 -0700949__attribute__((no_sanitize("integer")))
Glenn Kasten82aaf942013-07-17 16:05:07 -0700950void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
951{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700952 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800953 if (frameCount > 0) {
954 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700955
Phil Burk2812d9e2016-01-04 10:34:30 -0800956 if (!mUnderrunning) { // start of underrun?
957 mUnderrunCount++;
958 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
959 mUnderrunning = true;
960 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
961 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
962 }
963
964 // FIXME also wake futex so that underrun is noticed more quickly
965 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
966 } else {
967 ALOGV_IF(mUnderrunning,
968 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
969 frameCount, cblk->u.mStreaming.mUnderrunFrames);
970 mUnderrunning = false; // so we can detect the next edge
971 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700972}
973
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700974AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700975{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700976 mPlaybackRateObserver.poll(mPlaybackRate);
977 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700978}
979
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800980// ---------------------------------------------------------------------------
981
982StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
983 size_t frameCount, size_t frameSize)
984 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800985 mObserver(&cblk->u.mStatic.mSingleStateQueue),
986 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800987 mFramesReadySafe(frameCount), mFramesReady(frameCount),
988 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800989{
Andy Hung9b461582014-12-01 17:56:29 -0800990 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800991}
992
993void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
994{
995 mFramesReadyIsCalledByMultipleThreads = true;
996}
997
998size_t StaticAudioTrackServerProxy::framesReady()
999{
Andy Hungcb2129b2014-11-11 12:17:22 -08001000 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001001 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001002 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001003 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001004 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001005}
1006
Andy Hung2c6c3bb2017-06-16 14:01:45 -07001007size_t StaticAudioTrackServerProxy::framesReadySafe() const
1008{
1009 return mFramesReadySafe;
1010}
1011
Andy Hung9b461582014-12-01 17:56:29 -08001012status_t StaticAudioTrackServerProxy::updateStateWithLoop(
1013 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001014{
Andy Hung9b461582014-12-01 17:56:29 -08001015 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001016 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -08001017 const size_t loopStart = update.mLoopStart;
1018 const size_t loopEnd = update.mLoopEnd;
1019 size_t position = localState->mPosition;
1020 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001021 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -08001022 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001023 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
1024 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -08001025 // If the current position is greater than the end of the loop
1026 // we "wrap" to the loop start. This might cause an audible pop.
1027 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -08001028 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001029 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001030 valid = true;
1031 }
1032 }
Andy Hung9b461582014-12-01 17:56:29 -08001033 if (!valid || position > mFrameCount) {
1034 return NO_INIT;
1035 }
1036 localState->mPosition = position;
1037 localState->mLoopCount = update.mLoopCount;
1038 localState->mLoopEnd = loopEnd;
1039 localState->mLoopStart = loopStart;
1040 localState->mLoopSequence = update.mLoopSequence;
1041 }
1042 return OK;
1043}
1044
1045status_t StaticAudioTrackServerProxy::updateStateWithPosition(
1046 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
1047{
1048 if (localState->mPositionSequence != update.mPositionSequence) {
1049 if (update.mPosition > mFrameCount) {
1050 return NO_INIT;
1051 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
1052 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
1053 }
1054 localState->mPosition = update.mPosition;
1055 localState->mPositionSequence = update.mPositionSequence;
1056 }
1057 return OK;
1058}
1059
1060ssize_t StaticAudioTrackServerProxy::pollPosition()
1061{
1062 StaticAudioTrackState state;
1063 if (mObserver.poll(state)) {
1064 StaticAudioTrackState trystate = mState;
1065 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -07001066 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -08001067
1068 if (diffSeq < 0) {
1069 result = updateStateWithLoop(&trystate, state) == OK &&
1070 updateStateWithPosition(&trystate, state) == OK;
1071 } else {
1072 result = updateStateWithPosition(&trystate, state) == OK &&
1073 updateStateWithLoop(&trystate, state) == OK;
1074 }
1075 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -08001076 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -08001077 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001078 ALOGE("%s client pushed an invalid state, shutting down", __func__);
1079 mIsShutdown = true;
1080 return (ssize_t) NO_INIT;
1081 }
Andy Hung9b461582014-12-01 17:56:29 -08001082 mState = trystate;
1083 if (mState.mLoopCount == -1) {
1084 mFramesReady = INT64_MAX;
1085 } else if (mState.mLoopCount == 0) {
1086 mFramesReady = mFrameCount - mState.mPosition;
1087 } else if (mState.mLoopCount > 0) {
1088 // TODO: Later consider fixing overflow, but does not seem needed now
1089 // as will not overflow if loopStart and loopEnd are Java "ints".
1090 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
1091 + mFrameCount - mState.mPosition;
1092 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001093 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001094 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001095 StaticAudioTrackPosLoop posLoop;
1096
1097 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
1098 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
1099 mPosLoopMutator.push(posLoop);
1100 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001101 }
Andy Hung9b461582014-12-01 17:56:29 -08001102 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001103}
1104
Andy Hungd4ee4db2017-07-12 15:26:04 -07001105__attribute__((no_sanitize("integer")))
Andy Hung954ca452015-09-09 14:39:02 -07001106status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001107{
1108 if (mIsShutdown) {
1109 buffer->mFrameCount = 0;
1110 buffer->mRaw = NULL;
1111 buffer->mNonContig = 0;
1112 mUnreleased = 0;
1113 return NO_INIT;
1114 }
1115 ssize_t positionOrStatus = pollPosition();
1116 if (positionOrStatus < 0) {
1117 buffer->mFrameCount = 0;
1118 buffer->mRaw = NULL;
1119 buffer->mNonContig = 0;
1120 mUnreleased = 0;
1121 return (status_t) positionOrStatus;
1122 }
1123 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -08001124 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001125 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -08001126 if (position < end) {
1127 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001128 size_t wanted = buffer->mFrameCount;
1129 if (avail < wanted) {
1130 buffer->mFrameCount = avail;
1131 } else {
1132 avail = wanted;
1133 }
1134 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1135 } else {
1136 avail = 0;
1137 buffer->mFrameCount = 0;
1138 buffer->mRaw = NULL;
1139 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001140 // As mFramesReady is the total remaining frames in the static audio track,
1141 // it is always larger or equal to avail.
Andy Hung9c64f342017-08-02 18:10:00 -07001142 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail,
1143 "%s: mFramesReady out of range, mFramesReady:%lld < avail:%zu",
1144 __func__, (long long)mFramesReady, avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001145 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001146 if (!ackFlush) {
1147 mUnreleased = avail;
1148 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001149 return NO_ERROR;
1150}
1151
Andy Hungd4ee4db2017-07-12 15:26:04 -07001152__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001153void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1154{
1155 size_t stepCount = buffer->mFrameCount;
Andy Hung9c64f342017-08-02 18:10:00 -07001156 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady),
1157 "%s: stepCount out of range, "
1158 "!(stepCount:%zu <= mFramesReady:%lld)",
1159 __func__, stepCount, (long long)mFramesReady);
1160 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased),
1161 "%s: stepCount out of range, "
1162 "!(stepCount:%zu <= mUnreleased:%zu)",
1163 __func__, stepCount, mUnreleased);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001164 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001165 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001166 buffer->mRaw = NULL;
1167 buffer->mNonContig = 0;
1168 return;
1169 }
1170 mUnreleased -= stepCount;
1171 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001172 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001173 size_t newPosition = position + stepCount;
1174 int32_t setFlags = 0;
1175 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001176 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1177 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001178 newPosition = mFrameCount;
1179 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001180 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001181 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001182 setFlags = CBLK_LOOP_CYCLE;
1183 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001184 setFlags = CBLK_LOOP_FINAL;
1185 }
1186 }
1187 if (newPosition == mFrameCount) {
1188 setFlags |= CBLK_BUFFER_END;
1189 }
Andy Hung9b461582014-12-01 17:56:29 -08001190 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001191 if (mFramesReady != INT64_MAX) {
1192 mFramesReady -= stepCount;
1193 }
1194 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001195
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001196 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001197 mReleased += stepCount;
1198
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001199 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001200 StaticAudioTrackPosLoop posLoop;
1201 posLoop.mBufferPosition = mState.mPosition;
1202 posLoop.mLoopCount = mState.mLoopCount;
1203 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001204 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001205 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001206 // this would be a good place to wake a futex
1207 }
1208
1209 buffer->mFrameCount = 0;
1210 buffer->mRaw = NULL;
1211 buffer->mNonContig = 0;
1212}
1213
Phil Burk2812d9e2016-01-04 10:34:30 -08001214void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001215{
1216 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1217 // we don't have a location to count underrun frames. The underrun frame counter
1218 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1219 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1220
1221 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001222 if (frameCount > 0) {
1223 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1224 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001225}
1226
Andy Hung1d3556d2018-03-29 16:30:14 -07001227int32_t StaticAudioTrackServerProxy::getRear() const
1228{
1229 LOG_ALWAYS_FATAL("getRear() not permitted for static tracks");
1230 return 0;
1231}
1232
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001233// ---------------------------------------------------------------------------
1234
Glenn Kastena8190fc2012-12-03 17:06:56 -08001235} // namespace android