blob: 561cb24e93a119d53ca4109f666e2cc95b37f450 [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
28audio_track_cblk_t::audio_track_cblk_t()
Glenn Kasten74935e42013-12-19 08:56:45 -080029 : mServer(0), mFutex(0), mMinimum(0),
Glenn Kastenc56f3422014-03-21 17:53:17 -070030 mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0), mFlags(0)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080031{
32 memset(&u, 0, sizeof(u));
33}
34
35// ---------------------------------------------------------------------------
36
37Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
38 bool isOut, bool clientInServer)
39 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
40 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
Glenn Kasten7db7df02013-06-25 16:13:23 -070041 mIsShutdown(false), mUnreleased(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080042{
43}
44
Glenn Kasten9f80dd22012-12-18 15:57:32 -080045// ---------------------------------------------------------------------------
46
47ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
48 size_t frameSize, bool isOut, bool clientInServer)
49 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer), mEpoch(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080050{
Glenn Kastena8190fc2012-12-03 17:06:56 -080051}
52
Glenn Kasten9f80dd22012-12-18 15:57:32 -080053const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
54const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
55
56#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
57
58// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
59// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
60// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
61// order of minutes.
62#define MAX_SEC 5
63
64status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
65 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -080066{
Glenn Kasten7db7df02013-06-25 16:13:23 -070067 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080068 struct timespec total; // total elapsed time spent waiting
69 total.tv_sec = 0;
70 total.tv_nsec = 0;
71 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -080072
Glenn Kasten9f80dd22012-12-18 15:57:32 -080073 status_t status;
74 enum {
75 TIMEOUT_ZERO, // requested == NULL || *requested == 0
76 TIMEOUT_INFINITE, // *requested == infinity
77 TIMEOUT_FINITE, // 0 < *requested < infinity
78 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
79 } timeout;
80 if (requested == NULL) {
81 timeout = TIMEOUT_ZERO;
82 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
83 timeout = TIMEOUT_ZERO;
84 } else if (requested->tv_sec == INT_MAX) {
85 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -080086 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -080087 timeout = TIMEOUT_FINITE;
88 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
89 measure = true;
90 }
Glenn Kastena8190fc2012-12-03 17:06:56 -080091 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -080092 struct timespec before;
93 bool beforeIsValid = false;
94 audio_track_cblk_t* cblk = mCblk;
95 bool ignoreInitialPendingInterrupt = true;
96 // check for shared memory corruption
97 if (mIsShutdown) {
98 status = NO_INIT;
99 goto end;
100 }
101 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700102 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800103 // check for track invalidation by server, or server death detection
104 if (flags & CBLK_INVALID) {
105 ALOGV("Track invalidated");
106 status = DEAD_OBJECT;
107 goto end;
108 }
109 // check for obtainBuffer interrupted by client
110 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
111 ALOGV("obtainBuffer() interrupted by client");
112 status = -EINTR;
113 goto end;
114 }
115 ignoreInitialPendingInterrupt = false;
116 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
117 int32_t front;
118 int32_t rear;
119 if (mIsOut) {
120 // The barrier following the read of mFront is probably redundant.
121 // We're about to perform a conditional branch based on 'filled',
122 // which will force the processor to observe the read of mFront
123 // prior to allowing data writes starting at mRaw.
124 // However, the processor may support speculative execution,
125 // and be unable to undo speculative writes into shared memory.
126 // The barrier will prevent such speculative execution.
127 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
128 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800129 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800130 // On the other hand, this barrier is required.
131 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
132 front = cblk->u.mStreaming.mFront;
133 }
134 ssize_t filled = rear - front;
135 // pipe should not be overfull
136 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700137 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700138 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700139 "shutting down", filled, mFrameCount);
140 mIsShutdown = true;
141 status = NO_INIT;
142 goto end;
143 }
144 // for input, sync up on overrun
145 filled = 0;
146 cblk->u.mStreaming.mFront = rear;
147 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800148 }
149 // don't allow filling pipe beyond the nominal size
150 size_t avail = mIsOut ? mFrameCount - filled : filled;
151 if (avail > 0) {
152 // 'avail' may be non-contiguous, so return only the first contiguous chunk
153 size_t part1;
154 if (mIsOut) {
155 rear &= mFrameCountP2 - 1;
156 part1 = mFrameCountP2 - rear;
157 } else {
158 front &= mFrameCountP2 - 1;
159 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800160 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800161 if (part1 > avail) {
162 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800163 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800164 if (part1 > buffer->mFrameCount) {
165 part1 = buffer->mFrameCount;
166 }
167 buffer->mFrameCount = part1;
168 buffer->mRaw = part1 > 0 ?
169 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
170 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700171 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800172 status = NO_ERROR;
173 break;
174 }
175 struct timespec remaining;
176 const struct timespec *ts;
177 switch (timeout) {
178 case TIMEOUT_ZERO:
179 status = WOULD_BLOCK;
180 goto end;
181 case TIMEOUT_INFINITE:
182 ts = NULL;
183 break;
184 case TIMEOUT_FINITE:
185 timeout = TIMEOUT_CONTINUE;
186 if (MAX_SEC == 0) {
187 ts = requested;
188 break;
189 }
190 // fall through
191 case TIMEOUT_CONTINUE:
192 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
193 if (!measure || requested->tv_sec < total.tv_sec ||
194 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
195 status = TIMED_OUT;
196 goto end;
197 }
198 remaining.tv_sec = requested->tv_sec - total.tv_sec;
199 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
200 remaining.tv_nsec += 1000000000;
201 remaining.tv_sec++;
202 }
203 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
204 remaining.tv_sec = MAX_SEC;
205 remaining.tv_nsec = 0;
206 }
207 ts = &remaining;
208 break;
209 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800210 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800211 ts = NULL;
212 break;
213 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700214 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
215 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800216 if (measure && !beforeIsValid) {
217 clock_gettime(CLOCK_MONOTONIC, &before);
218 beforeIsValid = true;
219 }
Elliott Hughesee499292014-05-21 17:55:51 -0700220 errno = 0;
221 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700222 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800223 // update total elapsed time spent waiting
224 if (measure) {
225 struct timespec after;
226 clock_gettime(CLOCK_MONOTONIC, &after);
227 total.tv_sec += after.tv_sec - before.tv_sec;
228 long deltaNs = after.tv_nsec - before.tv_nsec;
229 if (deltaNs < 0) {
230 deltaNs += 1000000000;
231 total.tv_sec--;
232 }
233 if ((total.tv_nsec += deltaNs) >= 1000000000) {
234 total.tv_nsec -= 1000000000;
235 total.tv_sec++;
236 }
237 before = after;
238 beforeIsValid = true;
239 }
Elliott Hughesee499292014-05-21 17:55:51 -0700240 switch (errno) {
241 case 0: // normal wakeup by server, or by binderDied()
242 case EWOULDBLOCK: // benign race condition with server
243 case EINTR: // wait was interrupted by signal or other spurious wakeup
244 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700245 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800246 break;
247 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700248 status = errno;
249 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800250 goto end;
251 }
252 }
253 }
254
255end:
256 if (status != NO_ERROR) {
257 buffer->mFrameCount = 0;
258 buffer->mRaw = NULL;
259 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700260 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800261 }
262 if (elapsed != NULL) {
263 *elapsed = total;
264 }
265 if (requested == NULL) {
266 requested = &kNonBlocking;
267 }
268 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100269 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
270 requested->tv_sec, requested->tv_nsec / 1000000,
271 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800272 }
273 return status;
274}
275
276void ClientProxy::releaseBuffer(Buffer* buffer)
277{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700278 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800279 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700280 if (stepCount == 0 || mIsShutdown) {
281 // prevent accidental re-use of buffer
282 buffer->mFrameCount = 0;
283 buffer->mRaw = NULL;
284 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800285 return;
286 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700287 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
288 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800289 audio_track_cblk_t* cblk = mCblk;
290 // Both of these barriers are required
291 if (mIsOut) {
292 int32_t rear = cblk->u.mStreaming.mRear;
293 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
294 } else {
295 int32_t front = cblk->u.mStreaming.mFront;
296 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
297 }
298}
299
300void ClientProxy::binderDied()
301{
302 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700303 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800304 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700305 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
306 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800307 }
308}
309
310void ClientProxy::interrupt()
311{
312 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700313 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700314 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
315 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800316 }
317}
318
319size_t ClientProxy::getMisalignment()
320{
321 audio_track_cblk_t* cblk = mCblk;
322 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
323 (mFrameCountP2 - 1);
324}
325
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700326size_t ClientProxy::getFramesFilled() {
327 audio_track_cblk_t* cblk = mCblk;
328 int32_t front;
329 int32_t rear;
330
331 if (mIsOut) {
332 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
333 rear = cblk->u.mStreaming.mRear;
334 } else {
335 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
336 front = cblk->u.mStreaming.mFront;
337 }
338 ssize_t filled = rear - front;
339 // pipe should not be overfull
340 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700341 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700342 return 0;
343 }
344 return (size_t)filled;
345}
346
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800347// ---------------------------------------------------------------------------
348
349void AudioTrackClientProxy::flush()
350{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700351 // This works for mFrameCountP2 <= 2^30
352 size_t increment = mFrameCountP2 << 1;
353 size_t mask = increment - 1;
354 audio_track_cblk_t* cblk = mCblk;
355 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
356 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
357 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800358}
359
Eric Laurentbfb1b832013-01-07 09:53:42 -0800360bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700361 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800362}
363
364bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700365 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800366}
367
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100368status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
369{
370 struct timespec total; // total elapsed time spent waiting
371 total.tv_sec = 0;
372 total.tv_nsec = 0;
373 audio_track_cblk_t* cblk = mCblk;
374 status_t status;
375 enum {
376 TIMEOUT_ZERO, // requested == NULL || *requested == 0
377 TIMEOUT_INFINITE, // *requested == infinity
378 TIMEOUT_FINITE, // 0 < *requested < infinity
379 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
380 } timeout;
381 if (requested == NULL) {
382 timeout = TIMEOUT_ZERO;
383 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
384 timeout = TIMEOUT_ZERO;
385 } else if (requested->tv_sec == INT_MAX) {
386 timeout = TIMEOUT_INFINITE;
387 } else {
388 timeout = TIMEOUT_FINITE;
389 }
390 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700391 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100392 // check for track invalidation by server, or server death detection
393 if (flags & CBLK_INVALID) {
394 ALOGV("Track invalidated");
395 status = DEAD_OBJECT;
396 goto end;
397 }
398 if (flags & CBLK_STREAM_END_DONE) {
399 ALOGV("stream end received");
400 status = NO_ERROR;
401 goto end;
402 }
403 // check for obtainBuffer interrupted by client
404 // check for obtainBuffer interrupted by client
405 if (flags & CBLK_INTERRUPT) {
406 ALOGV("waitStreamEndDone() interrupted by client");
407 status = -EINTR;
408 goto end;
409 }
410 struct timespec remaining;
411 const struct timespec *ts;
412 switch (timeout) {
413 case TIMEOUT_ZERO:
414 status = WOULD_BLOCK;
415 goto end;
416 case TIMEOUT_INFINITE:
417 ts = NULL;
418 break;
419 case TIMEOUT_FINITE:
420 timeout = TIMEOUT_CONTINUE;
421 if (MAX_SEC == 0) {
422 ts = requested;
423 break;
424 }
425 // fall through
426 case TIMEOUT_CONTINUE:
427 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
428 if (requested->tv_sec < total.tv_sec ||
429 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
430 status = TIMED_OUT;
431 goto end;
432 }
433 remaining.tv_sec = requested->tv_sec - total.tv_sec;
434 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
435 remaining.tv_nsec += 1000000000;
436 remaining.tv_sec++;
437 }
438 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
439 remaining.tv_sec = MAX_SEC;
440 remaining.tv_nsec = 0;
441 }
442 ts = &remaining;
443 break;
444 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800445 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100446 ts = NULL;
447 break;
448 }
449 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
450 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700451 errno = 0;
452 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100453 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700454 switch (errno) {
455 case 0: // normal wakeup by server, or by binderDied()
456 case EWOULDBLOCK: // benign race condition with server
457 case EINTR: // wait was interrupted by signal or other spurious wakeup
458 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100459 break;
460 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700461 status = errno;
462 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100463 goto end;
464 }
465 }
466 }
467
468end:
469 if (requested == NULL) {
470 requested = &kNonBlocking;
471 }
472 return status;
473}
474
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800475// ---------------------------------------------------------------------------
476
477StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
478 size_t frameCount, size_t frameSize)
479 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
480 mMutator(&cblk->u.mStatic.mSingleStateQueue), mBufferPosition(0)
481{
482}
483
484void StaticAudioTrackClientProxy::flush()
485{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800486 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800487}
488
489void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
490{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800491 // This can only happen on a 64-bit client
492 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
493 // FIXME Should return an error status
494 return;
495 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800496 StaticAudioTrackState newState;
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800497 newState.mLoopStart = (uint32_t) loopStart;
498 newState.mLoopEnd = (uint32_t) loopEnd;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800499 newState.mLoopCount = loopCount;
500 mBufferPosition = loopStart;
501 (void) mMutator.push(newState);
502}
503
504size_t StaticAudioTrackClientProxy::getBufferPosition()
505{
506 size_t bufferPosition;
507 if (mMutator.ack()) {
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800508 bufferPosition = (size_t) mCblk->u.mStatic.mBufferPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800509 if (bufferPosition > mFrameCount) {
510 bufferPosition = mFrameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800511 }
512 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800513 bufferPosition = mBufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800514 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800515 return bufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800516}
517
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800518// ---------------------------------------------------------------------------
519
520ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
521 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700522 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Glenn Kastence8828a2013-09-16 18:07:38 -0700523 mAvailToClient(0), mFlush(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800524{
Glenn Kastena8190fc2012-12-03 17:06:56 -0800525}
526
Glenn Kasten2e422c42013-10-18 13:00:29 -0700527status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800528{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700529 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800530 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700531 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800532 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700533 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800534 audio_track_cblk_t* cblk = mCblk;
535 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
536 // or use previous cached value from framesReady(), with added barrier if it omits.
537 int32_t front;
538 int32_t rear;
539 // See notes on barriers at ClientProxy::obtainBuffer()
540 if (mIsOut) {
541 int32_t flush = cblk->u.mStreaming.mFlush;
542 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100543 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800544 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700545 // effectively obtain then release whatever is in the buffer
Glenn Kasten20f51b12014-10-30 10:43:19 -0700546 size_t mask = (mFrameCountP2 << 1) - 1;
547 int32_t newFront = (front & ~mask) | (flush & mask);
548 ssize_t filled = rear - newFront;
549 // Rather than shutting down on a corrupt flush, just treat it as a full flush
550 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
551 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, filled %d=%#x",
552 mFlush, flush, front, rear, mask, newFront, filled, filled);
553 newFront = rear;
554 }
555 mFlush = flush;
556 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
557 // There is no danger from a false positive, so err on the side of caution
558 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100559 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
560 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700561 (void) syscall(__NR_futex, &cblk->mFutex,
562 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100563 }
564 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700565 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800566 }
567 } else {
568 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
569 rear = cblk->u.mStreaming.mRear;
570 }
571 ssize_t filled = rear - front;
572 // pipe should not already be overfull
573 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700574 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800575 mIsShutdown = true;
576 }
577 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700578 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800579 }
580 // don't allow filling pipe beyond the nominal size
581 size_t availToServer;
582 if (mIsOut) {
583 availToServer = filled;
584 mAvailToClient = mFrameCount - filled;
585 } else {
586 availToServer = mFrameCount - filled;
587 mAvailToClient = filled;
588 }
589 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
590 size_t part1;
591 if (mIsOut) {
592 front &= mFrameCountP2 - 1;
593 part1 = mFrameCountP2 - front;
594 } else {
595 rear &= mFrameCountP2 - 1;
596 part1 = mFrameCountP2 - rear;
597 }
598 if (part1 > availToServer) {
599 part1 = availToServer;
600 }
601 size_t ask = buffer->mFrameCount;
602 if (part1 > ask) {
603 part1 = ask;
604 }
605 // is assignment redundant in some cases?
606 buffer->mFrameCount = part1;
607 buffer->mRaw = part1 > 0 ?
608 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
609 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700610 // After flush(), allow releaseBuffer() on a previously obtained buffer;
611 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
612 if (!ackFlush) {
613 mUnreleased = part1;
614 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800615 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700616 }
617no_init:
618 buffer->mFrameCount = 0;
619 buffer->mRaw = NULL;
620 buffer->mNonContig = 0;
621 mUnreleased = 0;
622 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800623}
624
625void ServerProxy::releaseBuffer(Buffer* buffer)
626{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700627 LOG_ALWAYS_FATAL_IF(buffer == NULL);
628 size_t stepCount = buffer->mFrameCount;
629 if (stepCount == 0 || mIsShutdown) {
630 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800631 buffer->mFrameCount = 0;
632 buffer->mRaw = NULL;
633 buffer->mNonContig = 0;
634 return;
635 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700636 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800637 mUnreleased -= stepCount;
638 audio_track_cblk_t* cblk = mCblk;
639 if (mIsOut) {
640 int32_t front = cblk->u.mStreaming.mFront;
641 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
642 } else {
643 int32_t rear = cblk->u.mStreaming.mRear;
644 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
645 }
646
Glenn Kasten844f88c2014-05-09 13:38:09 -0700647 cblk->mServer += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800648
649 size_t half = mFrameCount / 2;
650 if (half == 0) {
651 half = 1;
652 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800653 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800654 if (minimum == 0) {
655 minimum = mIsOut ? half : 1;
656 } else if (minimum > half) {
657 minimum = half;
658 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700659 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700660 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700661 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700662 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
663 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700664 (void) syscall(__NR_futex, &cblk->mFutex,
665 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800666 }
667 }
668
669 buffer->mFrameCount = 0;
670 buffer->mRaw = NULL;
671 buffer->mNonContig = 0;
672}
673
674// ---------------------------------------------------------------------------
675
676size_t AudioTrackServerProxy::framesReady()
677{
678 LOG_ALWAYS_FATAL_IF(!mIsOut);
679
680 if (mIsShutdown) {
681 return 0;
682 }
683 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100684
685 int32_t flush = cblk->u.mStreaming.mFlush;
686 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700687 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100688 return mFrameCount;
689 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800690 // the acquire might not be necessary since not doing a subsequent read
691 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
692 ssize_t filled = rear - cblk->u.mStreaming.mFront;
693 // pipe should not already be overfull
694 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700695 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800696 mIsShutdown = true;
697 return 0;
698 }
699 // cache this value for later use by obtainBuffer(), with added barrier
700 // and racy if called by normal mixer thread
701 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
702 return filled;
703}
704
Eric Laurentbfb1b832013-01-07 09:53:42 -0800705bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700706 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800707 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700708 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800709 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700710 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700711 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800712 }
713 return old;
714}
715
Glenn Kasten82aaf942013-07-17 16:05:07 -0700716void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
717{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700718 audio_track_cblk_t* cblk = mCblk;
719 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700720
721 // FIXME also wake futex so that underrun is noticed more quickly
Glenn Kasten844f88c2014-05-09 13:38:09 -0700722 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700723}
724
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800725// ---------------------------------------------------------------------------
726
727StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
728 size_t frameCount, size_t frameSize)
729 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
730 mObserver(&cblk->u.mStatic.mSingleStateQueue), mPosition(0),
731 mEnd(frameCount), mFramesReadyIsCalledByMultipleThreads(false)
732{
733 mState.mLoopStart = 0;
734 mState.mLoopEnd = 0;
735 mState.mLoopCount = 0;
736}
737
738void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
739{
740 mFramesReadyIsCalledByMultipleThreads = true;
741}
742
743size_t StaticAudioTrackServerProxy::framesReady()
744{
745 // FIXME
746 // This is racy if called by normal mixer thread,
747 // as we're reading 2 independent variables without a lock.
748 // Can't call mObserver.poll(), as we might be called from wrong thread.
749 // If looping is enabled, should return a higher number (since includes non-contiguous).
750 size_t position = mPosition;
751 if (!mFramesReadyIsCalledByMultipleThreads) {
752 ssize_t positionOrStatus = pollPosition();
753 if (positionOrStatus >= 0) {
754 position = (size_t) positionOrStatus;
755 }
756 }
757 size_t end = mEnd;
758 return position < end ? end - position : 0;
759}
760
761ssize_t StaticAudioTrackServerProxy::pollPosition()
762{
763 size_t position = mPosition;
764 StaticAudioTrackState state;
765 if (mObserver.poll(state)) {
766 bool valid = false;
767 size_t loopStart = state.mLoopStart;
768 size_t loopEnd = state.mLoopEnd;
769 if (state.mLoopCount == 0) {
770 if (loopStart > mFrameCount) {
771 loopStart = mFrameCount;
772 }
773 // ignore loopEnd
774 mPosition = position = loopStart;
775 mEnd = mFrameCount;
776 mState.mLoopCount = 0;
777 valid = true;
778 } else {
779 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
780 loopEnd - loopStart >= MIN_LOOP) {
781 if (!(loopStart <= position && position < loopEnd)) {
782 mPosition = position = loopStart;
783 }
784 mEnd = loopEnd;
785 mState = state;
786 valid = true;
787 }
788 }
789 if (!valid) {
790 ALOGE("%s client pushed an invalid state, shutting down", __func__);
791 mIsShutdown = true;
792 return (ssize_t) NO_INIT;
793 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800794 // This may overflow, but client is not supposed to rely on it
795 mCblk->u.mStatic.mBufferPosition = (uint32_t) position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800796 }
797 return (ssize_t) position;
798}
799
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800800status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800801{
802 if (mIsShutdown) {
803 buffer->mFrameCount = 0;
804 buffer->mRaw = NULL;
805 buffer->mNonContig = 0;
806 mUnreleased = 0;
807 return NO_INIT;
808 }
809 ssize_t positionOrStatus = pollPosition();
810 if (positionOrStatus < 0) {
811 buffer->mFrameCount = 0;
812 buffer->mRaw = NULL;
813 buffer->mNonContig = 0;
814 mUnreleased = 0;
815 return (status_t) positionOrStatus;
816 }
817 size_t position = (size_t) positionOrStatus;
818 size_t avail;
819 if (position < mEnd) {
820 avail = mEnd - position;
821 size_t wanted = buffer->mFrameCount;
822 if (avail < wanted) {
823 buffer->mFrameCount = avail;
824 } else {
825 avail = wanted;
826 }
827 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
828 } else {
829 avail = 0;
830 buffer->mFrameCount = 0;
831 buffer->mRaw = NULL;
832 }
833 buffer->mNonContig = 0; // FIXME should be > 0 for looping
834 mUnreleased = avail;
835 return NO_ERROR;
836}
837
838void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
839{
840 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700841 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800842 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700843 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800844 buffer->mRaw = NULL;
845 buffer->mNonContig = 0;
846 return;
847 }
848 mUnreleased -= stepCount;
849 audio_track_cblk_t* cblk = mCblk;
850 size_t position = mPosition;
851 size_t newPosition = position + stepCount;
852 int32_t setFlags = 0;
853 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700854 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800855 newPosition = mFrameCount;
856 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
857 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
858 newPosition = mState.mLoopStart;
859 setFlags = CBLK_LOOP_CYCLE;
860 } else {
861 mEnd = mFrameCount; // this is what allows playback to continue after the loop
862 setFlags = CBLK_LOOP_FINAL;
863 }
864 }
865 if (newPosition == mFrameCount) {
866 setFlags |= CBLK_BUFFER_END;
867 }
868 mPosition = newPosition;
869
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700870 cblk->mServer += stepCount;
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800871 // This may overflow, but client is not supposed to rely on it
872 cblk->u.mStatic.mBufferPosition = (uint32_t) newPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800873 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700874 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800875 // this would be a good place to wake a futex
876 }
877
878 buffer->mFrameCount = 0;
879 buffer->mRaw = NULL;
880 buffer->mNonContig = 0;
881}
882
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800883void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount __unused)
Glenn Kasten82aaf942013-07-17 16:05:07 -0700884{
885 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
886 // we don't have a location to count underrun frames. The underrun frame counter
887 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
888 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
889
890 // FIXME also wake futex so that underrun is noticed more quickly
891 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
892}
893
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800894// ---------------------------------------------------------------------------
895
Glenn Kastena8190fc2012-12-03 17:06:56 -0800896} // namespace android