blob: da73d655545ef1a519ed58febb5a98f2288fb99e [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{
478 StaticAudioTrackState newState;
479 newState.mLoopStart = loopStart;
480 newState.mLoopEnd = loopEnd;
481 newState.mLoopCount = loopCount;
482 mBufferPosition = loopStart;
483 (void) mMutator.push(newState);
484}
485
486size_t StaticAudioTrackClientProxy::getBufferPosition()
487{
488 size_t bufferPosition;
489 if (mMutator.ack()) {
490 bufferPosition = mCblk->u.mStatic.mBufferPosition;
491 if (bufferPosition > mFrameCount) {
492 bufferPosition = mFrameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800493 }
494 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800495 bufferPosition = mBufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800496 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800497 return bufferPosition;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800498}
499
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800500// ---------------------------------------------------------------------------
501
502ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
503 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700504 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Glenn Kastence8828a2013-09-16 18:07:38 -0700505 mAvailToClient(0), mFlush(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800506{
Glenn Kastena8190fc2012-12-03 17:06:56 -0800507}
508
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800509status_t ServerProxy::obtainBuffer(Buffer* buffer)
510{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700511 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800512 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700513 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700515 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800516 audio_track_cblk_t* cblk = mCblk;
517 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
518 // or use previous cached value from framesReady(), with added barrier if it omits.
519 int32_t front;
520 int32_t rear;
521 // See notes on barriers at ClientProxy::obtainBuffer()
522 if (mIsOut) {
523 int32_t flush = cblk->u.mStreaming.mFlush;
524 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100525 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800526 if (flush != mFlush) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527 mFlush = flush;
Glenn Kasten050501d2013-07-11 10:35:38 -0700528 // effectively obtain then release whatever is in the buffer
529 android_atomic_release_store(rear, &cblk->u.mStreaming.mFront);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100530 if (front != rear) {
531 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
532 if (!(old & CBLK_FUTEX_WAKE)) {
533 (void) __futex_syscall3(&cblk->mFutex,
534 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
535 }
536 }
537 front = rear;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800538 }
539 } else {
540 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
541 rear = cblk->u.mStreaming.mRear;
542 }
543 ssize_t filled = rear - front;
544 // pipe should not already be overfull
545 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
546 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
547 mIsShutdown = true;
548 }
549 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700550 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800551 }
552 // don't allow filling pipe beyond the nominal size
553 size_t availToServer;
554 if (mIsOut) {
555 availToServer = filled;
556 mAvailToClient = mFrameCount - filled;
557 } else {
558 availToServer = mFrameCount - filled;
559 mAvailToClient = filled;
560 }
561 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
562 size_t part1;
563 if (mIsOut) {
564 front &= mFrameCountP2 - 1;
565 part1 = mFrameCountP2 - front;
566 } else {
567 rear &= mFrameCountP2 - 1;
568 part1 = mFrameCountP2 - rear;
569 }
570 if (part1 > availToServer) {
571 part1 = availToServer;
572 }
573 size_t ask = buffer->mFrameCount;
574 if (part1 > ask) {
575 part1 = ask;
576 }
577 // is assignment redundant in some cases?
578 buffer->mFrameCount = part1;
579 buffer->mRaw = part1 > 0 ?
580 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
581 buffer->mNonContig = availToServer - part1;
582 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800583 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700584 }
585no_init:
586 buffer->mFrameCount = 0;
587 buffer->mRaw = NULL;
588 buffer->mNonContig = 0;
589 mUnreleased = 0;
590 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800591}
592
593void ServerProxy::releaseBuffer(Buffer* buffer)
594{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700595 LOG_ALWAYS_FATAL_IF(buffer == NULL);
596 size_t stepCount = buffer->mFrameCount;
597 if (stepCount == 0 || mIsShutdown) {
598 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800599 buffer->mFrameCount = 0;
600 buffer->mRaw = NULL;
601 buffer->mNonContig = 0;
602 return;
603 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700604 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800605 mUnreleased -= stepCount;
606 audio_track_cblk_t* cblk = mCblk;
607 if (mIsOut) {
608 int32_t front = cblk->u.mStreaming.mFront;
609 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
610 } else {
611 int32_t rear = cblk->u.mStreaming.mRear;
612 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
613 }
614
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700615 mCblk->mServer += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800616
617 size_t half = mFrameCount / 2;
618 if (half == 0) {
619 half = 1;
620 }
621 size_t minimum = cblk->mMinimum;
622 if (minimum == 0) {
623 minimum = mIsOut ? half : 1;
624 } else if (minimum > half) {
625 minimum = half;
626 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700627 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700628 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800629 ALOGV("mAvailToClient=%u stepCount=%u minimum=%u", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700630 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
631 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800632 (void) __futex_syscall3(&cblk->mFutex,
633 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
634 }
635 }
636
637 buffer->mFrameCount = 0;
638 buffer->mRaw = NULL;
639 buffer->mNonContig = 0;
640}
641
642// ---------------------------------------------------------------------------
643
644size_t AudioTrackServerProxy::framesReady()
645{
646 LOG_ALWAYS_FATAL_IF(!mIsOut);
647
648 if (mIsShutdown) {
649 return 0;
650 }
651 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100652
653 int32_t flush = cblk->u.mStreaming.mFlush;
654 if (flush != mFlush) {
655 return mFrameCount;
656 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800657 // the acquire might not be necessary since not doing a subsequent read
658 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
659 ssize_t filled = rear - cblk->u.mStreaming.mFront;
660 // pipe should not already be overfull
661 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
662 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled);
663 mIsShutdown = true;
664 return 0;
665 }
666 // cache this value for later use by obtainBuffer(), with added barrier
667 // and racy if called by normal mixer thread
668 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
669 return filled;
670}
671
Eric Laurentbfb1b832013-01-07 09:53:42 -0800672bool AudioTrackServerProxy::setStreamEndDone() {
673 bool old =
Glenn Kasten96f60d82013-07-12 10:21:18 -0700674 (android_atomic_or(CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800675 if (!old) {
676 (void) __futex_syscall3(&mCblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
677 1);
678 }
679 return old;
680}
681
Glenn Kasten82aaf942013-07-17 16:05:07 -0700682void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
683{
684 mCblk->u.mStreaming.mUnderrunFrames += frameCount;
685
686 // FIXME also wake futex so that underrun is noticed more quickly
687 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
688}
689
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800690// ---------------------------------------------------------------------------
691
692StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
693 size_t frameCount, size_t frameSize)
694 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
695 mObserver(&cblk->u.mStatic.mSingleStateQueue), mPosition(0),
696 mEnd(frameCount), mFramesReadyIsCalledByMultipleThreads(false)
697{
698 mState.mLoopStart = 0;
699 mState.mLoopEnd = 0;
700 mState.mLoopCount = 0;
701}
702
703void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
704{
705 mFramesReadyIsCalledByMultipleThreads = true;
706}
707
708size_t StaticAudioTrackServerProxy::framesReady()
709{
710 // FIXME
711 // This is racy if called by normal mixer thread,
712 // as we're reading 2 independent variables without a lock.
713 // Can't call mObserver.poll(), as we might be called from wrong thread.
714 // If looping is enabled, should return a higher number (since includes non-contiguous).
715 size_t position = mPosition;
716 if (!mFramesReadyIsCalledByMultipleThreads) {
717 ssize_t positionOrStatus = pollPosition();
718 if (positionOrStatus >= 0) {
719 position = (size_t) positionOrStatus;
720 }
721 }
722 size_t end = mEnd;
723 return position < end ? end - position : 0;
724}
725
726ssize_t StaticAudioTrackServerProxy::pollPosition()
727{
728 size_t position = mPosition;
729 StaticAudioTrackState state;
730 if (mObserver.poll(state)) {
731 bool valid = false;
732 size_t loopStart = state.mLoopStart;
733 size_t loopEnd = state.mLoopEnd;
734 if (state.mLoopCount == 0) {
735 if (loopStart > mFrameCount) {
736 loopStart = mFrameCount;
737 }
738 // ignore loopEnd
739 mPosition = position = loopStart;
740 mEnd = mFrameCount;
741 mState.mLoopCount = 0;
742 valid = true;
743 } else {
744 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
745 loopEnd - loopStart >= MIN_LOOP) {
746 if (!(loopStart <= position && position < loopEnd)) {
747 mPosition = position = loopStart;
748 }
749 mEnd = loopEnd;
750 mState = state;
751 valid = true;
752 }
753 }
754 if (!valid) {
755 ALOGE("%s client pushed an invalid state, shutting down", __func__);
756 mIsShutdown = true;
757 return (ssize_t) NO_INIT;
758 }
759 mCblk->u.mStatic.mBufferPosition = position;
760 }
761 return (ssize_t) position;
762}
763
764status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer)
765{
766 if (mIsShutdown) {
767 buffer->mFrameCount = 0;
768 buffer->mRaw = NULL;
769 buffer->mNonContig = 0;
770 mUnreleased = 0;
771 return NO_INIT;
772 }
773 ssize_t positionOrStatus = pollPosition();
774 if (positionOrStatus < 0) {
775 buffer->mFrameCount = 0;
776 buffer->mRaw = NULL;
777 buffer->mNonContig = 0;
778 mUnreleased = 0;
779 return (status_t) positionOrStatus;
780 }
781 size_t position = (size_t) positionOrStatus;
782 size_t avail;
783 if (position < mEnd) {
784 avail = mEnd - position;
785 size_t wanted = buffer->mFrameCount;
786 if (avail < wanted) {
787 buffer->mFrameCount = avail;
788 } else {
789 avail = wanted;
790 }
791 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
792 } else {
793 avail = 0;
794 buffer->mFrameCount = 0;
795 buffer->mRaw = NULL;
796 }
797 buffer->mNonContig = 0; // FIXME should be > 0 for looping
798 mUnreleased = avail;
799 return NO_ERROR;
800}
801
802void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
803{
804 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700805 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800806 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700807 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 buffer->mRaw = NULL;
809 buffer->mNonContig = 0;
810 return;
811 }
812 mUnreleased -= stepCount;
813 audio_track_cblk_t* cblk = mCblk;
814 size_t position = mPosition;
815 size_t newPosition = position + stepCount;
816 int32_t setFlags = 0;
817 if (!(position <= newPosition && newPosition <= mFrameCount)) {
818 ALOGW("%s newPosition %u outside [%u, %u]", __func__, newPosition, position, mFrameCount);
819 newPosition = mFrameCount;
820 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
821 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
822 newPosition = mState.mLoopStart;
823 setFlags = CBLK_LOOP_CYCLE;
824 } else {
825 mEnd = mFrameCount; // this is what allows playback to continue after the loop
826 setFlags = CBLK_LOOP_FINAL;
827 }
828 }
829 if (newPosition == mFrameCount) {
830 setFlags |= CBLK_BUFFER_END;
831 }
832 mPosition = newPosition;
833
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700834 cblk->mServer += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800835 cblk->u.mStatic.mBufferPosition = newPosition;
836 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700837 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800838 // this would be a good place to wake a futex
839 }
840
841 buffer->mFrameCount = 0;
842 buffer->mRaw = NULL;
843 buffer->mNonContig = 0;
844}
845
Glenn Kasten82aaf942013-07-17 16:05:07 -0700846void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
847{
848 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
849 // we don't have a location to count underrun frames. The underrun frame counter
850 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
851 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
852
853 // FIXME also wake futex so that underrun is noticed more quickly
854 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
855}
856
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800857// ---------------------------------------------------------------------------
858
Glenn Kastena8190fc2012-12-03 17:06:56 -0800859} // namespace android