blob: c44cdeeac760252f8fd5957a768a2c0675a06209 [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) {
41 int32_t diff = self - other;
42 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);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800243 // update total elapsed time spent waiting
244 if (measure) {
245 struct timespec after;
246 clock_gettime(CLOCK_MONOTONIC, &after);
247 total.tv_sec += after.tv_sec - before.tv_sec;
248 long deltaNs = after.tv_nsec - before.tv_nsec;
249 if (deltaNs < 0) {
250 deltaNs += 1000000000;
251 total.tv_sec--;
252 }
253 if ((total.tv_nsec += deltaNs) >= 1000000000) {
254 total.tv_nsec -= 1000000000;
255 total.tv_sec++;
256 }
257 before = after;
258 beforeIsValid = true;
259 }
Elliott Hughesee499292014-05-21 17:55:51 -0700260 switch (errno) {
261 case 0: // normal wakeup by server, or by binderDied()
262 case EWOULDBLOCK: // benign race condition with server
263 case EINTR: // wait was interrupted by signal or other spurious wakeup
264 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700265 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800266 break;
267 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700268 status = errno;
269 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800270 goto end;
271 }
272 }
273 }
274
275end:
276 if (status != NO_ERROR) {
277 buffer->mFrameCount = 0;
278 buffer->mRaw = NULL;
279 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700280 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800281 }
282 if (elapsed != NULL) {
283 *elapsed = total;
284 }
285 if (requested == NULL) {
286 requested = &kNonBlocking;
287 }
288 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100289 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
290 requested->tv_sec, requested->tv_nsec / 1000000,
291 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800292 }
293 return status;
294}
295
296void ClientProxy::releaseBuffer(Buffer* buffer)
297{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700298 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800299 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700300 if (stepCount == 0 || mIsShutdown) {
301 // prevent accidental re-use of buffer
302 buffer->mFrameCount = 0;
303 buffer->mRaw = NULL;
304 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800305 return;
306 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700307 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
308 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800309 audio_track_cblk_t* cblk = mCblk;
310 // Both of these barriers are required
311 if (mIsOut) {
312 int32_t rear = cblk->u.mStreaming.mRear;
313 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
314 } else {
315 int32_t front = cblk->u.mStreaming.mFront;
316 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
317 }
318}
319
320void ClientProxy::binderDied()
321{
322 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700323 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900324 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800325 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700326 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
327 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800328 }
329}
330
331void ClientProxy::interrupt()
332{
333 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700334 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900335 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700336 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
337 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800338 }
339}
340
341size_t ClientProxy::getMisalignment()
342{
343 audio_track_cblk_t* cblk = mCblk;
344 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
345 (mFrameCountP2 - 1);
346}
347
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700348size_t ClientProxy::getFramesFilled() {
349 audio_track_cblk_t* cblk = mCblk;
350 int32_t front;
351 int32_t rear;
352
353 if (mIsOut) {
354 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
355 rear = cblk->u.mStreaming.mRear;
356 } else {
357 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
358 front = cblk->u.mStreaming.mFront;
359 }
360 ssize_t filled = rear - front;
361 // pipe should not be overfull
362 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700363 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700364 return 0;
365 }
366 return (size_t)filled;
367}
368
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800369// ---------------------------------------------------------------------------
370
371void AudioTrackClientProxy::flush()
372{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700373 // This works for mFrameCountP2 <= 2^30
374 size_t increment = mFrameCountP2 << 1;
375 size_t mask = increment - 1;
376 audio_track_cblk_t* cblk = mCblk;
377 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
378 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
379 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800380}
381
Eric Laurentbfb1b832013-01-07 09:53:42 -0800382bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700383 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800384}
385
386bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700387 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800388}
389
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100390status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
391{
392 struct timespec total; // total elapsed time spent waiting
393 total.tv_sec = 0;
394 total.tv_nsec = 0;
395 audio_track_cblk_t* cblk = mCblk;
396 status_t status;
397 enum {
398 TIMEOUT_ZERO, // requested == NULL || *requested == 0
399 TIMEOUT_INFINITE, // *requested == infinity
400 TIMEOUT_FINITE, // 0 < *requested < infinity
401 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
402 } timeout;
403 if (requested == NULL) {
404 timeout = TIMEOUT_ZERO;
405 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
406 timeout = TIMEOUT_ZERO;
407 } else if (requested->tv_sec == INT_MAX) {
408 timeout = TIMEOUT_INFINITE;
409 } else {
410 timeout = TIMEOUT_FINITE;
411 }
412 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700413 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100414 // check for track invalidation by server, or server death detection
415 if (flags & CBLK_INVALID) {
416 ALOGV("Track invalidated");
417 status = DEAD_OBJECT;
418 goto end;
419 }
420 if (flags & CBLK_STREAM_END_DONE) {
421 ALOGV("stream end received");
422 status = NO_ERROR;
423 goto end;
424 }
425 // check for obtainBuffer interrupted by client
426 // check for obtainBuffer interrupted by client
427 if (flags & CBLK_INTERRUPT) {
428 ALOGV("waitStreamEndDone() interrupted by client");
429 status = -EINTR;
430 goto end;
431 }
432 struct timespec remaining;
433 const struct timespec *ts;
434 switch (timeout) {
435 case TIMEOUT_ZERO:
436 status = WOULD_BLOCK;
437 goto end;
438 case TIMEOUT_INFINITE:
439 ts = NULL;
440 break;
441 case TIMEOUT_FINITE:
442 timeout = TIMEOUT_CONTINUE;
443 if (MAX_SEC == 0) {
444 ts = requested;
445 break;
446 }
447 // fall through
448 case TIMEOUT_CONTINUE:
449 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
450 if (requested->tv_sec < total.tv_sec ||
451 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
452 status = TIMED_OUT;
453 goto end;
454 }
455 remaining.tv_sec = requested->tv_sec - total.tv_sec;
456 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
457 remaining.tv_nsec += 1000000000;
458 remaining.tv_sec++;
459 }
460 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
461 remaining.tv_sec = MAX_SEC;
462 remaining.tv_nsec = 0;
463 }
464 ts = &remaining;
465 break;
466 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800467 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100468 ts = NULL;
469 break;
470 }
471 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
472 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700473 errno = 0;
474 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100475 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700476 switch (errno) {
477 case 0: // normal wakeup by server, or by binderDied()
478 case EWOULDBLOCK: // benign race condition with server
479 case EINTR: // wait was interrupted by signal or other spurious wakeup
480 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100481 break;
482 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700483 status = errno;
484 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100485 goto end;
486 }
487 }
488 }
489
490end:
491 if (requested == NULL) {
492 requested = &kNonBlocking;
493 }
494 return status;
495}
496
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800497// ---------------------------------------------------------------------------
498
499StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
500 size_t frameCount, size_t frameSize)
501 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
502 mMutator(&cblk->u.mStatic.mSingleStateQueue), mBufferPosition(0)
503{
Andy Hung9b461582014-12-01 17:56:29 -0800504 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800505}
506
507void StaticAudioTrackClientProxy::flush()
508{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800509 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800510}
511
512void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
513{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800514 // This can only happen on a 64-bit client
515 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
516 // FIXME Should return an error status
517 return;
518 }
Andy Hung9b461582014-12-01 17:56:29 -0800519 mState.mLoopStart = (uint32_t) loopStart;
520 mState.mLoopEnd = (uint32_t) loopEnd;
521 mState.mLoopCount = loopCount;
522 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
523 // set patch-up variables until the mState is acknowledged by the ServerProxy.
524 // observed buffer position and loop count will freeze until then to give the
525 // illusion of a synchronous change.
526 size_t bufferPosition = getBufferPosition();
527 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
528 if (loopCount != 0 && bufferPosition >= mState.mLoopEnd) {
529 mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800530 }
Andy Hung9b461582014-12-01 17:56:29 -0800531 (void) mMutator.push(mState);
532}
533
534void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
535{
536 // This can only happen on a 64-bit client
537 if (position > UINT32_MAX) {
538 // FIXME Should return an error status
539 return;
540 }
541 mState.mPosition = (uint32_t) position;
542 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
543 mBufferPosition = position;
544 (void) mMutator.push(mState);
545}
546
547void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
548 size_t loopEnd, int loopCount)
549{
550 setLoop(loopStart, loopEnd, loopCount);
551 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800552}
553
554size_t StaticAudioTrackClientProxy::getBufferPosition()
555{
556 size_t bufferPosition;
557 if (mMutator.ack()) {
Andy Hung9b461582014-12-01 17:56:29 -0800558 // There is a race condition here as ack may be signaled before
559 // the buffer position in mCblk is updated. Will be fixed in a later CL.
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800560 bufferPosition = (size_t) mCblk->u.mStatic.mBufferPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 if (bufferPosition > mFrameCount) {
562 bufferPosition = mFrameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800563 }
564 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800565 bufferPosition = mBufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800566 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 return bufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800568}
569
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800570// ---------------------------------------------------------------------------
571
572ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
573 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700574 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Glenn Kastence8828a2013-09-16 18:07:38 -0700575 mAvailToClient(0), mFlush(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800576{
Glenn Kastena8190fc2012-12-03 17:06:56 -0800577}
578
Glenn Kasten2e422c42013-10-18 13:00:29 -0700579status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800580{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700581 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800582 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700583 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800584 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700585 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800586 audio_track_cblk_t* cblk = mCblk;
587 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
588 // or use previous cached value from framesReady(), with added barrier if it omits.
589 int32_t front;
590 int32_t rear;
591 // See notes on barriers at ClientProxy::obtainBuffer()
592 if (mIsOut) {
593 int32_t flush = cblk->u.mStreaming.mFlush;
594 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100595 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800596 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700597 // effectively obtain then release whatever is in the buffer
Glenn Kasten20f51b12014-10-30 10:43:19 -0700598 size_t mask = (mFrameCountP2 << 1) - 1;
599 int32_t newFront = (front & ~mask) | (flush & mask);
600 ssize_t filled = rear - newFront;
601 // Rather than shutting down on a corrupt flush, just treat it as a full flush
602 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800603 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
604 "filled %d=%#x",
Glenn Kasten20f51b12014-10-30 10:43:19 -0700605 mFlush, flush, front, rear, mask, newFront, filled, filled);
606 newFront = rear;
607 }
608 mFlush = flush;
609 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
610 // There is no danger from a false positive, so err on the side of caution
611 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100612 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
613 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700614 (void) syscall(__NR_futex, &cblk->mFutex,
615 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100616 }
617 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700618 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800619 }
620 } else {
621 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
622 rear = cblk->u.mStreaming.mRear;
623 }
624 ssize_t filled = rear - front;
625 // pipe should not already be overfull
626 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700627 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800628 mIsShutdown = true;
629 }
630 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700631 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800632 }
633 // don't allow filling pipe beyond the nominal size
634 size_t availToServer;
635 if (mIsOut) {
636 availToServer = filled;
637 mAvailToClient = mFrameCount - filled;
638 } else {
639 availToServer = mFrameCount - filled;
640 mAvailToClient = filled;
641 }
642 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
643 size_t part1;
644 if (mIsOut) {
645 front &= mFrameCountP2 - 1;
646 part1 = mFrameCountP2 - front;
647 } else {
648 rear &= mFrameCountP2 - 1;
649 part1 = mFrameCountP2 - rear;
650 }
651 if (part1 > availToServer) {
652 part1 = availToServer;
653 }
654 size_t ask = buffer->mFrameCount;
655 if (part1 > ask) {
656 part1 = ask;
657 }
658 // is assignment redundant in some cases?
659 buffer->mFrameCount = part1;
660 buffer->mRaw = part1 > 0 ?
661 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
662 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700663 // After flush(), allow releaseBuffer() on a previously obtained buffer;
664 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
665 if (!ackFlush) {
666 mUnreleased = part1;
667 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800668 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700669 }
670no_init:
671 buffer->mFrameCount = 0;
672 buffer->mRaw = NULL;
673 buffer->mNonContig = 0;
674 mUnreleased = 0;
675 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800676}
677
678void ServerProxy::releaseBuffer(Buffer* buffer)
679{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700680 LOG_ALWAYS_FATAL_IF(buffer == NULL);
681 size_t stepCount = buffer->mFrameCount;
682 if (stepCount == 0 || mIsShutdown) {
683 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800684 buffer->mFrameCount = 0;
685 buffer->mRaw = NULL;
686 buffer->mNonContig = 0;
687 return;
688 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700689 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800690 mUnreleased -= stepCount;
691 audio_track_cblk_t* cblk = mCblk;
692 if (mIsOut) {
693 int32_t front = cblk->u.mStreaming.mFront;
694 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
695 } else {
696 int32_t rear = cblk->u.mStreaming.mRear;
697 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
698 }
699
Glenn Kasten844f88c2014-05-09 13:38:09 -0700700 cblk->mServer += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800701
702 size_t half = mFrameCount / 2;
703 if (half == 0) {
704 half = 1;
705 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800706 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800707 if (minimum == 0) {
708 minimum = mIsOut ? half : 1;
709 } else if (minimum > half) {
710 minimum = half;
711 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700712 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700713 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700714 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700715 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
716 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700717 (void) syscall(__NR_futex, &cblk->mFutex,
718 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800719 }
720 }
721
722 buffer->mFrameCount = 0;
723 buffer->mRaw = NULL;
724 buffer->mNonContig = 0;
725}
726
727// ---------------------------------------------------------------------------
728
729size_t AudioTrackServerProxy::framesReady()
730{
731 LOG_ALWAYS_FATAL_IF(!mIsOut);
732
733 if (mIsShutdown) {
734 return 0;
735 }
736 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100737
738 int32_t flush = cblk->u.mStreaming.mFlush;
739 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700740 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100741 return mFrameCount;
742 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800743 // the acquire might not be necessary since not doing a subsequent read
744 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
745 ssize_t filled = rear - cblk->u.mStreaming.mFront;
746 // pipe should not already be overfull
747 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700748 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800749 mIsShutdown = true;
750 return 0;
751 }
752 // cache this value for later use by obtainBuffer(), with added barrier
753 // and racy if called by normal mixer thread
754 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
755 return filled;
756}
757
Eric Laurentbfb1b832013-01-07 09:53:42 -0800758bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700759 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800760 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700761 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800762 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700763 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700764 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800765 }
766 return old;
767}
768
Glenn Kasten82aaf942013-07-17 16:05:07 -0700769void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
770{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700771 audio_track_cblk_t* cblk = mCblk;
772 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700773
774 // FIXME also wake futex so that underrun is noticed more quickly
Glenn Kasten844f88c2014-05-09 13:38:09 -0700775 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700776}
777
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800778// ---------------------------------------------------------------------------
779
780StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
781 size_t frameCount, size_t frameSize)
782 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
783 mObserver(&cblk->u.mStatic.mSingleStateQueue), mPosition(0),
Andy Hungcb2129b2014-11-11 12:17:22 -0800784 mFramesReadySafe(frameCount), mFramesReady(frameCount),
785 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800786{
Andy Hung9b461582014-12-01 17:56:29 -0800787 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800788}
789
790void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
791{
792 mFramesReadyIsCalledByMultipleThreads = true;
793}
794
795size_t StaticAudioTrackServerProxy::framesReady()
796{
Andy Hungcb2129b2014-11-11 12:17:22 -0800797 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800798 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800799 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800800 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800801 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800802}
803
Andy Hung9b461582014-12-01 17:56:29 -0800804status_t StaticAudioTrackServerProxy::updateStateWithLoop(
805 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800806{
Andy Hung9b461582014-12-01 17:56:29 -0800807 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800809 const size_t loopStart = update.mLoopStart;
810 const size_t loopEnd = update.mLoopEnd;
811 size_t position = localState->mPosition;
812 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800813 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800814 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800815 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
816 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800817 // If the current position is greater than the end of the loop
818 // we "wrap" to the loop start. This might cause an audible pop.
819 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800820 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800821 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800822 valid = true;
823 }
824 }
Andy Hung9b461582014-12-01 17:56:29 -0800825 if (!valid || position > mFrameCount) {
826 return NO_INIT;
827 }
828 localState->mPosition = position;
829 localState->mLoopCount = update.mLoopCount;
830 localState->mLoopEnd = loopEnd;
831 localState->mLoopStart = loopStart;
832 localState->mLoopSequence = update.mLoopSequence;
833 }
834 return OK;
835}
836
837status_t StaticAudioTrackServerProxy::updateStateWithPosition(
838 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
839{
840 if (localState->mPositionSequence != update.mPositionSequence) {
841 if (update.mPosition > mFrameCount) {
842 return NO_INIT;
843 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
844 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
845 }
846 localState->mPosition = update.mPosition;
847 localState->mPositionSequence = update.mPositionSequence;
848 }
849 return OK;
850}
851
852ssize_t StaticAudioTrackServerProxy::pollPosition()
853{
854 StaticAudioTrackState state;
855 if (mObserver.poll(state)) {
856 StaticAudioTrackState trystate = mState;
857 bool result;
858 const int32_t diffSeq = state.mLoopSequence - state.mPositionSequence;
859
860 if (diffSeq < 0) {
861 result = updateStateWithLoop(&trystate, state) == OK &&
862 updateStateWithPosition(&trystate, state) == OK;
863 } else {
864 result = updateStateWithPosition(&trystate, state) == OK &&
865 updateStateWithLoop(&trystate, state) == OK;
866 }
867 if (!result) {
868 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800869 ALOGE("%s client pushed an invalid state, shutting down", __func__);
870 mIsShutdown = true;
871 return (ssize_t) NO_INIT;
872 }
Andy Hung9b461582014-12-01 17:56:29 -0800873 mState = trystate;
874 if (mState.mLoopCount == -1) {
875 mFramesReady = INT64_MAX;
876 } else if (mState.mLoopCount == 0) {
877 mFramesReady = mFrameCount - mState.mPosition;
878 } else if (mState.mLoopCount > 0) {
879 // TODO: Later consider fixing overflow, but does not seem needed now
880 // as will not overflow if loopStart and loopEnd are Java "ints".
881 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
882 + mFrameCount - mState.mPosition;
883 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800884 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800885 // This may overflow, but client is not supposed to rely on it
Andy Hung9b461582014-12-01 17:56:29 -0800886 mCblk->u.mStatic.mBufferPosition = (uint32_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800887 }
Andy Hung9b461582014-12-01 17:56:29 -0800888 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800889}
890
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800891status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800892{
893 if (mIsShutdown) {
894 buffer->mFrameCount = 0;
895 buffer->mRaw = NULL;
896 buffer->mNonContig = 0;
897 mUnreleased = 0;
898 return NO_INIT;
899 }
900 ssize_t positionOrStatus = pollPosition();
901 if (positionOrStatus < 0) {
902 buffer->mFrameCount = 0;
903 buffer->mRaw = NULL;
904 buffer->mNonContig = 0;
905 mUnreleased = 0;
906 return (status_t) positionOrStatus;
907 }
908 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800909 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800910 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800911 if (position < end) {
912 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800913 size_t wanted = buffer->mFrameCount;
914 if (avail < wanted) {
915 buffer->mFrameCount = avail;
916 } else {
917 avail = wanted;
918 }
919 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
920 } else {
921 avail = 0;
922 buffer->mFrameCount = 0;
923 buffer->mRaw = NULL;
924 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800925 // As mFramesReady is the total remaining frames in the static audio track,
926 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -0800927 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -0800928 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800929 mUnreleased = avail;
930 return NO_ERROR;
931}
932
933void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
934{
935 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -0800936 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -0700937 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800938 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700939 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800940 buffer->mRaw = NULL;
941 buffer->mNonContig = 0;
942 return;
943 }
944 mUnreleased -= stepCount;
945 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -0800946 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800947 size_t newPosition = position + stepCount;
948 int32_t setFlags = 0;
949 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800950 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
951 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800952 newPosition = mFrameCount;
953 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800954 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800955 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800956 setFlags = CBLK_LOOP_CYCLE;
957 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800958 setFlags = CBLK_LOOP_FINAL;
959 }
960 }
961 if (newPosition == mFrameCount) {
962 setFlags |= CBLK_BUFFER_END;
963 }
Andy Hung9b461582014-12-01 17:56:29 -0800964 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -0800965 if (mFramesReady != INT64_MAX) {
966 mFramesReady -= stepCount;
967 }
968 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800969
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700970 cblk->mServer += stepCount;
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800971 // This may overflow, but client is not supposed to rely on it
Andy Hung9b461582014-12-01 17:56:29 -0800972 cblk->u.mStatic.mBufferPosition = (uint32_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800973 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700974 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800975 // this would be a good place to wake a futex
976 }
977
978 buffer->mFrameCount = 0;
979 buffer->mRaw = NULL;
980 buffer->mNonContig = 0;
981}
982
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800983void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount __unused)
Glenn Kasten82aaf942013-07-17 16:05:07 -0700984{
985 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
986 // we don't have a location to count underrun frames. The underrun frame counter
987 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
988 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
989
990 // FIXME also wake futex so that underrun is noticed more quickly
991 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
992}
993
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800994// ---------------------------------------------------------------------------
995
Glenn Kastena8190fc2012-12-03 17:06:56 -0800996} // namespace android