blob: 08c37f8c20e953d5264caba5b18f0594c7264937 [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.
39
40static 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{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700398 // This works for mFrameCountP2 <= 2^30
399 size_t increment = mFrameCountP2 << 1;
400 size_t mask = increment - 1;
401 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700402 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
403 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
404 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700405 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
406 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
407 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800408}
409
Eric Laurentbfb1b832013-01-07 09:53:42 -0800410bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700411 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800412}
413
414bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700415 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800416}
417
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100418status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
419{
420 struct timespec total; // total elapsed time spent waiting
421 total.tv_sec = 0;
422 total.tv_nsec = 0;
423 audio_track_cblk_t* cblk = mCblk;
424 status_t status;
425 enum {
426 TIMEOUT_ZERO, // requested == NULL || *requested == 0
427 TIMEOUT_INFINITE, // *requested == infinity
428 TIMEOUT_FINITE, // 0 < *requested < infinity
429 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
430 } timeout;
431 if (requested == NULL) {
432 timeout = TIMEOUT_ZERO;
433 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
434 timeout = TIMEOUT_ZERO;
435 } else if (requested->tv_sec == INT_MAX) {
436 timeout = TIMEOUT_INFINITE;
437 } else {
438 timeout = TIMEOUT_FINITE;
439 }
440 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700441 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100442 // check for track invalidation by server, or server death detection
443 if (flags & CBLK_INVALID) {
444 ALOGV("Track invalidated");
445 status = DEAD_OBJECT;
446 goto end;
447 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800448 // a track is not supposed to underrun at this stage but consider it done
449 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100450 ALOGV("stream end received");
451 status = NO_ERROR;
452 goto end;
453 }
454 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100455 if (flags & CBLK_INTERRUPT) {
456 ALOGV("waitStreamEndDone() interrupted by client");
457 status = -EINTR;
458 goto end;
459 }
460 struct timespec remaining;
461 const struct timespec *ts;
462 switch (timeout) {
463 case TIMEOUT_ZERO:
464 status = WOULD_BLOCK;
465 goto end;
466 case TIMEOUT_INFINITE:
467 ts = NULL;
468 break;
469 case TIMEOUT_FINITE:
470 timeout = TIMEOUT_CONTINUE;
471 if (MAX_SEC == 0) {
472 ts = requested;
473 break;
474 }
475 // fall through
476 case TIMEOUT_CONTINUE:
477 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
478 if (requested->tv_sec < total.tv_sec ||
479 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
480 status = TIMED_OUT;
481 goto end;
482 }
483 remaining.tv_sec = requested->tv_sec - total.tv_sec;
484 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
485 remaining.tv_nsec += 1000000000;
486 remaining.tv_sec++;
487 }
488 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
489 remaining.tv_sec = MAX_SEC;
490 remaining.tv_nsec = 0;
491 }
492 ts = &remaining;
493 break;
494 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800495 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100496 ts = NULL;
497 break;
498 }
499 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
500 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700501 errno = 0;
502 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100503 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700504 switch (errno) {
505 case 0: // normal wakeup by server, or by binderDied()
506 case EWOULDBLOCK: // benign race condition with server
507 case EINTR: // wait was interrupted by signal or other spurious wakeup
508 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100509 break;
510 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700511 status = errno;
512 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100513 goto end;
514 }
515 }
516 }
517
518end:
519 if (requested == NULL) {
520 requested = &kNonBlocking;
521 }
522 return status;
523}
524
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800525// ---------------------------------------------------------------------------
526
527StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
528 size_t frameCount, size_t frameSize)
529 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800530 mMutator(&cblk->u.mStatic.mSingleStateQueue),
531 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800532{
Andy Hung9b461582014-12-01 17:56:29 -0800533 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800534 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800535}
536
537void StaticAudioTrackClientProxy::flush()
538{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800539 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800540}
541
542void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
543{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800544 // This can only happen on a 64-bit client
545 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
546 // FIXME Should return an error status
547 return;
548 }
Andy Hung9b461582014-12-01 17:56:29 -0800549 mState.mLoopStart = (uint32_t) loopStart;
550 mState.mLoopEnd = (uint32_t) loopEnd;
551 mState.mLoopCount = loopCount;
552 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
553 // set patch-up variables until the mState is acknowledged by the ServerProxy.
554 // observed buffer position and loop count will freeze until then to give the
555 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800556 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800557 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800558 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
559 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800560 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800561 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800562 (void) mMutator.push(mState);
563}
564
565void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
566{
567 // This can only happen on a 64-bit client
568 if (position > UINT32_MAX) {
569 // FIXME Should return an error status
570 return;
571 }
572 mState.mPosition = (uint32_t) position;
573 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800574 // set patch-up variables until the mState is acknowledged by the ServerProxy.
575 // observed buffer position and loop count will freeze until then to give the
576 // illusion of a synchronous change.
577 if (mState.mLoopCount > 0) { // only check if loop count is changing
578 getBufferPositionAndLoopCount(NULL, NULL); // get last position
579 }
580 mPosLoop.mBufferPosition = position;
581 if (position >= mState.mLoopEnd) {
582 // no ongoing loop is possible if position is greater than loopEnd.
583 mPosLoop.mLoopCount = 0;
584 }
Andy Hung9b461582014-12-01 17:56:29 -0800585 (void) mMutator.push(mState);
586}
587
588void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
589 size_t loopEnd, int loopCount)
590{
591 setLoop(loopStart, loopEnd, loopCount);
592 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800593}
594
595size_t StaticAudioTrackClientProxy::getBufferPosition()
596{
Andy Hung4ede21d2014-12-12 15:37:34 -0800597 getBufferPositionAndLoopCount(NULL, NULL);
598 return mPosLoop.mBufferPosition;
599}
600
601void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
602 size_t *position, int *loopCount)
603{
604 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
605 if (mPosLoopObserver.poll(mPosLoop)) {
606 ; // a valid mPosLoop should be available if ackDone is true.
607 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800608 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800609 if (position != NULL) {
610 *position = mPosLoop.mBufferPosition;
611 }
612 if (loopCount != NULL) {
613 *loopCount = mPosLoop.mLoopCount;
614 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800615}
616
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617// ---------------------------------------------------------------------------
618
619ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
620 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700621 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hungea2b9c02016-02-12 17:06:53 -0800622 mAvailToClient(0), mFlush(0), mReleased(0), mFlushed(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800623 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800624{
Phil Burke8972b02016-03-04 11:29:57 -0800625 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800626}
627
ilewis926b82f2016-03-29 14:50:36 -0700628__attribute__((no_sanitize("integer")))
Phil Burk4bb650b2016-09-09 12:11:17 -0700629void ServerProxy::flushBufferIfNeeded()
630{
631 audio_track_cblk_t* cblk = mCblk;
632 // The acquire_load is not really required. But since the write is a release_store in the
633 // client, using acquire_load here makes it easier for people to maintain the code,
634 // and the logic for communicating ipc variables seems somewhat standard,
635 // and there really isn't much penalty for 4 or 8 byte atomics.
636 int32_t flush = android_atomic_acquire_load(&cblk->u.mStreaming.mFlush);
637 if (flush != mFlush) {
638 ALOGV("ServerProxy::flushBufferIfNeeded() mStreaming.mFlush = 0x%x, mFlush = 0x%0x",
639 flush, mFlush);
640 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
641 int32_t front = cblk->u.mStreaming.mFront;
642
643 // effectively obtain then release whatever is in the buffer
644 const size_t overflowBit = mFrameCountP2 << 1;
645 const size_t mask = overflowBit - 1;
646 int32_t newFront = (front & ~mask) | (flush & mask);
647 ssize_t filled = rear - newFront;
648 if (filled >= (ssize_t)overflowBit) {
649 // front and rear offsets span the overflow bit of the p2 mask
650 // so rebasing newFront on the front offset is off by the overflow bit.
651 // adjust newFront to match rear offset.
652 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
653 newFront += overflowBit;
654 filled -= overflowBit;
655 }
656 // Rather than shutting down on a corrupt flush, just treat it as a full flush
657 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
658 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
659 "filled %zd=%#x",
660 mFlush, flush, front, rear,
661 (unsigned)mask, newFront, filled, (unsigned)filled);
662 newFront = rear;
663 }
664 mFlush = flush;
665 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
666 // There is no danger from a false positive, so err on the side of caution
667 if (true /*front != newFront*/) {
668 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
669 if (!(old & CBLK_FUTEX_WAKE)) {
670 (void) syscall(__NR_futex, &cblk->mFutex,
671 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
672 }
673 }
674 mFlushed += (newFront - front) & mask;
675 }
676}
677
678__attribute__((no_sanitize("integer")))
Glenn Kasten2e422c42013-10-18 13:00:29 -0700679status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800680{
Andy Hung9c64f342017-08-02 18:10:00 -0700681 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0,
682 "%s: null or zero frame buffer, buffer:%p", __func__, buffer);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800683 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700684 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800685 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700686 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800687 audio_track_cblk_t* cblk = mCblk;
688 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
689 // or use previous cached value from framesReady(), with added barrier if it omits.
690 int32_t front;
691 int32_t rear;
692 // See notes on barriers at ClientProxy::obtainBuffer()
693 if (mIsOut) {
Phil Burk4bb650b2016-09-09 12:11:17 -0700694 flushBufferIfNeeded(); // might modify mFront
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800695 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100696 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800697 } else {
698 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
699 rear = cblk->u.mStreaming.mRear;
700 }
701 ssize_t filled = rear - front;
702 // pipe should not already be overfull
703 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800704 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
705 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800706 mIsShutdown = true;
707 }
708 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700709 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800710 }
711 // don't allow filling pipe beyond the nominal size
712 size_t availToServer;
713 if (mIsOut) {
714 availToServer = filled;
715 mAvailToClient = mFrameCount - filled;
716 } else {
717 availToServer = mFrameCount - filled;
718 mAvailToClient = filled;
719 }
720 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
721 size_t part1;
722 if (mIsOut) {
723 front &= mFrameCountP2 - 1;
724 part1 = mFrameCountP2 - front;
725 } else {
726 rear &= mFrameCountP2 - 1;
727 part1 = mFrameCountP2 - rear;
728 }
729 if (part1 > availToServer) {
730 part1 = availToServer;
731 }
732 size_t ask = buffer->mFrameCount;
733 if (part1 > ask) {
734 part1 = ask;
735 }
736 // is assignment redundant in some cases?
737 buffer->mFrameCount = part1;
738 buffer->mRaw = part1 > 0 ?
739 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
740 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700741 // After flush(), allow releaseBuffer() on a previously obtained buffer;
742 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
743 if (!ackFlush) {
744 mUnreleased = part1;
745 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800746 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700747 }
748no_init:
749 buffer->mFrameCount = 0;
750 buffer->mRaw = NULL;
751 buffer->mNonContig = 0;
752 mUnreleased = 0;
753 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800754}
755
ilewis926b82f2016-03-29 14:50:36 -0700756__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800757void ServerProxy::releaseBuffer(Buffer* buffer)
758{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700759 LOG_ALWAYS_FATAL_IF(buffer == NULL);
760 size_t stepCount = buffer->mFrameCount;
761 if (stepCount == 0 || mIsShutdown) {
762 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800763 buffer->mFrameCount = 0;
764 buffer->mRaw = NULL;
765 buffer->mNonContig = 0;
766 return;
767 }
Andy Hung9c64f342017-08-02 18:10:00 -0700768 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount),
769 "%s: mUnreleased out of range, "
770 "!(stepCount:%zu <= mUnreleased:%zu <= mFrameCount:%zu)",
771 __func__, stepCount, mUnreleased, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800772 mUnreleased -= stepCount;
773 audio_track_cblk_t* cblk = mCblk;
774 if (mIsOut) {
775 int32_t front = cblk->u.mStreaming.mFront;
776 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
777 } else {
778 int32_t rear = cblk->u.mStreaming.mRear;
779 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
780 }
781
Glenn Kasten844f88c2014-05-09 13:38:09 -0700782 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800783 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800784
785 size_t half = mFrameCount / 2;
786 if (half == 0) {
787 half = 1;
788 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800789 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800790 if (minimum == 0) {
791 minimum = mIsOut ? half : 1;
792 } else if (minimum > half) {
793 minimum = half;
794 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700795 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700796 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700797 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700798 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
799 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700800 (void) syscall(__NR_futex, &cblk->mFutex,
801 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800802 }
803 }
804
805 buffer->mFrameCount = 0;
806 buffer->mRaw = NULL;
807 buffer->mNonContig = 0;
808}
809
810// ---------------------------------------------------------------------------
811
ilewis926b82f2016-03-29 14:50:36 -0700812__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800813size_t AudioTrackServerProxy::framesReady()
814{
815 LOG_ALWAYS_FATAL_IF(!mIsOut);
816
817 if (mIsShutdown) {
818 return 0;
819 }
820 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100821
822 int32_t flush = cblk->u.mStreaming.mFlush;
823 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700824 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100825 return mFrameCount;
826 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827 // the acquire might not be necessary since not doing a subsequent read
828 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
829 ssize_t filled = rear - cblk->u.mStreaming.mFront;
830 // pipe should not already be overfull
831 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten1bfe09a2017-02-21 13:05:56 -0800832 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); shutting down",
833 filled, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800834 mIsShutdown = true;
835 return 0;
836 }
837 // cache this value for later use by obtainBuffer(), with added barrier
838 // and racy if called by normal mixer thread
839 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
840 return filled;
841}
842
Eric Laurentbfb1b832013-01-07 09:53:42 -0800843bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700844 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800845 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700846 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800847 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700848 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700849 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800850 }
851 return old;
852}
853
Glenn Kasten82aaf942013-07-17 16:05:07 -0700854void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
855{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700856 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800857 if (frameCount > 0) {
858 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700859
Phil Burk2812d9e2016-01-04 10:34:30 -0800860 if (!mUnderrunning) { // start of underrun?
861 mUnderrunCount++;
862 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
863 mUnderrunning = true;
864 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
865 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
866 }
867
868 // FIXME also wake futex so that underrun is noticed more quickly
869 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
870 } else {
871 ALOGV_IF(mUnderrunning,
872 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
873 frameCount, cblk->u.mStreaming.mUnderrunFrames);
874 mUnderrunning = false; // so we can detect the next edge
875 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700876}
877
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700878AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700879{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700880 mPlaybackRateObserver.poll(mPlaybackRate);
881 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700882}
883
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800884// ---------------------------------------------------------------------------
885
886StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
887 size_t frameCount, size_t frameSize)
888 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800889 mObserver(&cblk->u.mStatic.mSingleStateQueue),
890 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800891 mFramesReadySafe(frameCount), mFramesReady(frameCount),
892 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800893{
Andy Hung9b461582014-12-01 17:56:29 -0800894 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800895}
896
897void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
898{
899 mFramesReadyIsCalledByMultipleThreads = true;
900}
901
902size_t StaticAudioTrackServerProxy::framesReady()
903{
Andy Hungcb2129b2014-11-11 12:17:22 -0800904 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800905 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800906 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800907 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800908 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800909}
910
Andy Hung9b461582014-12-01 17:56:29 -0800911status_t StaticAudioTrackServerProxy::updateStateWithLoop(
912 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800913{
Andy Hung9b461582014-12-01 17:56:29 -0800914 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800915 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800916 const size_t loopStart = update.mLoopStart;
917 const size_t loopEnd = update.mLoopEnd;
918 size_t position = localState->mPosition;
919 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800920 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800921 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800922 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
923 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800924 // If the current position is greater than the end of the loop
925 // we "wrap" to the loop start. This might cause an audible pop.
926 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800927 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800928 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800929 valid = true;
930 }
931 }
Andy Hung9b461582014-12-01 17:56:29 -0800932 if (!valid || position > mFrameCount) {
933 return NO_INIT;
934 }
935 localState->mPosition = position;
936 localState->mLoopCount = update.mLoopCount;
937 localState->mLoopEnd = loopEnd;
938 localState->mLoopStart = loopStart;
939 localState->mLoopSequence = update.mLoopSequence;
940 }
941 return OK;
942}
943
944status_t StaticAudioTrackServerProxy::updateStateWithPosition(
945 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
946{
947 if (localState->mPositionSequence != update.mPositionSequence) {
948 if (update.mPosition > mFrameCount) {
949 return NO_INIT;
950 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
951 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
952 }
953 localState->mPosition = update.mPosition;
954 localState->mPositionSequence = update.mPositionSequence;
955 }
956 return OK;
957}
958
959ssize_t StaticAudioTrackServerProxy::pollPosition()
960{
961 StaticAudioTrackState state;
962 if (mObserver.poll(state)) {
963 StaticAudioTrackState trystate = mState;
964 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700965 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800966
967 if (diffSeq < 0) {
968 result = updateStateWithLoop(&trystate, state) == OK &&
969 updateStateWithPosition(&trystate, state) == OK;
970 } else {
971 result = updateStateWithPosition(&trystate, state) == OK &&
972 updateStateWithLoop(&trystate, state) == OK;
973 }
974 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800975 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800976 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800977 ALOGE("%s client pushed an invalid state, shutting down", __func__);
978 mIsShutdown = true;
979 return (ssize_t) NO_INIT;
980 }
Andy Hung9b461582014-12-01 17:56:29 -0800981 mState = trystate;
982 if (mState.mLoopCount == -1) {
983 mFramesReady = INT64_MAX;
984 } else if (mState.mLoopCount == 0) {
985 mFramesReady = mFrameCount - mState.mPosition;
986 } else if (mState.mLoopCount > 0) {
987 // TODO: Later consider fixing overflow, but does not seem needed now
988 // as will not overflow if loopStart and loopEnd are Java "ints".
989 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
990 + mFrameCount - mState.mPosition;
991 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800992 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800993 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800994 StaticAudioTrackPosLoop posLoop;
995
996 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
997 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
998 mPosLoopMutator.push(posLoop);
999 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001000 }
Andy Hung9b461582014-12-01 17:56:29 -08001001 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001002}
1003
Andy Hung954ca452015-09-09 14:39:02 -07001004status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001005{
1006 if (mIsShutdown) {
1007 buffer->mFrameCount = 0;
1008 buffer->mRaw = NULL;
1009 buffer->mNonContig = 0;
1010 mUnreleased = 0;
1011 return NO_INIT;
1012 }
1013 ssize_t positionOrStatus = pollPosition();
1014 if (positionOrStatus < 0) {
1015 buffer->mFrameCount = 0;
1016 buffer->mRaw = NULL;
1017 buffer->mNonContig = 0;
1018 mUnreleased = 0;
1019 return (status_t) positionOrStatus;
1020 }
1021 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -08001022 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001023 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -08001024 if (position < end) {
1025 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026 size_t wanted = buffer->mFrameCount;
1027 if (avail < wanted) {
1028 buffer->mFrameCount = avail;
1029 } else {
1030 avail = wanted;
1031 }
1032 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1033 } else {
1034 avail = 0;
1035 buffer->mFrameCount = 0;
1036 buffer->mRaw = NULL;
1037 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001038 // As mFramesReady is the total remaining frames in the static audio track,
1039 // it is always larger or equal to avail.
Andy Hung9c64f342017-08-02 18:10:00 -07001040 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail,
1041 "%s: mFramesReady out of range, mFramesReady:%lld < avail:%zu",
1042 __func__, (long long)mFramesReady, avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001043 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001044 if (!ackFlush) {
1045 mUnreleased = avail;
1046 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001047 return NO_ERROR;
1048}
1049
1050void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1051{
1052 size_t stepCount = buffer->mFrameCount;
Andy Hung9c64f342017-08-02 18:10:00 -07001053 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady),
1054 "%s: stepCount out of range, "
1055 "!(stepCount:%zu <= mFramesReady:%lld)",
1056 __func__, stepCount, (long long)mFramesReady);
1057 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased),
1058 "%s: stepCount out of range, "
1059 "!(stepCount:%zu <= mUnreleased:%zu)",
1060 __func__, stepCount, mUnreleased);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001061 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001062 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001063 buffer->mRaw = NULL;
1064 buffer->mNonContig = 0;
1065 return;
1066 }
1067 mUnreleased -= stepCount;
1068 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001069 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001070 size_t newPosition = position + stepCount;
1071 int32_t setFlags = 0;
1072 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001073 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1074 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001075 newPosition = mFrameCount;
1076 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001077 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001078 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001079 setFlags = CBLK_LOOP_CYCLE;
1080 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001081 setFlags = CBLK_LOOP_FINAL;
1082 }
1083 }
1084 if (newPosition == mFrameCount) {
1085 setFlags |= CBLK_BUFFER_END;
1086 }
Andy Hung9b461582014-12-01 17:56:29 -08001087 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001088 if (mFramesReady != INT64_MAX) {
1089 mFramesReady -= stepCount;
1090 }
1091 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001092
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001093 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001094 mReleased += stepCount;
1095
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001096 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001097 StaticAudioTrackPosLoop posLoop;
1098 posLoop.mBufferPosition = mState.mPosition;
1099 posLoop.mLoopCount = mState.mLoopCount;
1100 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001101 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001102 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001103 // this would be a good place to wake a futex
1104 }
1105
1106 buffer->mFrameCount = 0;
1107 buffer->mRaw = NULL;
1108 buffer->mNonContig = 0;
1109}
1110
Phil Burk2812d9e2016-01-04 10:34:30 -08001111void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001112{
1113 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1114 // we don't have a location to count underrun frames. The underrun frame counter
1115 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1116 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1117
1118 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001119 if (frameCount > 0) {
1120 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1121 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001122}
1123
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001124// ---------------------------------------------------------------------------
1125
Glenn Kastena8190fc2012-12-03 17:06:56 -08001126} // namespace android