blob: 9d5d9969b54d53be512fa4da17ec9b866a7c4af1 [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()
Glenn Kasten74935e42013-12-19 08:56:45 -080049 : mServer(0), mFutex(0), mMinimum(0),
Glenn Kastenc56f3422014-03-21 17:53:17 -070050 mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0), mFlags(0)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080051{
52 memset(&u, 0, sizeof(u));
53}
54
55// ---------------------------------------------------------------------------
56
57Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
58 bool isOut, bool clientInServer)
59 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
60 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
Glenn Kasten7db7df02013-06-25 16:13:23 -070061 mIsShutdown(false), mUnreleased(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080062{
63}
64
Glenn Kasten9f80dd22012-12-18 15:57:32 -080065// ---------------------------------------------------------------------------
66
67ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
68 size_t frameSize, bool isOut, bool clientInServer)
69 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer), mEpoch(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080070{
Glenn Kastena8190fc2012-12-03 17:06:56 -080071}
72
Glenn Kasten9f80dd22012-12-18 15:57:32 -080073const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
74const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
75
76#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
77
78// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
79// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
80// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
81// order of minutes.
82#define MAX_SEC 5
83
84status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
85 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -080086{
Glenn Kasten7db7df02013-06-25 16:13:23 -070087 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080088 struct timespec total; // total elapsed time spent waiting
89 total.tv_sec = 0;
90 total.tv_nsec = 0;
91 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -080092
Glenn Kasten9f80dd22012-12-18 15:57:32 -080093 status_t status;
94 enum {
95 TIMEOUT_ZERO, // requested == NULL || *requested == 0
96 TIMEOUT_INFINITE, // *requested == infinity
97 TIMEOUT_FINITE, // 0 < *requested < infinity
98 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
99 } timeout;
100 if (requested == NULL) {
101 timeout = TIMEOUT_ZERO;
102 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
103 timeout = TIMEOUT_ZERO;
104 } else if (requested->tv_sec == INT_MAX) {
105 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800106 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800107 timeout = TIMEOUT_FINITE;
108 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
109 measure = true;
110 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800111 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800112 struct timespec before;
113 bool beforeIsValid = false;
114 audio_track_cblk_t* cblk = mCblk;
115 bool ignoreInitialPendingInterrupt = true;
116 // check for shared memory corruption
117 if (mIsShutdown) {
118 status = NO_INIT;
119 goto end;
120 }
121 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700122 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800123 // check for track invalidation by server, or server death detection
124 if (flags & CBLK_INVALID) {
125 ALOGV("Track invalidated");
126 status = DEAD_OBJECT;
127 goto end;
128 }
129 // check for obtainBuffer interrupted by client
130 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
131 ALOGV("obtainBuffer() interrupted by client");
132 status = -EINTR;
133 goto end;
134 }
135 ignoreInitialPendingInterrupt = false;
136 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
137 int32_t front;
138 int32_t rear;
139 if (mIsOut) {
140 // The barrier following the read of mFront is probably redundant.
141 // We're about to perform a conditional branch based on 'filled',
142 // which will force the processor to observe the read of mFront
143 // prior to allowing data writes starting at mRaw.
144 // However, the processor may support speculative execution,
145 // and be unable to undo speculative writes into shared memory.
146 // The barrier will prevent such speculative execution.
147 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
148 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800149 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800150 // On the other hand, this barrier is required.
151 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
152 front = cblk->u.mStreaming.mFront;
153 }
154 ssize_t filled = rear - front;
155 // pipe should not be overfull
156 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700157 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700158 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700159 "shutting down", filled, mFrameCount);
160 mIsShutdown = true;
161 status = NO_INIT;
162 goto end;
163 }
164 // for input, sync up on overrun
165 filled = 0;
166 cblk->u.mStreaming.mFront = rear;
167 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800168 }
169 // don't allow filling pipe beyond the nominal size
170 size_t avail = mIsOut ? mFrameCount - filled : filled;
171 if (avail > 0) {
172 // 'avail' may be non-contiguous, so return only the first contiguous chunk
173 size_t part1;
174 if (mIsOut) {
175 rear &= mFrameCountP2 - 1;
176 part1 = mFrameCountP2 - rear;
177 } else {
178 front &= mFrameCountP2 - 1;
179 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800180 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800181 if (part1 > avail) {
182 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800183 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800184 if (part1 > buffer->mFrameCount) {
185 part1 = buffer->mFrameCount;
186 }
187 buffer->mFrameCount = part1;
188 buffer->mRaw = part1 > 0 ?
189 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
190 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700191 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800192 status = NO_ERROR;
193 break;
194 }
195 struct timespec remaining;
196 const struct timespec *ts;
197 switch (timeout) {
198 case TIMEOUT_ZERO:
199 status = WOULD_BLOCK;
200 goto end;
201 case TIMEOUT_INFINITE:
202 ts = NULL;
203 break;
204 case TIMEOUT_FINITE:
205 timeout = TIMEOUT_CONTINUE;
206 if (MAX_SEC == 0) {
207 ts = requested;
208 break;
209 }
210 // fall through
211 case TIMEOUT_CONTINUE:
212 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
213 if (!measure || requested->tv_sec < total.tv_sec ||
214 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
215 status = TIMED_OUT;
216 goto end;
217 }
218 remaining.tv_sec = requested->tv_sec - total.tv_sec;
219 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
220 remaining.tv_nsec += 1000000000;
221 remaining.tv_sec++;
222 }
223 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
224 remaining.tv_sec = MAX_SEC;
225 remaining.tv_nsec = 0;
226 }
227 ts = &remaining;
228 break;
229 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800230 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800231 ts = NULL;
232 break;
233 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700234 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
235 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800236 if (measure && !beforeIsValid) {
237 clock_gettime(CLOCK_MONOTONIC, &before);
238 beforeIsValid = true;
239 }
Elliott Hughesee499292014-05-21 17:55:51 -0700240 errno = 0;
241 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700242 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800243 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800244 // update total elapsed time spent waiting
245 if (measure) {
246 struct timespec after;
247 clock_gettime(CLOCK_MONOTONIC, &after);
248 total.tv_sec += after.tv_sec - before.tv_sec;
249 long deltaNs = after.tv_nsec - before.tv_nsec;
250 if (deltaNs < 0) {
251 deltaNs += 1000000000;
252 total.tv_sec--;
253 }
254 if ((total.tv_nsec += deltaNs) >= 1000000000) {
255 total.tv_nsec -= 1000000000;
256 total.tv_sec++;
257 }
258 before = after;
259 beforeIsValid = true;
260 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800261 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700262 case 0: // normal wakeup by server, or by binderDied()
263 case EWOULDBLOCK: // benign race condition with server
264 case EINTR: // wait was interrupted by signal or other spurious wakeup
265 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700266 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800267 break;
268 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800269 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700270 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800271 goto end;
272 }
273 }
274 }
275
276end:
277 if (status != NO_ERROR) {
278 buffer->mFrameCount = 0;
279 buffer->mRaw = NULL;
280 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700281 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800282 }
283 if (elapsed != NULL) {
284 *elapsed = total;
285 }
286 if (requested == NULL) {
287 requested = &kNonBlocking;
288 }
289 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100290 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
291 requested->tv_sec, requested->tv_nsec / 1000000,
292 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800293 }
294 return status;
295}
296
297void ClientProxy::releaseBuffer(Buffer* buffer)
298{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700299 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800300 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700301 if (stepCount == 0 || mIsShutdown) {
302 // prevent accidental re-use of buffer
303 buffer->mFrameCount = 0;
304 buffer->mRaw = NULL;
305 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800306 return;
307 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700308 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
309 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800310 audio_track_cblk_t* cblk = mCblk;
311 // Both of these barriers are required
312 if (mIsOut) {
313 int32_t rear = cblk->u.mStreaming.mRear;
314 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
315 } else {
316 int32_t front = cblk->u.mStreaming.mFront;
317 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
318 }
319}
320
321void ClientProxy::binderDied()
322{
323 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700324 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900325 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800326 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700327 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
328 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800329 }
330}
331
332void ClientProxy::interrupt()
333{
334 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700335 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900336 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700337 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
338 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800339 }
340}
341
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700342__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800343size_t ClientProxy::getMisalignment()
344{
345 audio_track_cblk_t* cblk = mCblk;
346 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
347 (mFrameCountP2 - 1);
348}
349
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700350size_t ClientProxy::getFramesFilled() {
351 audio_track_cblk_t* cblk = mCblk;
352 int32_t front;
353 int32_t rear;
354
355 if (mIsOut) {
356 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
357 rear = cblk->u.mStreaming.mRear;
358 } else {
359 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
360 front = cblk->u.mStreaming.mFront;
361 }
362 ssize_t filled = rear - front;
363 // pipe should not be overfull
364 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700365 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700366 return 0;
367 }
368 return (size_t)filled;
369}
370
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800371// ---------------------------------------------------------------------------
372
373void AudioTrackClientProxy::flush()
374{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700375 // This works for mFrameCountP2 <= 2^30
376 size_t increment = mFrameCountP2 << 1;
377 size_t mask = increment - 1;
378 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700379 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
380 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
381 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700382 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
383 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
384 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800385}
386
Eric Laurentbfb1b832013-01-07 09:53:42 -0800387bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700388 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800389}
390
391bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700392 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800393}
394
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100395status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
396{
397 struct timespec total; // total elapsed time spent waiting
398 total.tv_sec = 0;
399 total.tv_nsec = 0;
400 audio_track_cblk_t* cblk = mCblk;
401 status_t status;
402 enum {
403 TIMEOUT_ZERO, // requested == NULL || *requested == 0
404 TIMEOUT_INFINITE, // *requested == infinity
405 TIMEOUT_FINITE, // 0 < *requested < infinity
406 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
407 } timeout;
408 if (requested == NULL) {
409 timeout = TIMEOUT_ZERO;
410 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
411 timeout = TIMEOUT_ZERO;
412 } else if (requested->tv_sec == INT_MAX) {
413 timeout = TIMEOUT_INFINITE;
414 } else {
415 timeout = TIMEOUT_FINITE;
416 }
417 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700418 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100419 // check for track invalidation by server, or server death detection
420 if (flags & CBLK_INVALID) {
421 ALOGV("Track invalidated");
422 status = DEAD_OBJECT;
423 goto end;
424 }
425 if (flags & CBLK_STREAM_END_DONE) {
426 ALOGV("stream end received");
427 status = NO_ERROR;
428 goto end;
429 }
430 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100431 if (flags & CBLK_INTERRUPT) {
432 ALOGV("waitStreamEndDone() interrupted by client");
433 status = -EINTR;
434 goto end;
435 }
436 struct timespec remaining;
437 const struct timespec *ts;
438 switch (timeout) {
439 case TIMEOUT_ZERO:
440 status = WOULD_BLOCK;
441 goto end;
442 case TIMEOUT_INFINITE:
443 ts = NULL;
444 break;
445 case TIMEOUT_FINITE:
446 timeout = TIMEOUT_CONTINUE;
447 if (MAX_SEC == 0) {
448 ts = requested;
449 break;
450 }
451 // fall through
452 case TIMEOUT_CONTINUE:
453 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
454 if (requested->tv_sec < total.tv_sec ||
455 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
456 status = TIMED_OUT;
457 goto end;
458 }
459 remaining.tv_sec = requested->tv_sec - total.tv_sec;
460 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
461 remaining.tv_nsec += 1000000000;
462 remaining.tv_sec++;
463 }
464 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
465 remaining.tv_sec = MAX_SEC;
466 remaining.tv_nsec = 0;
467 }
468 ts = &remaining;
469 break;
470 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800471 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100472 ts = NULL;
473 break;
474 }
475 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
476 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700477 errno = 0;
478 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100479 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700480 switch (errno) {
481 case 0: // normal wakeup by server, or by binderDied()
482 case EWOULDBLOCK: // benign race condition with server
483 case EINTR: // wait was interrupted by signal or other spurious wakeup
484 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100485 break;
486 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700487 status = errno;
488 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100489 goto end;
490 }
491 }
492 }
493
494end:
495 if (requested == NULL) {
496 requested = &kNonBlocking;
497 }
498 return status;
499}
500
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800501// ---------------------------------------------------------------------------
502
503StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
504 size_t frameCount, size_t frameSize)
505 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800506 mMutator(&cblk->u.mStatic.mSingleStateQueue),
507 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800508{
Andy Hung9b461582014-12-01 17:56:29 -0800509 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800510 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800511}
512
513void StaticAudioTrackClientProxy::flush()
514{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800515 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800516}
517
518void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
519{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800520 // This can only happen on a 64-bit client
521 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
522 // FIXME Should return an error status
523 return;
524 }
Andy Hung9b461582014-12-01 17:56:29 -0800525 mState.mLoopStart = (uint32_t) loopStart;
526 mState.mLoopEnd = (uint32_t) loopEnd;
527 mState.mLoopCount = loopCount;
528 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
529 // set patch-up variables until the mState is acknowledged by the ServerProxy.
530 // observed buffer position and loop count will freeze until then to give the
531 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800532 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800533 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800534 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
535 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800536 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800537 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800538 (void) mMutator.push(mState);
539}
540
541void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
542{
543 // This can only happen on a 64-bit client
544 if (position > UINT32_MAX) {
545 // FIXME Should return an error status
546 return;
547 }
548 mState.mPosition = (uint32_t) position;
549 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800550 // set patch-up variables until the mState is acknowledged by the ServerProxy.
551 // observed buffer position and loop count will freeze until then to give the
552 // illusion of a synchronous change.
553 if (mState.mLoopCount > 0) { // only check if loop count is changing
554 getBufferPositionAndLoopCount(NULL, NULL); // get last position
555 }
556 mPosLoop.mBufferPosition = position;
557 if (position >= mState.mLoopEnd) {
558 // no ongoing loop is possible if position is greater than loopEnd.
559 mPosLoop.mLoopCount = 0;
560 }
Andy Hung9b461582014-12-01 17:56:29 -0800561 (void) mMutator.push(mState);
562}
563
564void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
565 size_t loopEnd, int loopCount)
566{
567 setLoop(loopStart, loopEnd, loopCount);
568 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800569}
570
571size_t StaticAudioTrackClientProxy::getBufferPosition()
572{
Andy Hung4ede21d2014-12-12 15:37:34 -0800573 getBufferPositionAndLoopCount(NULL, NULL);
574 return mPosLoop.mBufferPosition;
575}
576
577void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
578 size_t *position, int *loopCount)
579{
580 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
581 if (mPosLoopObserver.poll(mPosLoop)) {
582 ; // a valid mPosLoop should be available if ackDone is true.
583 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800584 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800585 if (position != NULL) {
586 *position = mPosLoop.mBufferPosition;
587 }
588 if (loopCount != NULL) {
589 *loopCount = mPosLoop.mLoopCount;
590 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800591}
592
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800593// ---------------------------------------------------------------------------
594
595ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
596 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700597 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Glenn Kastence8828a2013-09-16 18:07:38 -0700598 mAvailToClient(0), mFlush(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800599{
Glenn Kastena8190fc2012-12-03 17:06:56 -0800600}
601
Glenn Kasten2e422c42013-10-18 13:00:29 -0700602status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800603{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700604 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800605 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700606 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800607 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700608 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 audio_track_cblk_t* cblk = mCblk;
610 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
611 // or use previous cached value from framesReady(), with added barrier if it omits.
612 int32_t front;
613 int32_t rear;
614 // See notes on barriers at ClientProxy::obtainBuffer()
615 if (mIsOut) {
616 int32_t flush = cblk->u.mStreaming.mFlush;
617 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100618 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800619 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700620 // effectively obtain then release whatever is in the buffer
Andy Hunga2d75cd2015-07-15 17:04:20 -0700621 const size_t overflowBit = mFrameCountP2 << 1;
622 const size_t mask = overflowBit - 1;
Glenn Kasten20f51b12014-10-30 10:43:19 -0700623 int32_t newFront = (front & ~mask) | (flush & mask);
624 ssize_t filled = rear - newFront;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700625 if (filled >= (ssize_t)overflowBit) {
626 // front and rear offsets span the overflow bit of the p2 mask
627 // so rebasing newFront on the front offset is off by the overflow bit.
628 // adjust newFront to match rear offset.
Glenn Kastendbd0f3c2015-07-17 11:04:04 -0700629 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hunga2d75cd2015-07-15 17:04:20 -0700630 newFront += overflowBit;
631 filled -= overflowBit;
632 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700633 // Rather than shutting down on a corrupt flush, just treat it as a full flush
634 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800635 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
Lajos Molnarf1063e22015-04-17 15:19:42 -0700636 "filled %zd=%#x",
637 mFlush, flush, front, rear,
638 (unsigned)mask, newFront, filled, (unsigned)filled);
Glenn Kasten20f51b12014-10-30 10:43:19 -0700639 newFront = rear;
640 }
641 mFlush = flush;
642 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
643 // There is no danger from a false positive, so err on the side of caution
644 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100645 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
646 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700647 (void) syscall(__NR_futex, &cblk->mFutex,
648 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100649 }
650 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700651 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800652 }
653 } else {
654 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
655 rear = cblk->u.mStreaming.mRear;
656 }
657 ssize_t filled = rear - front;
658 // pipe should not already be overfull
659 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700660 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800661 mIsShutdown = true;
662 }
663 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700664 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800665 }
666 // don't allow filling pipe beyond the nominal size
667 size_t availToServer;
668 if (mIsOut) {
669 availToServer = filled;
670 mAvailToClient = mFrameCount - filled;
671 } else {
672 availToServer = mFrameCount - filled;
673 mAvailToClient = filled;
674 }
675 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
676 size_t part1;
677 if (mIsOut) {
678 front &= mFrameCountP2 - 1;
679 part1 = mFrameCountP2 - front;
680 } else {
681 rear &= mFrameCountP2 - 1;
682 part1 = mFrameCountP2 - rear;
683 }
684 if (part1 > availToServer) {
685 part1 = availToServer;
686 }
687 size_t ask = buffer->mFrameCount;
688 if (part1 > ask) {
689 part1 = ask;
690 }
691 // is assignment redundant in some cases?
692 buffer->mFrameCount = part1;
693 buffer->mRaw = part1 > 0 ?
694 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
695 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700696 // After flush(), allow releaseBuffer() on a previously obtained buffer;
697 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
698 if (!ackFlush) {
699 mUnreleased = part1;
700 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800701 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700702 }
703no_init:
704 buffer->mFrameCount = 0;
705 buffer->mRaw = NULL;
706 buffer->mNonContig = 0;
707 mUnreleased = 0;
708 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800709}
710
711void ServerProxy::releaseBuffer(Buffer* buffer)
712{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700713 LOG_ALWAYS_FATAL_IF(buffer == NULL);
714 size_t stepCount = buffer->mFrameCount;
715 if (stepCount == 0 || mIsShutdown) {
716 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800717 buffer->mFrameCount = 0;
718 buffer->mRaw = NULL;
719 buffer->mNonContig = 0;
720 return;
721 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700722 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800723 mUnreleased -= stepCount;
724 audio_track_cblk_t* cblk = mCblk;
725 if (mIsOut) {
726 int32_t front = cblk->u.mStreaming.mFront;
727 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
728 } else {
729 int32_t rear = cblk->u.mStreaming.mRear;
730 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
731 }
732
Glenn Kasten844f88c2014-05-09 13:38:09 -0700733 cblk->mServer += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800734
735 size_t half = mFrameCount / 2;
736 if (half == 0) {
737 half = 1;
738 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800739 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800740 if (minimum == 0) {
741 minimum = mIsOut ? half : 1;
742 } else if (minimum > half) {
743 minimum = half;
744 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700745 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700746 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700747 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700748 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
749 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700750 (void) syscall(__NR_futex, &cblk->mFutex,
751 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800752 }
753 }
754
755 buffer->mFrameCount = 0;
756 buffer->mRaw = NULL;
757 buffer->mNonContig = 0;
758}
759
760// ---------------------------------------------------------------------------
761
762size_t AudioTrackServerProxy::framesReady()
763{
764 LOG_ALWAYS_FATAL_IF(!mIsOut);
765
766 if (mIsShutdown) {
767 return 0;
768 }
769 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100770
771 int32_t flush = cblk->u.mStreaming.mFlush;
772 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700773 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100774 return mFrameCount;
775 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800776 // the acquire might not be necessary since not doing a subsequent read
777 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
778 ssize_t filled = rear - cblk->u.mStreaming.mFront;
779 // pipe should not already be overfull
780 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700781 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800782 mIsShutdown = true;
783 return 0;
784 }
785 // cache this value for later use by obtainBuffer(), with added barrier
786 // and racy if called by normal mixer thread
787 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
788 return filled;
789}
790
Eric Laurentbfb1b832013-01-07 09:53:42 -0800791bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700792 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800793 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700794 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800795 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700796 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700797 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800798 }
799 return old;
800}
801
Glenn Kasten82aaf942013-07-17 16:05:07 -0700802void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
803{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700804 audio_track_cblk_t* cblk = mCblk;
805 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700806
807 // FIXME also wake futex so that underrun is noticed more quickly
Glenn Kasten844f88c2014-05-09 13:38:09 -0700808 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700809}
810
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700811AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700812{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700813 mPlaybackRateObserver.poll(mPlaybackRate);
814 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700815}
816
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800817// ---------------------------------------------------------------------------
818
819StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
820 size_t frameCount, size_t frameSize)
821 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800822 mObserver(&cblk->u.mStatic.mSingleStateQueue),
823 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800824 mFramesReadySafe(frameCount), mFramesReady(frameCount),
825 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800826{
Andy Hung9b461582014-12-01 17:56:29 -0800827 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800828}
829
830void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
831{
832 mFramesReadyIsCalledByMultipleThreads = true;
833}
834
835size_t StaticAudioTrackServerProxy::framesReady()
836{
Andy Hungcb2129b2014-11-11 12:17:22 -0800837 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800838 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800839 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800841 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800842}
843
Andy Hung9b461582014-12-01 17:56:29 -0800844status_t StaticAudioTrackServerProxy::updateStateWithLoop(
845 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800846{
Andy Hung9b461582014-12-01 17:56:29 -0800847 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800848 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800849 const size_t loopStart = update.mLoopStart;
850 const size_t loopEnd = update.mLoopEnd;
851 size_t position = localState->mPosition;
852 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800853 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800854 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800855 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
856 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800857 // If the current position is greater than the end of the loop
858 // we "wrap" to the loop start. This might cause an audible pop.
859 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800860 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800861 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800862 valid = true;
863 }
864 }
Andy Hung9b461582014-12-01 17:56:29 -0800865 if (!valid || position > mFrameCount) {
866 return NO_INIT;
867 }
868 localState->mPosition = position;
869 localState->mLoopCount = update.mLoopCount;
870 localState->mLoopEnd = loopEnd;
871 localState->mLoopStart = loopStart;
872 localState->mLoopSequence = update.mLoopSequence;
873 }
874 return OK;
875}
876
877status_t StaticAudioTrackServerProxy::updateStateWithPosition(
878 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
879{
880 if (localState->mPositionSequence != update.mPositionSequence) {
881 if (update.mPosition > mFrameCount) {
882 return NO_INIT;
883 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
884 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
885 }
886 localState->mPosition = update.mPosition;
887 localState->mPositionSequence = update.mPositionSequence;
888 }
889 return OK;
890}
891
892ssize_t StaticAudioTrackServerProxy::pollPosition()
893{
894 StaticAudioTrackState state;
895 if (mObserver.poll(state)) {
896 StaticAudioTrackState trystate = mState;
897 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700898 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800899
900 if (diffSeq < 0) {
901 result = updateStateWithLoop(&trystate, state) == OK &&
902 updateStateWithPosition(&trystate, state) == OK;
903 } else {
904 result = updateStateWithPosition(&trystate, state) == OK &&
905 updateStateWithLoop(&trystate, state) == OK;
906 }
907 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800908 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800909 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800910 ALOGE("%s client pushed an invalid state, shutting down", __func__);
911 mIsShutdown = true;
912 return (ssize_t) NO_INIT;
913 }
Andy Hung9b461582014-12-01 17:56:29 -0800914 mState = trystate;
915 if (mState.mLoopCount == -1) {
916 mFramesReady = INT64_MAX;
917 } else if (mState.mLoopCount == 0) {
918 mFramesReady = mFrameCount - mState.mPosition;
919 } else if (mState.mLoopCount > 0) {
920 // TODO: Later consider fixing overflow, but does not seem needed now
921 // as will not overflow if loopStart and loopEnd are Java "ints".
922 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
923 + mFrameCount - mState.mPosition;
924 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800925 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800926 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800927 StaticAudioTrackPosLoop posLoop;
928
929 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
930 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
931 mPosLoopMutator.push(posLoop);
932 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800933 }
Andy Hung9b461582014-12-01 17:56:29 -0800934 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800935}
936
Andy Hung954ca452015-09-09 14:39:02 -0700937status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800938{
939 if (mIsShutdown) {
940 buffer->mFrameCount = 0;
941 buffer->mRaw = NULL;
942 buffer->mNonContig = 0;
943 mUnreleased = 0;
944 return NO_INIT;
945 }
946 ssize_t positionOrStatus = pollPosition();
947 if (positionOrStatus < 0) {
948 buffer->mFrameCount = 0;
949 buffer->mRaw = NULL;
950 buffer->mNonContig = 0;
951 mUnreleased = 0;
952 return (status_t) positionOrStatus;
953 }
954 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800955 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800956 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800957 if (position < end) {
958 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800959 size_t wanted = buffer->mFrameCount;
960 if (avail < wanted) {
961 buffer->mFrameCount = avail;
962 } else {
963 avail = wanted;
964 }
965 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
966 } else {
967 avail = 0;
968 buffer->mFrameCount = 0;
969 buffer->mRaw = NULL;
970 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800971 // As mFramesReady is the total remaining frames in the static audio track,
972 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -0800973 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -0800974 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -0700975 if (!ackFlush) {
976 mUnreleased = avail;
977 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800978 return NO_ERROR;
979}
980
981void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
982{
983 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -0800984 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -0700985 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800986 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700987 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800988 buffer->mRaw = NULL;
989 buffer->mNonContig = 0;
990 return;
991 }
992 mUnreleased -= stepCount;
993 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -0800994 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800995 size_t newPosition = position + stepCount;
996 int32_t setFlags = 0;
997 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800998 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
999 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001000 newPosition = mFrameCount;
1001 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001002 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001003 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001004 setFlags = CBLK_LOOP_CYCLE;
1005 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001006 setFlags = CBLK_LOOP_FINAL;
1007 }
1008 }
1009 if (newPosition == mFrameCount) {
1010 setFlags |= CBLK_BUFFER_END;
1011 }
Andy Hung9b461582014-12-01 17:56:29 -08001012 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001013 if (mFramesReady != INT64_MAX) {
1014 mFramesReady -= stepCount;
1015 }
1016 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001017
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001018 cblk->mServer += stepCount;
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001019 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001020 StaticAudioTrackPosLoop posLoop;
1021 posLoop.mBufferPosition = mState.mPosition;
1022 posLoop.mLoopCount = mState.mLoopCount;
1023 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001024 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001025 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026 // this would be a good place to wake a futex
1027 }
1028
1029 buffer->mFrameCount = 0;
1030 buffer->mRaw = NULL;
1031 buffer->mNonContig = 0;
1032}
1033
Glenn Kasten7c7be1e2013-12-19 16:34:04 -08001034void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount __unused)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001035{
1036 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1037 // we don't have a location to count underrun frames. The underrun frame counter
1038 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1039 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1040
1041 // FIXME also wake futex so that underrun is noticed more quickly
1042 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1043}
1044
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001045// ---------------------------------------------------------------------------
1046
Glenn Kastena8190fc2012-12-03 17:06:56 -08001047} // namespace android