blob: 52533f543aed6a90179374229703a8e4692815e8 [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)) {
zunkyu.leea78e1042014-11-07 15:47:32 +0900304 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800305 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700306 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
307 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800308 }
309}
310
311void ClientProxy::interrupt()
312{
313 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700314 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.leea78e1042014-11-07 15:47:32 +0900315 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700316 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
317 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800318 }
319}
320
321size_t ClientProxy::getMisalignment()
322{
323 audio_track_cblk_t* cblk = mCblk;
324 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
325 (mFrameCountP2 - 1);
326}
327
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700328size_t ClientProxy::getFramesFilled() {
329 audio_track_cblk_t* cblk = mCblk;
330 int32_t front;
331 int32_t rear;
332
333 if (mIsOut) {
334 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
335 rear = cblk->u.mStreaming.mRear;
336 } else {
337 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
338 front = cblk->u.mStreaming.mFront;
339 }
340 ssize_t filled = rear - front;
341 // pipe should not be overfull
342 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700343 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700344 return 0;
345 }
346 return (size_t)filled;
347}
348
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800349// ---------------------------------------------------------------------------
350
351void AudioTrackClientProxy::flush()
352{
353 mCblk->u.mStreaming.mFlush++;
354}
355
Eric Laurentbfb1b832013-01-07 09:53:42 -0800356bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700357 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800358}
359
360bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700361 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800362}
363
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100364status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
365{
366 struct timespec total; // total elapsed time spent waiting
367 total.tv_sec = 0;
368 total.tv_nsec = 0;
369 audio_track_cblk_t* cblk = mCblk;
370 status_t status;
371 enum {
372 TIMEOUT_ZERO, // requested == NULL || *requested == 0
373 TIMEOUT_INFINITE, // *requested == infinity
374 TIMEOUT_FINITE, // 0 < *requested < infinity
375 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
376 } timeout;
377 if (requested == NULL) {
378 timeout = TIMEOUT_ZERO;
379 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
380 timeout = TIMEOUT_ZERO;
381 } else if (requested->tv_sec == INT_MAX) {
382 timeout = TIMEOUT_INFINITE;
383 } else {
384 timeout = TIMEOUT_FINITE;
385 }
386 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700387 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100388 // check for track invalidation by server, or server death detection
389 if (flags & CBLK_INVALID) {
390 ALOGV("Track invalidated");
391 status = DEAD_OBJECT;
392 goto end;
393 }
394 if (flags & CBLK_STREAM_END_DONE) {
395 ALOGV("stream end received");
396 status = NO_ERROR;
397 goto end;
398 }
399 // check for obtainBuffer interrupted by client
400 // check for obtainBuffer interrupted by client
401 if (flags & CBLK_INTERRUPT) {
402 ALOGV("waitStreamEndDone() interrupted by client");
403 status = -EINTR;
404 goto end;
405 }
406 struct timespec remaining;
407 const struct timespec *ts;
408 switch (timeout) {
409 case TIMEOUT_ZERO:
410 status = WOULD_BLOCK;
411 goto end;
412 case TIMEOUT_INFINITE:
413 ts = NULL;
414 break;
415 case TIMEOUT_FINITE:
416 timeout = TIMEOUT_CONTINUE;
417 if (MAX_SEC == 0) {
418 ts = requested;
419 break;
420 }
421 // fall through
422 case TIMEOUT_CONTINUE:
423 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
424 if (requested->tv_sec < total.tv_sec ||
425 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
426 status = TIMED_OUT;
427 goto end;
428 }
429 remaining.tv_sec = requested->tv_sec - total.tv_sec;
430 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
431 remaining.tv_nsec += 1000000000;
432 remaining.tv_sec++;
433 }
434 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
435 remaining.tv_sec = MAX_SEC;
436 remaining.tv_nsec = 0;
437 }
438 ts = &remaining;
439 break;
440 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800441 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100442 ts = NULL;
443 break;
444 }
445 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
446 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700447 errno = 0;
448 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100449 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700450 switch (errno) {
451 case 0: // normal wakeup by server, or by binderDied()
452 case EWOULDBLOCK: // benign race condition with server
453 case EINTR: // wait was interrupted by signal or other spurious wakeup
454 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100455 break;
456 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700457 status = errno;
458 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100459 goto end;
460 }
461 }
462 }
463
464end:
465 if (requested == NULL) {
466 requested = &kNonBlocking;
467 }
468 return status;
469}
470
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800471// ---------------------------------------------------------------------------
472
473StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
474 size_t frameCount, size_t frameSize)
475 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
476 mMutator(&cblk->u.mStatic.mSingleStateQueue), mBufferPosition(0)
477{
478}
479
480void StaticAudioTrackClientProxy::flush()
481{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800482 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483}
484
485void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
486{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800487 // This can only happen on a 64-bit client
488 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
489 // FIXME Should return an error status
490 return;
491 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800492 StaticAudioTrackState newState;
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800493 newState.mLoopStart = (uint32_t) loopStart;
494 newState.mLoopEnd = (uint32_t) loopEnd;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800495 newState.mLoopCount = loopCount;
496 mBufferPosition = loopStart;
497 (void) mMutator.push(newState);
498}
499
500size_t StaticAudioTrackClientProxy::getBufferPosition()
501{
502 size_t bufferPosition;
503 if (mMutator.ack()) {
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800504 bufferPosition = (size_t) mCblk->u.mStatic.mBufferPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800505 if (bufferPosition > mFrameCount) {
506 bufferPosition = mFrameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800507 }
508 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800509 bufferPosition = mBufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800510 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800511 return bufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800512}
513
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514// ---------------------------------------------------------------------------
515
516ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
517 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700518 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Glenn Kastence8828a2013-09-16 18:07:38 -0700519 mAvailToClient(0), mFlush(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800520{
Glenn Kastena8190fc2012-12-03 17:06:56 -0800521}
522
Glenn Kasten2e422c42013-10-18 13:00:29 -0700523status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800524{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700525 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800526 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700527 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800528 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700529 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800530 audio_track_cblk_t* cblk = mCblk;
531 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
532 // or use previous cached value from framesReady(), with added barrier if it omits.
533 int32_t front;
534 int32_t rear;
535 // See notes on barriers at ClientProxy::obtainBuffer()
536 if (mIsOut) {
537 int32_t flush = cblk->u.mStreaming.mFlush;
538 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100539 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800540 if (flush != mFlush) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800541 mFlush = flush;
Glenn Kasten050501d2013-07-11 10:35:38 -0700542 // effectively obtain then release whatever is in the buffer
543 android_atomic_release_store(rear, &cblk->u.mStreaming.mFront);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100544 if (front != rear) {
545 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
546 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700547 (void) syscall(__NR_futex, &cblk->mFutex,
548 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100549 }
550 }
551 front = rear;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800552 }
553 } else {
554 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
555 rear = cblk->u.mStreaming.mRear;
556 }
557 ssize_t filled = rear - front;
558 // pipe should not already be overfull
559 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700560 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800561 mIsShutdown = true;
562 }
563 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700564 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800565 }
566 // don't allow filling pipe beyond the nominal size
567 size_t availToServer;
568 if (mIsOut) {
569 availToServer = filled;
570 mAvailToClient = mFrameCount - filled;
571 } else {
572 availToServer = mFrameCount - filled;
573 mAvailToClient = filled;
574 }
575 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
576 size_t part1;
577 if (mIsOut) {
578 front &= mFrameCountP2 - 1;
579 part1 = mFrameCountP2 - front;
580 } else {
581 rear &= mFrameCountP2 - 1;
582 part1 = mFrameCountP2 - rear;
583 }
584 if (part1 > availToServer) {
585 part1 = availToServer;
586 }
587 size_t ask = buffer->mFrameCount;
588 if (part1 > ask) {
589 part1 = ask;
590 }
591 // is assignment redundant in some cases?
592 buffer->mFrameCount = part1;
593 buffer->mRaw = part1 > 0 ?
594 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
595 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700596 // After flush(), allow releaseBuffer() on a previously obtained buffer;
597 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
598 if (!ackFlush) {
599 mUnreleased = part1;
600 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800601 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700602 }
603no_init:
604 buffer->mFrameCount = 0;
605 buffer->mRaw = NULL;
606 buffer->mNonContig = 0;
607 mUnreleased = 0;
608 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609}
610
611void ServerProxy::releaseBuffer(Buffer* buffer)
612{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700613 LOG_ALWAYS_FATAL_IF(buffer == NULL);
614 size_t stepCount = buffer->mFrameCount;
615 if (stepCount == 0 || mIsShutdown) {
616 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617 buffer->mFrameCount = 0;
618 buffer->mRaw = NULL;
619 buffer->mNonContig = 0;
620 return;
621 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700622 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800623 mUnreleased -= stepCount;
624 audio_track_cblk_t* cblk = mCblk;
625 if (mIsOut) {
626 int32_t front = cblk->u.mStreaming.mFront;
627 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
628 } else {
629 int32_t rear = cblk->u.mStreaming.mRear;
630 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
631 }
632
Glenn Kasten844f88c2014-05-09 13:38:09 -0700633 cblk->mServer += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800634
635 size_t half = mFrameCount / 2;
636 if (half == 0) {
637 half = 1;
638 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800639 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800640 if (minimum == 0) {
641 minimum = mIsOut ? half : 1;
642 } else if (minimum > half) {
643 minimum = half;
644 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700645 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700646 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700647 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700648 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
649 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700650 (void) syscall(__NR_futex, &cblk->mFutex,
651 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800652 }
653 }
654
655 buffer->mFrameCount = 0;
656 buffer->mRaw = NULL;
657 buffer->mNonContig = 0;
658}
659
660// ---------------------------------------------------------------------------
661
662size_t AudioTrackServerProxy::framesReady()
663{
664 LOG_ALWAYS_FATAL_IF(!mIsOut);
665
666 if (mIsShutdown) {
667 return 0;
668 }
669 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100670
671 int32_t flush = cblk->u.mStreaming.mFlush;
672 if (flush != mFlush) {
673 return mFrameCount;
674 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800675 // the acquire might not be necessary since not doing a subsequent read
676 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
677 ssize_t filled = rear - cblk->u.mStreaming.mFront;
678 // pipe should not already be overfull
679 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700680 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800681 mIsShutdown = true;
682 return 0;
683 }
684 // cache this value for later use by obtainBuffer(), with added barrier
685 // and racy if called by normal mixer thread
686 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
687 return filled;
688}
689
Eric Laurentbfb1b832013-01-07 09:53:42 -0800690bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700691 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800692 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700693 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800694 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700695 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700696 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800697 }
698 return old;
699}
700
Glenn Kasten82aaf942013-07-17 16:05:07 -0700701void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
702{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700703 audio_track_cblk_t* cblk = mCblk;
704 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700705
706 // FIXME also wake futex so that underrun is noticed more quickly
Glenn Kasten844f88c2014-05-09 13:38:09 -0700707 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700708}
709
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800710// ---------------------------------------------------------------------------
711
712StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
713 size_t frameCount, size_t frameSize)
714 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
715 mObserver(&cblk->u.mStatic.mSingleStateQueue), mPosition(0),
716 mEnd(frameCount), mFramesReadyIsCalledByMultipleThreads(false)
717{
718 mState.mLoopStart = 0;
719 mState.mLoopEnd = 0;
720 mState.mLoopCount = 0;
721}
722
723void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
724{
725 mFramesReadyIsCalledByMultipleThreads = true;
726}
727
728size_t StaticAudioTrackServerProxy::framesReady()
729{
730 // FIXME
731 // This is racy if called by normal mixer thread,
732 // as we're reading 2 independent variables without a lock.
733 // Can't call mObserver.poll(), as we might be called from wrong thread.
734 // If looping is enabled, should return a higher number (since includes non-contiguous).
735 size_t position = mPosition;
736 if (!mFramesReadyIsCalledByMultipleThreads) {
737 ssize_t positionOrStatus = pollPosition();
738 if (positionOrStatus >= 0) {
739 position = (size_t) positionOrStatus;
740 }
741 }
742 size_t end = mEnd;
743 return position < end ? end - position : 0;
744}
745
746ssize_t StaticAudioTrackServerProxy::pollPosition()
747{
748 size_t position = mPosition;
749 StaticAudioTrackState state;
750 if (mObserver.poll(state)) {
751 bool valid = false;
752 size_t loopStart = state.mLoopStart;
753 size_t loopEnd = state.mLoopEnd;
754 if (state.mLoopCount == 0) {
755 if (loopStart > mFrameCount) {
756 loopStart = mFrameCount;
757 }
758 // ignore loopEnd
759 mPosition = position = loopStart;
760 mEnd = mFrameCount;
761 mState.mLoopCount = 0;
762 valid = true;
763 } else {
764 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
765 loopEnd - loopStart >= MIN_LOOP) {
766 if (!(loopStart <= position && position < loopEnd)) {
767 mPosition = position = loopStart;
768 }
769 mEnd = loopEnd;
770 mState = state;
771 valid = true;
772 }
773 }
774 if (!valid) {
775 ALOGE("%s client pushed an invalid state, shutting down", __func__);
776 mIsShutdown = true;
777 return (ssize_t) NO_INIT;
778 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800779 // This may overflow, but client is not supposed to rely on it
780 mCblk->u.mStatic.mBufferPosition = (uint32_t) position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800781 }
782 return (ssize_t) position;
783}
784
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800785status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush __unused)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800786{
787 if (mIsShutdown) {
788 buffer->mFrameCount = 0;
789 buffer->mRaw = NULL;
790 buffer->mNonContig = 0;
791 mUnreleased = 0;
792 return NO_INIT;
793 }
794 ssize_t positionOrStatus = pollPosition();
795 if (positionOrStatus < 0) {
796 buffer->mFrameCount = 0;
797 buffer->mRaw = NULL;
798 buffer->mNonContig = 0;
799 mUnreleased = 0;
800 return (status_t) positionOrStatus;
801 }
802 size_t position = (size_t) positionOrStatus;
803 size_t avail;
804 if (position < mEnd) {
805 avail = mEnd - position;
806 size_t wanted = buffer->mFrameCount;
807 if (avail < wanted) {
808 buffer->mFrameCount = avail;
809 } else {
810 avail = wanted;
811 }
812 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
813 } else {
814 avail = 0;
815 buffer->mFrameCount = 0;
816 buffer->mRaw = NULL;
817 }
818 buffer->mNonContig = 0; // FIXME should be > 0 for looping
819 mUnreleased = avail;
820 return NO_ERROR;
821}
822
823void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
824{
825 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700826 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800827 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700828 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800829 buffer->mRaw = NULL;
830 buffer->mNonContig = 0;
831 return;
832 }
833 mUnreleased -= stepCount;
834 audio_track_cblk_t* cblk = mCblk;
835 size_t position = mPosition;
836 size_t newPosition = position + stepCount;
837 int32_t setFlags = 0;
838 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700839 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position, mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800840 newPosition = mFrameCount;
841 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
842 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
843 newPosition = mState.mLoopStart;
844 setFlags = CBLK_LOOP_CYCLE;
845 } else {
846 mEnd = mFrameCount; // this is what allows playback to continue after the loop
847 setFlags = CBLK_LOOP_FINAL;
848 }
849 }
850 if (newPosition == mFrameCount) {
851 setFlags |= CBLK_BUFFER_END;
852 }
853 mPosition = newPosition;
854
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700855 cblk->mServer += stepCount;
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800856 // This may overflow, but client is not supposed to rely on it
857 cblk->u.mStatic.mBufferPosition = (uint32_t) newPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800858 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700859 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800860 // this would be a good place to wake a futex
861 }
862
863 buffer->mFrameCount = 0;
864 buffer->mRaw = NULL;
865 buffer->mNonContig = 0;
866}
867
Glenn Kasten7c7be1e2013-12-19 16:34:04 -0800868void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount __unused)
Glenn Kasten82aaf942013-07-17 16:05:07 -0700869{
870 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
871 // we don't have a location to count underrun frames. The underrun frame counter
872 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
873 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
874
875 // FIXME also wake futex so that underrun is noticed more quickly
876 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
877}
878
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800879// ---------------------------------------------------------------------------
880
Glenn Kastena8190fc2012-12-03 17:06:56 -0800881} // namespace android