blob: e898109e6a493370bba011a3be5bbb8b5a50c81e [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>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080022extern "C" {
23#include "../private/bionic_futex.h"
24}
Glenn Kastena8190fc2012-12-03 17:06:56 -080025
26namespace android {
27
28audio_track_cblk_t::audio_track_cblk_t()
Glenn Kastenf20e1d82013-07-12 09:45:18 -070029 : mServer(0), frameCount_(0), mFutex(0), mMinimum(0),
Glenn Kastend054c322013-07-12 12:59:20 -070030 mVolumeLR(0x10001000), 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)) {
137 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
138 mIsShutdown = true;
139 status = NO_INIT;
140 goto end;
141 }
142 // don't allow filling pipe beyond the nominal size
143 size_t avail = mIsOut ? mFrameCount - filled : filled;
144 if (avail > 0) {
145 // 'avail' may be non-contiguous, so return only the first contiguous chunk
146 size_t part1;
147 if (mIsOut) {
148 rear &= mFrameCountP2 - 1;
149 part1 = mFrameCountP2 - rear;
150 } else {
151 front &= mFrameCountP2 - 1;
152 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800153 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800154 if (part1 > avail) {
155 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800156 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800157 if (part1 > buffer->mFrameCount) {
158 part1 = buffer->mFrameCount;
159 }
160 buffer->mFrameCount = part1;
161 buffer->mRaw = part1 > 0 ?
162 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
163 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700164 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800165 status = NO_ERROR;
166 break;
167 }
168 struct timespec remaining;
169 const struct timespec *ts;
170 switch (timeout) {
171 case TIMEOUT_ZERO:
172 status = WOULD_BLOCK;
173 goto end;
174 case TIMEOUT_INFINITE:
175 ts = NULL;
176 break;
177 case TIMEOUT_FINITE:
178 timeout = TIMEOUT_CONTINUE;
179 if (MAX_SEC == 0) {
180 ts = requested;
181 break;
182 }
183 // fall through
184 case TIMEOUT_CONTINUE:
185 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
186 if (!measure || requested->tv_sec < total.tv_sec ||
187 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
188 status = TIMED_OUT;
189 goto end;
190 }
191 remaining.tv_sec = requested->tv_sec - total.tv_sec;
192 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
193 remaining.tv_nsec += 1000000000;
194 remaining.tv_sec++;
195 }
196 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
197 remaining.tv_sec = MAX_SEC;
198 remaining.tv_nsec = 0;
199 }
200 ts = &remaining;
201 break;
202 default:
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100203 LOG_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800204 ts = NULL;
205 break;
206 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700207 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
208 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800209 int rc;
210 if (measure && !beforeIsValid) {
211 clock_gettime(CLOCK_MONOTONIC, &before);
212 beforeIsValid = true;
213 }
214 int ret = __futex_syscall4(&cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700215 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800216 // update total elapsed time spent waiting
217 if (measure) {
218 struct timespec after;
219 clock_gettime(CLOCK_MONOTONIC, &after);
220 total.tv_sec += after.tv_sec - before.tv_sec;
221 long deltaNs = after.tv_nsec - before.tv_nsec;
222 if (deltaNs < 0) {
223 deltaNs += 1000000000;
224 total.tv_sec--;
225 }
226 if ((total.tv_nsec += deltaNs) >= 1000000000) {
227 total.tv_nsec -= 1000000000;
228 total.tv_sec++;
229 }
230 before = after;
231 beforeIsValid = true;
232 }
233 switch (ret) {
234 case 0: // normal wakeup by server, or by binderDied()
235 case -EWOULDBLOCK: // benign race condition with server
236 case -EINTR: // wait was interrupted by signal or other spurious wakeup
237 case -ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700238 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800239 break;
240 default:
241 ALOGE("%s unexpected error %d", __func__, ret);
242 status = -ret;
243 goto end;
244 }
245 }
246 }
247
248end:
249 if (status != NO_ERROR) {
250 buffer->mFrameCount = 0;
251 buffer->mRaw = NULL;
252 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700253 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800254 }
255 if (elapsed != NULL) {
256 *elapsed = total;
257 }
258 if (requested == NULL) {
259 requested = &kNonBlocking;
260 }
261 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100262 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
263 requested->tv_sec, requested->tv_nsec / 1000000,
264 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800265 }
266 return status;
267}
268
269void ClientProxy::releaseBuffer(Buffer* buffer)
270{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700271 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800272 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700273 if (stepCount == 0 || mIsShutdown) {
274 // prevent accidental re-use of buffer
275 buffer->mFrameCount = 0;
276 buffer->mRaw = NULL;
277 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800278 return;
279 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700280 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
281 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800282 audio_track_cblk_t* cblk = mCblk;
283 // Both of these barriers are required
284 if (mIsOut) {
285 int32_t rear = cblk->u.mStreaming.mRear;
286 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
287 } else {
288 int32_t front = cblk->u.mStreaming.mFront;
289 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
290 }
291}
292
293void ClientProxy::binderDied()
294{
295 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700296 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800297 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
298 (void) __futex_syscall3(&cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
299 1);
300 }
301}
302
303void ClientProxy::interrupt()
304{
305 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700306 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800307 (void) __futex_syscall3(&cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
308 1);
309 }
310}
311
312size_t ClientProxy::getMisalignment()
313{
314 audio_track_cblk_t* cblk = mCblk;
315 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
316 (mFrameCountP2 - 1);
317}
318
Eric Laurentcc21e4f2013-10-16 15:12:32 -0700319size_t ClientProxy::getFramesFilled() {
320 audio_track_cblk_t* cblk = mCblk;
321 int32_t front;
322 int32_t rear;
323
324 if (mIsOut) {
325 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
326 rear = cblk->u.mStreaming.mRear;
327 } else {
328 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
329 front = cblk->u.mStreaming.mFront;
330 }
331 ssize_t filled = rear - front;
332 // pipe should not be overfull
333 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
334 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
335 return 0;
336 }
337 return (size_t)filled;
338}
339
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800340// ---------------------------------------------------------------------------
341
342void AudioTrackClientProxy::flush()
343{
344 mCblk->u.mStreaming.mFlush++;
345}
346
Eric Laurentbfb1b832013-01-07 09:53:42 -0800347bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700348 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800349}
350
351bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700352 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800353}
354
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100355status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
356{
357 struct timespec total; // total elapsed time spent waiting
358 total.tv_sec = 0;
359 total.tv_nsec = 0;
360 audio_track_cblk_t* cblk = mCblk;
361 status_t status;
362 enum {
363 TIMEOUT_ZERO, // requested == NULL || *requested == 0
364 TIMEOUT_INFINITE, // *requested == infinity
365 TIMEOUT_FINITE, // 0 < *requested < infinity
366 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
367 } timeout;
368 if (requested == NULL) {
369 timeout = TIMEOUT_ZERO;
370 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
371 timeout = TIMEOUT_ZERO;
372 } else if (requested->tv_sec == INT_MAX) {
373 timeout = TIMEOUT_INFINITE;
374 } else {
375 timeout = TIMEOUT_FINITE;
376 }
377 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700378 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100379 // check for track invalidation by server, or server death detection
380 if (flags & CBLK_INVALID) {
381 ALOGV("Track invalidated");
382 status = DEAD_OBJECT;
383 goto end;
384 }
385 if (flags & CBLK_STREAM_END_DONE) {
386 ALOGV("stream end received");
387 status = NO_ERROR;
388 goto end;
389 }
390 // check for obtainBuffer interrupted by client
391 // check for obtainBuffer interrupted by client
392 if (flags & CBLK_INTERRUPT) {
393 ALOGV("waitStreamEndDone() interrupted by client");
394 status = -EINTR;
395 goto end;
396 }
397 struct timespec remaining;
398 const struct timespec *ts;
399 switch (timeout) {
400 case TIMEOUT_ZERO:
401 status = WOULD_BLOCK;
402 goto end;
403 case TIMEOUT_INFINITE:
404 ts = NULL;
405 break;
406 case TIMEOUT_FINITE:
407 timeout = TIMEOUT_CONTINUE;
408 if (MAX_SEC == 0) {
409 ts = requested;
410 break;
411 }
412 // fall through
413 case TIMEOUT_CONTINUE:
414 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
415 if (requested->tv_sec < total.tv_sec ||
416 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
417 status = TIMED_OUT;
418 goto end;
419 }
420 remaining.tv_sec = requested->tv_sec - total.tv_sec;
421 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
422 remaining.tv_nsec += 1000000000;
423 remaining.tv_sec++;
424 }
425 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
426 remaining.tv_sec = MAX_SEC;
427 remaining.tv_nsec = 0;
428 }
429 ts = &remaining;
430 break;
431 default:
432 LOG_FATAL("waitStreamEndDone() timeout=%d", timeout);
433 ts = NULL;
434 break;
435 }
436 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
437 if (!(old & CBLK_FUTEX_WAKE)) {
438 int rc;
439 int ret = __futex_syscall4(&cblk->mFutex,
440 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
441 switch (ret) {
442 case 0: // normal wakeup by server, or by binderDied()
443 case -EWOULDBLOCK: // benign race condition with server
444 case -EINTR: // wait was interrupted by signal or other spurious wakeup
445 case -ETIMEDOUT: // time-out expired
446 break;
447 default:
448 ALOGE("%s unexpected error %d", __func__, ret);
449 status = -ret;
450 goto end;
451 }
452 }
453 }
454
455end:
456 if (requested == NULL) {
457 requested = &kNonBlocking;
458 }
459 return status;
460}
461
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800462// ---------------------------------------------------------------------------
463
464StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
465 size_t frameCount, size_t frameSize)
466 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
467 mMutator(&cblk->u.mStatic.mSingleStateQueue), mBufferPosition(0)
468{
469}
470
471void StaticAudioTrackClientProxy::flush()
472{
473 LOG_FATAL("static flush");
474}
475
476void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
477{
Glenn Kasten751a9c82014-01-28 11:03:28 -0800478 // This can only happen on a 64-bit client
479 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
480 // FIXME Should return an error status
481 return;
482 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800483 StaticAudioTrackState newState;
Glenn Kasten751a9c82014-01-28 11:03:28 -0800484 newState.mLoopStart = (uint32_t) loopStart;
485 newState.mLoopEnd = (uint32_t) loopEnd;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800486 newState.mLoopCount = loopCount;
487 mBufferPosition = loopStart;
488 (void) mMutator.push(newState);
489}
490
491size_t StaticAudioTrackClientProxy::getBufferPosition()
492{
493 size_t bufferPosition;
494 if (mMutator.ack()) {
Glenn Kasten751a9c82014-01-28 11:03:28 -0800495 bufferPosition = (size_t) mCblk->u.mStatic.mBufferPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800496 if (bufferPosition > mFrameCount) {
497 bufferPosition = mFrameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800498 }
499 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800500 bufferPosition = mBufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800501 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800502 return bufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800503}
504
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800505// ---------------------------------------------------------------------------
506
507ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
508 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700509 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Glenn Kastence8828a2013-09-16 18:07:38 -0700510 mAvailToClient(0), mFlush(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800511{
Glenn Kastena8190fc2012-12-03 17:06:56 -0800512}
513
Glenn Kasten2e422c42013-10-18 13:00:29 -0700514status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800515{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700516 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700518 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700520 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800521 audio_track_cblk_t* cblk = mCblk;
522 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
523 // or use previous cached value from framesReady(), with added barrier if it omits.
524 int32_t front;
525 int32_t rear;
526 // See notes on barriers at ClientProxy::obtainBuffer()
527 if (mIsOut) {
528 int32_t flush = cblk->u.mStreaming.mFlush;
529 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100530 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800531 if (flush != mFlush) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800532 mFlush = flush;
Glenn Kasten050501d2013-07-11 10:35:38 -0700533 // effectively obtain then release whatever is in the buffer
534 android_atomic_release_store(rear, &cblk->u.mStreaming.mFront);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100535 if (front != rear) {
536 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
537 if (!(old & CBLK_FUTEX_WAKE)) {
538 (void) __futex_syscall3(&cblk->mFutex,
539 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
540 }
541 }
542 front = rear;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800543 }
544 } else {
545 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
546 rear = cblk->u.mStreaming.mRear;
547 }
548 ssize_t filled = rear - front;
549 // pipe should not already be overfull
550 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
551 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
552 mIsShutdown = true;
553 }
554 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700555 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800556 }
557 // don't allow filling pipe beyond the nominal size
558 size_t availToServer;
559 if (mIsOut) {
560 availToServer = filled;
561 mAvailToClient = mFrameCount - filled;
562 } else {
563 availToServer = mFrameCount - filled;
564 mAvailToClient = filled;
565 }
566 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
567 size_t part1;
568 if (mIsOut) {
569 front &= mFrameCountP2 - 1;
570 part1 = mFrameCountP2 - front;
571 } else {
572 rear &= mFrameCountP2 - 1;
573 part1 = mFrameCountP2 - rear;
574 }
575 if (part1 > availToServer) {
576 part1 = availToServer;
577 }
578 size_t ask = buffer->mFrameCount;
579 if (part1 > ask) {
580 part1 = ask;
581 }
582 // is assignment redundant in some cases?
583 buffer->mFrameCount = part1;
584 buffer->mRaw = part1 > 0 ?
585 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
586 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700587 // After flush(), allow releaseBuffer() on a previously obtained buffer;
588 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
589 if (!ackFlush) {
590 mUnreleased = part1;
591 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800592 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700593 }
594no_init:
595 buffer->mFrameCount = 0;
596 buffer->mRaw = NULL;
597 buffer->mNonContig = 0;
598 mUnreleased = 0;
599 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600}
601
602void ServerProxy::releaseBuffer(Buffer* buffer)
603{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700604 LOG_ALWAYS_FATAL_IF(buffer == NULL);
605 size_t stepCount = buffer->mFrameCount;
606 if (stepCount == 0 || mIsShutdown) {
607 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800608 buffer->mFrameCount = 0;
609 buffer->mRaw = NULL;
610 buffer->mNonContig = 0;
611 return;
612 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700613 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800614 mUnreleased -= stepCount;
615 audio_track_cblk_t* cblk = mCblk;
616 if (mIsOut) {
617 int32_t front = cblk->u.mStreaming.mFront;
618 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
619 } else {
620 int32_t rear = cblk->u.mStreaming.mRear;
621 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
622 }
623
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700624 mCblk->mServer += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800625
626 size_t half = mFrameCount / 2;
627 if (half == 0) {
628 half = 1;
629 }
Glenn Kasten751a9c82014-01-28 11:03:28 -0800630 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800631 if (minimum == 0) {
632 minimum = mIsOut ? half : 1;
633 } else if (minimum > half) {
634 minimum = half;
635 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700636 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700637 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800638 ALOGV("mAvailToClient=%u stepCount=%u minimum=%u", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700639 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
640 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800641 (void) __futex_syscall3(&cblk->mFutex,
642 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
643 }
644 }
645
646 buffer->mFrameCount = 0;
647 buffer->mRaw = NULL;
648 buffer->mNonContig = 0;
649}
650
651// ---------------------------------------------------------------------------
652
653size_t AudioTrackServerProxy::framesReady()
654{
655 LOG_ALWAYS_FATAL_IF(!mIsOut);
656
657 if (mIsShutdown) {
658 return 0;
659 }
660 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100661
662 int32_t flush = cblk->u.mStreaming.mFlush;
663 if (flush != mFlush) {
664 return mFrameCount;
665 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800666 // the acquire might not be necessary since not doing a subsequent read
667 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
668 ssize_t filled = rear - cblk->u.mStreaming.mFront;
669 // pipe should not already be overfull
670 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
671 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
672 mIsShutdown = true;
673 return 0;
674 }
675 // cache this value for later use by obtainBuffer(), with added barrier
676 // and racy if called by normal mixer thread
677 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
678 return filled;
679}
680
Eric Laurentbfb1b832013-01-07 09:53:42 -0800681bool AudioTrackServerProxy::setStreamEndDone() {
682 bool old =
Glenn Kasten96f60d82013-07-12 10:21:18 -0700683 (android_atomic_or(CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800684 if (!old) {
685 (void) __futex_syscall3(&mCblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
686 1);
687 }
688 return old;
689}
690
Glenn Kasten82aaf942013-07-17 16:05:07 -0700691void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
692{
693 mCblk->u.mStreaming.mUnderrunFrames += frameCount;
694
695 // FIXME also wake futex so that underrun is noticed more quickly
696 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
697}
698
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800699// ---------------------------------------------------------------------------
700
701StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
702 size_t frameCount, size_t frameSize)
703 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
704 mObserver(&cblk->u.mStatic.mSingleStateQueue), mPosition(0),
705 mEnd(frameCount), mFramesReadyIsCalledByMultipleThreads(false)
706{
707 mState.mLoopStart = 0;
708 mState.mLoopEnd = 0;
709 mState.mLoopCount = 0;
710}
711
712void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
713{
714 mFramesReadyIsCalledByMultipleThreads = true;
715}
716
717size_t StaticAudioTrackServerProxy::framesReady()
718{
719 // FIXME
720 // This is racy if called by normal mixer thread,
721 // as we're reading 2 independent variables without a lock.
722 // Can't call mObserver.poll(), as we might be called from wrong thread.
723 // If looping is enabled, should return a higher number (since includes non-contiguous).
724 size_t position = mPosition;
725 if (!mFramesReadyIsCalledByMultipleThreads) {
726 ssize_t positionOrStatus = pollPosition();
727 if (positionOrStatus >= 0) {
728 position = (size_t) positionOrStatus;
729 }
730 }
731 size_t end = mEnd;
732 return position < end ? end - position : 0;
733}
734
735ssize_t StaticAudioTrackServerProxy::pollPosition()
736{
737 size_t position = mPosition;
738 StaticAudioTrackState state;
739 if (mObserver.poll(state)) {
740 bool valid = false;
741 size_t loopStart = state.mLoopStart;
742 size_t loopEnd = state.mLoopEnd;
743 if (state.mLoopCount == 0) {
744 if (loopStart > mFrameCount) {
745 loopStart = mFrameCount;
746 }
747 // ignore loopEnd
748 mPosition = position = loopStart;
749 mEnd = mFrameCount;
750 mState.mLoopCount = 0;
751 valid = true;
752 } else {
753 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
754 loopEnd - loopStart >= MIN_LOOP) {
755 if (!(loopStart <= position && position < loopEnd)) {
756 mPosition = position = loopStart;
757 }
758 mEnd = loopEnd;
759 mState = state;
760 valid = true;
761 }
762 }
763 if (!valid) {
764 ALOGE("%s client pushed an invalid state, shutting down", __func__);
765 mIsShutdown = true;
766 return (ssize_t) NO_INIT;
767 }
Glenn Kasten751a9c82014-01-28 11:03:28 -0800768 // This may overflow, but client is not supposed to rely on it
769 mCblk->u.mStatic.mBufferPosition = (uint32_t) position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800770 }
771 return (ssize_t) position;
772}
773
Glenn Kasten2e422c42013-10-18 13:00:29 -0700774status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800775{
776 if (mIsShutdown) {
777 buffer->mFrameCount = 0;
778 buffer->mRaw = NULL;
779 buffer->mNonContig = 0;
780 mUnreleased = 0;
781 return NO_INIT;
782 }
783 ssize_t positionOrStatus = pollPosition();
784 if (positionOrStatus < 0) {
785 buffer->mFrameCount = 0;
786 buffer->mRaw = NULL;
787 buffer->mNonContig = 0;
788 mUnreleased = 0;
789 return (status_t) positionOrStatus;
790 }
791 size_t position = (size_t) positionOrStatus;
792 size_t avail;
793 if (position < mEnd) {
794 avail = mEnd - position;
795 size_t wanted = buffer->mFrameCount;
796 if (avail < wanted) {
797 buffer->mFrameCount = avail;
798 } else {
799 avail = wanted;
800 }
801 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
802 } else {
803 avail = 0;
804 buffer->mFrameCount = 0;
805 buffer->mRaw = NULL;
806 }
807 buffer->mNonContig = 0; // FIXME should be > 0 for looping
808 mUnreleased = avail;
809 return NO_ERROR;
810}
811
812void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
813{
814 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700815 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800816 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700817 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800818 buffer->mRaw = NULL;
819 buffer->mNonContig = 0;
820 return;
821 }
822 mUnreleased -= stepCount;
823 audio_track_cblk_t* cblk = mCblk;
824 size_t position = mPosition;
825 size_t newPosition = position + stepCount;
826 int32_t setFlags = 0;
827 if (!(position <= newPosition && newPosition <= mFrameCount)) {
828 ALOGW("%s newPosition %u outside [%u, %u]", __func__, newPosition, position, mFrameCount);
829 newPosition = mFrameCount;
830 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
831 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
832 newPosition = mState.mLoopStart;
833 setFlags = CBLK_LOOP_CYCLE;
834 } else {
835 mEnd = mFrameCount; // this is what allows playback to continue after the loop
836 setFlags = CBLK_LOOP_FINAL;
837 }
838 }
839 if (newPosition == mFrameCount) {
840 setFlags |= CBLK_BUFFER_END;
841 }
842 mPosition = newPosition;
843
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700844 cblk->mServer += stepCount;
Glenn Kasten751a9c82014-01-28 11:03:28 -0800845 // This may overflow, but client is not supposed to rely on it
846 cblk->u.mStatic.mBufferPosition = (uint32_t) newPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800847 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700848 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800849 // this would be a good place to wake a futex
850 }
851
852 buffer->mFrameCount = 0;
853 buffer->mRaw = NULL;
854 buffer->mNonContig = 0;
855}
856
Glenn Kasten82aaf942013-07-17 16:05:07 -0700857void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
858{
859 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
860 // we don't have a location to count underrun frames. The underrun frame counter
861 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
862 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
863
864 // FIXME also wake futex so that underrun is noticed more quickly
865 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
866}
867
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800868// ---------------------------------------------------------------------------
869
Glenn Kastena8190fc2012-12-03 17:06:56 -0800870} // namespace android