blob: d75ad87223f28f16ca9f5f2ef8f933e95b8e67b2 [file] [log] [blame]
Glenn Kastena8190fc2012-12-03 17:06:56 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioTrackShared"
18//#define LOG_NDEBUG 0
19
20#include <private/media/AudioTrackShared.h>
21#include <utils/Log.h>
Elliott Hughesee499292014-05-21 17:55:51 -070022
23#include <linux/futex.h>
24#include <sys/syscall.h>
Glenn Kastena8190fc2012-12-03 17:06:56 -080025
26namespace android {
27
Andy Hungcb2129b2014-11-11 12:17:22 -080028// used to clamp a value to size_t. TODO: move to another file.
29template <typename T>
30size_t clampToSize(T x) {
Andy Hung486a7132014-12-22 16:54:21 -080031 return sizeof(T) > sizeof(size_t) && x > (T) SIZE_MAX ? SIZE_MAX : x < 0 ? 0 : (size_t) x;
Andy Hungcb2129b2014-11-11 12:17:22 -080032}
33
Andy Hung9b461582014-12-01 17:56:29 -080034// incrementSequence is used to determine the next sequence value
35// for the loop and position sequence counters. It should return
36// a value between "other" + 1 and "other" + INT32_MAX, the choice of
37// which needs to be the "least recently used" sequence value for "self".
38// In general, this means (new_self) returned is max(self, other) + 1.
39
40static uint32_t incrementSequence(uint32_t self, uint32_t other) {
Chad Brubakercb50c542015-10-07 14:20:10 -070041 int32_t diff = (int32_t) self - (int32_t) other;
Andy Hung9b461582014-12-01 17:56:29 -080042 if (diff >= 0 && diff < INT32_MAX) {
43 return self + 1; // we're already ahead of other.
44 }
45 return other + 1; // we're behind, so move just ahead of other.
46}
47
Glenn Kastena8190fc2012-12-03 17:06:56 -080048audio_track_cblk_t::audio_track_cblk_t()
Glenn Kasten74935e42013-12-19 08:56:45 -080049 : mServer(0), mFutex(0), mMinimum(0),
Glenn Kastenc56f3422014-03-21 17:53:17 -070050 mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0), mFlags(0)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080051{
52 memset(&u, 0, sizeof(u));
53}
54
55// ---------------------------------------------------------------------------
56
57Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
58 bool isOut, bool clientInServer)
59 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
60 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
Glenn Kasten7db7df02013-06-25 16:13:23 -070061 mIsShutdown(false), mUnreleased(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080062{
63}
64
Glenn Kasten9f80dd22012-12-18 15:57:32 -080065// ---------------------------------------------------------------------------
66
67ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
68 size_t frameSize, bool isOut, bool clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080069 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
70 , mBufferSizeInFrames(frameCount)
71 , mEpoch(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080072{
Glenn Kastena8190fc2012-12-03 17:06:56 -080073}
74
Glenn Kasten9f80dd22012-12-18 15:57:32 -080075const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
76const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
77
78#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
79
80// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
81// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
82// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
83// order of minutes.
84#define MAX_SEC 5
85
86status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
87 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -080088{
Glenn Kasten7db7df02013-06-25 16:13:23 -070089 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080090 struct timespec total; // total elapsed time spent waiting
91 total.tv_sec = 0;
92 total.tv_nsec = 0;
93 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -080094
Glenn Kasten9f80dd22012-12-18 15:57:32 -080095 status_t status;
96 enum {
97 TIMEOUT_ZERO, // requested == NULL || *requested == 0
98 TIMEOUT_INFINITE, // *requested == infinity
99 TIMEOUT_FINITE, // 0 < *requested < infinity
100 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
101 } timeout;
102 if (requested == NULL) {
103 timeout = TIMEOUT_ZERO;
104 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
105 timeout = TIMEOUT_ZERO;
106 } else if (requested->tv_sec == INT_MAX) {
107 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800108 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800109 timeout = TIMEOUT_FINITE;
110 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
111 measure = true;
112 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800113 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800114 struct timespec before;
115 bool beforeIsValid = false;
116 audio_track_cblk_t* cblk = mCblk;
117 bool ignoreInitialPendingInterrupt = true;
118 // check for shared memory corruption
119 if (mIsShutdown) {
120 status = NO_INIT;
121 goto end;
122 }
123 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700124 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800125 // check for track invalidation by server, or server death detection
126 if (flags & CBLK_INVALID) {
127 ALOGV("Track invalidated");
128 status = DEAD_OBJECT;
129 goto end;
130 }
131 // check for obtainBuffer interrupted by client
132 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
133 ALOGV("obtainBuffer() interrupted by client");
134 status = -EINTR;
135 goto end;
136 }
137 ignoreInitialPendingInterrupt = false;
138 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
139 int32_t front;
140 int32_t rear;
141 if (mIsOut) {
142 // The barrier following the read of mFront is probably redundant.
143 // We're about to perform a conditional branch based on 'filled',
144 // which will force the processor to observe the read of mFront
145 // prior to allowing data writes starting at mRaw.
146 // However, the processor may support speculative execution,
147 // and be unable to undo speculative writes into shared memory.
148 // The barrier will prevent such speculative execution.
149 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
150 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800151 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800152 // On the other hand, this barrier is required.
153 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
154 front = cblk->u.mStreaming.mFront;
155 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800156 // write to rear, read from front
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800157 ssize_t filled = rear - front;
158 // pipe should not be overfull
159 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700160 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700161 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700162 "shutting down", filled, mFrameCount);
163 mIsShutdown = true;
164 status = NO_INIT;
165 goto end;
166 }
167 // for input, sync up on overrun
168 filled = 0;
169 cblk->u.mStreaming.mFront = rear;
170 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800171 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800172 // Don't allow filling pipe beyond the user settable size.
173 // The calculation for avail can go negative if the buffer size
174 // is suddenly dropped below the amount already in the buffer.
175 // So use a signed calculation to prevent a numeric overflow abort.
176 ssize_t adjustableSize = (ssize_t) mBufferSizeInFrames;
177 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
178 if (avail < 0) {
179 avail = 0;
180 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800181 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800182 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800183 if (mIsOut) {
184 rear &= mFrameCountP2 - 1;
185 part1 = mFrameCountP2 - rear;
186 } else {
187 front &= mFrameCountP2 - 1;
188 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800189 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800190 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800191 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800192 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800193 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800194 part1 = buffer->mFrameCount;
195 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800196 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800197 buffer->mRaw = part1 > 0 ?
198 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
199 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700200 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800201 status = NO_ERROR;
202 break;
203 }
204 struct timespec remaining;
205 const struct timespec *ts;
206 switch (timeout) {
207 case TIMEOUT_ZERO:
208 status = WOULD_BLOCK;
209 goto end;
210 case TIMEOUT_INFINITE:
211 ts = NULL;
212 break;
213 case TIMEOUT_FINITE:
214 timeout = TIMEOUT_CONTINUE;
215 if (MAX_SEC == 0) {
216 ts = requested;
217 break;
218 }
219 // fall through
220 case TIMEOUT_CONTINUE:
221 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
222 if (!measure || requested->tv_sec < total.tv_sec ||
223 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
224 status = TIMED_OUT;
225 goto end;
226 }
227 remaining.tv_sec = requested->tv_sec - total.tv_sec;
228 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
229 remaining.tv_nsec += 1000000000;
230 remaining.tv_sec++;
231 }
232 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
233 remaining.tv_sec = MAX_SEC;
234 remaining.tv_nsec = 0;
235 }
236 ts = &remaining;
237 break;
238 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800239 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800240 ts = NULL;
241 break;
242 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700243 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
244 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800245 if (measure && !beforeIsValid) {
246 clock_gettime(CLOCK_MONOTONIC, &before);
247 beforeIsValid = true;
248 }
Elliott Hughesee499292014-05-21 17:55:51 -0700249 errno = 0;
250 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700251 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800252 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800253 // update total elapsed time spent waiting
254 if (measure) {
255 struct timespec after;
256 clock_gettime(CLOCK_MONOTONIC, &after);
257 total.tv_sec += after.tv_sec - before.tv_sec;
258 long deltaNs = after.tv_nsec - before.tv_nsec;
259 if (deltaNs < 0) {
260 deltaNs += 1000000000;
261 total.tv_sec--;
262 }
263 if ((total.tv_nsec += deltaNs) >= 1000000000) {
264 total.tv_nsec -= 1000000000;
265 total.tv_sec++;
266 }
267 before = after;
268 beforeIsValid = true;
269 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800270 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700271 case 0: // normal wakeup by server, or by binderDied()
272 case EWOULDBLOCK: // benign race condition with server
273 case EINTR: // wait was interrupted by signal or other spurious wakeup
274 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700275 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800276 break;
277 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800278 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700279 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800280 goto end;
281 }
282 }
283 }
284
285end:
286 if (status != NO_ERROR) {
287 buffer->mFrameCount = 0;
288 buffer->mRaw = NULL;
289 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700290 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800291 }
292 if (elapsed != NULL) {
293 *elapsed = total;
294 }
295 if (requested == NULL) {
296 requested = &kNonBlocking;
297 }
298 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100299 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
300 requested->tv_sec, requested->tv_nsec / 1000000,
301 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800302 }
303 return status;
304}
305
306void ClientProxy::releaseBuffer(Buffer* buffer)
307{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700308 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800309 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700310 if (stepCount == 0 || mIsShutdown) {
311 // prevent accidental re-use of buffer
312 buffer->mFrameCount = 0;
313 buffer->mRaw = NULL;
314 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800315 return;
316 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700317 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
318 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800319 audio_track_cblk_t* cblk = mCblk;
320 // Both of these barriers are required
321 if (mIsOut) {
322 int32_t rear = cblk->u.mStreaming.mRear;
323 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
324 } else {
325 int32_t front = cblk->u.mStreaming.mFront;
326 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
327 }
328}
329
330void ClientProxy::binderDied()
331{
332 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700333 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900334 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800335 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700336 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
337 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800338 }
339}
340
341void ClientProxy::interrupt()
342{
343 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700344 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900345 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700346 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
347 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800348 }
349}
350
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700351__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800352size_t ClientProxy::getMisalignment()
353{
354 audio_track_cblk_t* cblk = mCblk;
355 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
356 (mFrameCountP2 - 1);
357}
358
Phil Burkc0adecb2016-01-08 12:44:11 -0800359size_t ClientProxy::setBufferSizeInFrames(size_t size)
360{
361 // TODO set minimum to 2X the fast mixer buffer size.
362 size_t minimum = 128 * 2; // arbitrary
363 size_t maximum = frameCount();
364 if (size < minimum) {
365 size = minimum;
366 } else if (size > maximum) {
367 size = maximum;
368 }
369 mBufferSizeInFrames = size;
370 return size;
371}
372
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800373// ---------------------------------------------------------------------------
374
375void AudioTrackClientProxy::flush()
376{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700377 // This works for mFrameCountP2 <= 2^30
378 size_t increment = mFrameCountP2 << 1;
379 size_t mask = increment - 1;
380 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700381 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
382 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
383 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700384 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
385 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
386 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800387}
388
Eric Laurentbfb1b832013-01-07 09:53:42 -0800389bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700390 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800391}
392
393bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700394 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800395}
396
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100397status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
398{
399 struct timespec total; // total elapsed time spent waiting
400 total.tv_sec = 0;
401 total.tv_nsec = 0;
402 audio_track_cblk_t* cblk = mCblk;
403 status_t status;
404 enum {
405 TIMEOUT_ZERO, // requested == NULL || *requested == 0
406 TIMEOUT_INFINITE, // *requested == infinity
407 TIMEOUT_FINITE, // 0 < *requested < infinity
408 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
409 } timeout;
410 if (requested == NULL) {
411 timeout = TIMEOUT_ZERO;
412 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
413 timeout = TIMEOUT_ZERO;
414 } else if (requested->tv_sec == INT_MAX) {
415 timeout = TIMEOUT_INFINITE;
416 } else {
417 timeout = TIMEOUT_FINITE;
418 }
419 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700420 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100421 // check for track invalidation by server, or server death detection
422 if (flags & CBLK_INVALID) {
423 ALOGV("Track invalidated");
424 status = DEAD_OBJECT;
425 goto end;
426 }
427 if (flags & CBLK_STREAM_END_DONE) {
428 ALOGV("stream end received");
429 status = NO_ERROR;
430 goto end;
431 }
432 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100433 if (flags & CBLK_INTERRUPT) {
434 ALOGV("waitStreamEndDone() interrupted by client");
435 status = -EINTR;
436 goto end;
437 }
438 struct timespec remaining;
439 const struct timespec *ts;
440 switch (timeout) {
441 case TIMEOUT_ZERO:
442 status = WOULD_BLOCK;
443 goto end;
444 case TIMEOUT_INFINITE:
445 ts = NULL;
446 break;
447 case TIMEOUT_FINITE:
448 timeout = TIMEOUT_CONTINUE;
449 if (MAX_SEC == 0) {
450 ts = requested;
451 break;
452 }
453 // fall through
454 case TIMEOUT_CONTINUE:
455 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
456 if (requested->tv_sec < total.tv_sec ||
457 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
458 status = TIMED_OUT;
459 goto end;
460 }
461 remaining.tv_sec = requested->tv_sec - total.tv_sec;
462 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
463 remaining.tv_nsec += 1000000000;
464 remaining.tv_sec++;
465 }
466 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
467 remaining.tv_sec = MAX_SEC;
468 remaining.tv_nsec = 0;
469 }
470 ts = &remaining;
471 break;
472 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800473 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100474 ts = NULL;
475 break;
476 }
477 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
478 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700479 errno = 0;
480 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100481 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700482 switch (errno) {
483 case 0: // normal wakeup by server, or by binderDied()
484 case EWOULDBLOCK: // benign race condition with server
485 case EINTR: // wait was interrupted by signal or other spurious wakeup
486 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100487 break;
488 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700489 status = errno;
490 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100491 goto end;
492 }
493 }
494 }
495
496end:
497 if (requested == NULL) {
498 requested = &kNonBlocking;
499 }
500 return status;
501}
502
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800503// ---------------------------------------------------------------------------
504
505StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
506 size_t frameCount, size_t frameSize)
507 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800508 mMutator(&cblk->u.mStatic.mSingleStateQueue),
509 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800510{
Andy Hung9b461582014-12-01 17:56:29 -0800511 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800512 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800513}
514
515void StaticAudioTrackClientProxy::flush()
516{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800517 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800518}
519
520void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
521{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800522 // This can only happen on a 64-bit client
523 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
524 // FIXME Should return an error status
525 return;
526 }
Andy Hung9b461582014-12-01 17:56:29 -0800527 mState.mLoopStart = (uint32_t) loopStart;
528 mState.mLoopEnd = (uint32_t) loopEnd;
529 mState.mLoopCount = loopCount;
530 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
531 // set patch-up variables until the mState is acknowledged by the ServerProxy.
532 // observed buffer position and loop count will freeze until then to give the
533 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800534 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800535 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800536 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
537 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800538 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800539 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800540 (void) mMutator.push(mState);
541}
542
543void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
544{
545 // This can only happen on a 64-bit client
546 if (position > UINT32_MAX) {
547 // FIXME Should return an error status
548 return;
549 }
550 mState.mPosition = (uint32_t) position;
551 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800552 // set patch-up variables until the mState is acknowledged by the ServerProxy.
553 // observed buffer position and loop count will freeze until then to give the
554 // illusion of a synchronous change.
555 if (mState.mLoopCount > 0) { // only check if loop count is changing
556 getBufferPositionAndLoopCount(NULL, NULL); // get last position
557 }
558 mPosLoop.mBufferPosition = position;
559 if (position >= mState.mLoopEnd) {
560 // no ongoing loop is possible if position is greater than loopEnd.
561 mPosLoop.mLoopCount = 0;
562 }
Andy Hung9b461582014-12-01 17:56:29 -0800563 (void) mMutator.push(mState);
564}
565
566void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
567 size_t loopEnd, int loopCount)
568{
569 setLoop(loopStart, loopEnd, loopCount);
570 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800571}
572
573size_t StaticAudioTrackClientProxy::getBufferPosition()
574{
Andy Hung4ede21d2014-12-12 15:37:34 -0800575 getBufferPositionAndLoopCount(NULL, NULL);
576 return mPosLoop.mBufferPosition;
577}
578
579void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
580 size_t *position, int *loopCount)
581{
582 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
583 if (mPosLoopObserver.poll(mPosLoop)) {
584 ; // a valid mPosLoop should be available if ackDone is true.
585 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800586 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800587 if (position != NULL) {
588 *position = mPosLoop.mBufferPosition;
589 }
590 if (loopCount != NULL) {
591 *loopCount = mPosLoop.mLoopCount;
592 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800593}
594
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800595// ---------------------------------------------------------------------------
596
597ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
598 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700599 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Glenn Kastence8828a2013-09-16 18:07:38 -0700600 mAvailToClient(0), mFlush(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800601{
Glenn Kastena8190fc2012-12-03 17:06:56 -0800602}
603
Glenn Kasten2e422c42013-10-18 13:00:29 -0700604status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800605{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700606 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800607 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700608 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800609 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700610 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800611 audio_track_cblk_t* cblk = mCblk;
612 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
613 // or use previous cached value from framesReady(), with added barrier if it omits.
614 int32_t front;
615 int32_t rear;
616 // See notes on barriers at ClientProxy::obtainBuffer()
617 if (mIsOut) {
618 int32_t flush = cblk->u.mStreaming.mFlush;
619 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100620 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800621 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700622 // effectively obtain then release whatever is in the buffer
Andy Hunga2d75cd2015-07-15 17:04:20 -0700623 const size_t overflowBit = mFrameCountP2 << 1;
624 const size_t mask = overflowBit - 1;
Glenn Kasten20f51b12014-10-30 10:43:19 -0700625 int32_t newFront = (front & ~mask) | (flush & mask);
626 ssize_t filled = rear - newFront;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700627 if (filled >= (ssize_t)overflowBit) {
628 // front and rear offsets span the overflow bit of the p2 mask
629 // so rebasing newFront on the front offset is off by the overflow bit.
630 // adjust newFront to match rear offset.
Glenn Kastendbd0f3c2015-07-17 11:04:04 -0700631 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hunga2d75cd2015-07-15 17:04:20 -0700632 newFront += overflowBit;
633 filled -= overflowBit;
634 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700635 // Rather than shutting down on a corrupt flush, just treat it as a full flush
636 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800637 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
Lajos Molnarf1063e22015-04-17 15:19:42 -0700638 "filled %zd=%#x",
639 mFlush, flush, front, rear,
640 (unsigned)mask, newFront, filled, (unsigned)filled);
Glenn Kasten20f51b12014-10-30 10:43:19 -0700641 newFront = rear;
642 }
643 mFlush = flush;
644 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
645 // There is no danger from a false positive, so err on the side of caution
646 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100647 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
648 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700649 (void) syscall(__NR_futex, &cblk->mFutex,
650 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100651 }
652 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700653 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800654 }
655 } else {
656 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
657 rear = cblk->u.mStreaming.mRear;
658 }
659 ssize_t filled = rear - front;
660 // pipe should not already be overfull
661 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700662 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800663 mIsShutdown = true;
664 }
665 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700666 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800667 }
668 // don't allow filling pipe beyond the nominal size
669 size_t availToServer;
670 if (mIsOut) {
671 availToServer = filled;
672 mAvailToClient = mFrameCount - filled;
673 } else {
674 availToServer = mFrameCount - filled;
675 mAvailToClient = filled;
676 }
677 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
678 size_t part1;
679 if (mIsOut) {
680 front &= mFrameCountP2 - 1;
681 part1 = mFrameCountP2 - front;
682 } else {
683 rear &= mFrameCountP2 - 1;
684 part1 = mFrameCountP2 - rear;
685 }
686 if (part1 > availToServer) {
687 part1 = availToServer;
688 }
689 size_t ask = buffer->mFrameCount;
690 if (part1 > ask) {
691 part1 = ask;
692 }
693 // is assignment redundant in some cases?
694 buffer->mFrameCount = part1;
695 buffer->mRaw = part1 > 0 ?
696 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
697 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700698 // After flush(), allow releaseBuffer() on a previously obtained buffer;
699 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
700 if (!ackFlush) {
701 mUnreleased = part1;
702 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800703 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700704 }
705no_init:
706 buffer->mFrameCount = 0;
707 buffer->mRaw = NULL;
708 buffer->mNonContig = 0;
709 mUnreleased = 0;
710 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800711}
712
713void ServerProxy::releaseBuffer(Buffer* buffer)
714{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700715 LOG_ALWAYS_FATAL_IF(buffer == NULL);
716 size_t stepCount = buffer->mFrameCount;
717 if (stepCount == 0 || mIsShutdown) {
718 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800719 buffer->mFrameCount = 0;
720 buffer->mRaw = NULL;
721 buffer->mNonContig = 0;
722 return;
723 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700724 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800725 mUnreleased -= stepCount;
726 audio_track_cblk_t* cblk = mCblk;
727 if (mIsOut) {
728 int32_t front = cblk->u.mStreaming.mFront;
729 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
730 } else {
731 int32_t rear = cblk->u.mStreaming.mRear;
732 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
733 }
734
Glenn Kasten844f88c2014-05-09 13:38:09 -0700735 cblk->mServer += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800736
737 size_t half = mFrameCount / 2;
738 if (half == 0) {
739 half = 1;
740 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800741 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800742 if (minimum == 0) {
743 minimum = mIsOut ? half : 1;
744 } else if (minimum > half) {
745 minimum = half;
746 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700747 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700748 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700749 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700750 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
751 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700752 (void) syscall(__NR_futex, &cblk->mFutex,
753 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800754 }
755 }
756
757 buffer->mFrameCount = 0;
758 buffer->mRaw = NULL;
759 buffer->mNonContig = 0;
760}
761
762// ---------------------------------------------------------------------------
763
764size_t AudioTrackServerProxy::framesReady()
765{
766 LOG_ALWAYS_FATAL_IF(!mIsOut);
767
768 if (mIsShutdown) {
769 return 0;
770 }
771 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100772
773 int32_t flush = cblk->u.mStreaming.mFlush;
774 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700775 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100776 return mFrameCount;
777 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800778 // the acquire might not be necessary since not doing a subsequent read
779 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
780 ssize_t filled = rear - cblk->u.mStreaming.mFront;
781 // pipe should not already be overfull
782 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700783 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800784 mIsShutdown = true;
785 return 0;
786 }
787 // cache this value for later use by obtainBuffer(), with added barrier
788 // and racy if called by normal mixer thread
789 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
790 return filled;
791}
792
Eric Laurentbfb1b832013-01-07 09:53:42 -0800793bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700794 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800795 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700796 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800797 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700798 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700799 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800800 }
801 return old;
802}
803
Glenn Kasten82aaf942013-07-17 16:05:07 -0700804void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
805{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700806 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800807 if (frameCount > 0) {
808 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700809
Phil Burk2812d9e2016-01-04 10:34:30 -0800810 if (!mUnderrunning) { // start of underrun?
811 mUnderrunCount++;
812 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
813 mUnderrunning = true;
814 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
815 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
816 }
817
818 // FIXME also wake futex so that underrun is noticed more quickly
819 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
820 } else {
821 ALOGV_IF(mUnderrunning,
822 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
823 frameCount, cblk->u.mStreaming.mUnderrunFrames);
824 mUnderrunning = false; // so we can detect the next edge
825 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700826}
827
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700828AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700829{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700830 mPlaybackRateObserver.poll(mPlaybackRate);
831 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700832}
833
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800834// ---------------------------------------------------------------------------
835
836StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
837 size_t frameCount, size_t frameSize)
838 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800839 mObserver(&cblk->u.mStatic.mSingleStateQueue),
840 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800841 mFramesReadySafe(frameCount), mFramesReady(frameCount),
842 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800843{
Andy Hung9b461582014-12-01 17:56:29 -0800844 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800845}
846
847void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
848{
849 mFramesReadyIsCalledByMultipleThreads = true;
850}
851
852size_t StaticAudioTrackServerProxy::framesReady()
853{
Andy Hungcb2129b2014-11-11 12:17:22 -0800854 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800855 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800856 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800857 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800858 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800859}
860
Andy Hung9b461582014-12-01 17:56:29 -0800861status_t StaticAudioTrackServerProxy::updateStateWithLoop(
862 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800863{
Andy Hung9b461582014-12-01 17:56:29 -0800864 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800865 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800866 const size_t loopStart = update.mLoopStart;
867 const size_t loopEnd = update.mLoopEnd;
868 size_t position = localState->mPosition;
869 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800870 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800871 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800872 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
873 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800874 // If the current position is greater than the end of the loop
875 // we "wrap" to the loop start. This might cause an audible pop.
876 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800877 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800878 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800879 valid = true;
880 }
881 }
Andy Hung9b461582014-12-01 17:56:29 -0800882 if (!valid || position > mFrameCount) {
883 return NO_INIT;
884 }
885 localState->mPosition = position;
886 localState->mLoopCount = update.mLoopCount;
887 localState->mLoopEnd = loopEnd;
888 localState->mLoopStart = loopStart;
889 localState->mLoopSequence = update.mLoopSequence;
890 }
891 return OK;
892}
893
894status_t StaticAudioTrackServerProxy::updateStateWithPosition(
895 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
896{
897 if (localState->mPositionSequence != update.mPositionSequence) {
898 if (update.mPosition > mFrameCount) {
899 return NO_INIT;
900 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
901 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
902 }
903 localState->mPosition = update.mPosition;
904 localState->mPositionSequence = update.mPositionSequence;
905 }
906 return OK;
907}
908
909ssize_t StaticAudioTrackServerProxy::pollPosition()
910{
911 StaticAudioTrackState state;
912 if (mObserver.poll(state)) {
913 StaticAudioTrackState trystate = mState;
914 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700915 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800916
917 if (diffSeq < 0) {
918 result = updateStateWithLoop(&trystate, state) == OK &&
919 updateStateWithPosition(&trystate, state) == OK;
920 } else {
921 result = updateStateWithPosition(&trystate, state) == OK &&
922 updateStateWithLoop(&trystate, state) == OK;
923 }
924 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800925 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800926 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800927 ALOGE("%s client pushed an invalid state, shutting down", __func__);
928 mIsShutdown = true;
929 return (ssize_t) NO_INIT;
930 }
Andy Hung9b461582014-12-01 17:56:29 -0800931 mState = trystate;
932 if (mState.mLoopCount == -1) {
933 mFramesReady = INT64_MAX;
934 } else if (mState.mLoopCount == 0) {
935 mFramesReady = mFrameCount - mState.mPosition;
936 } else if (mState.mLoopCount > 0) {
937 // TODO: Later consider fixing overflow, but does not seem needed now
938 // as will not overflow if loopStart and loopEnd are Java "ints".
939 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
940 + mFrameCount - mState.mPosition;
941 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800942 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800943 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800944 StaticAudioTrackPosLoop posLoop;
945
946 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
947 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
948 mPosLoopMutator.push(posLoop);
949 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800950 }
Andy Hung9b461582014-12-01 17:56:29 -0800951 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800952}
953
Andy Hung954ca452015-09-09 14:39:02 -0700954status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800955{
956 if (mIsShutdown) {
957 buffer->mFrameCount = 0;
958 buffer->mRaw = NULL;
959 buffer->mNonContig = 0;
960 mUnreleased = 0;
961 return NO_INIT;
962 }
963 ssize_t positionOrStatus = pollPosition();
964 if (positionOrStatus < 0) {
965 buffer->mFrameCount = 0;
966 buffer->mRaw = NULL;
967 buffer->mNonContig = 0;
968 mUnreleased = 0;
969 return (status_t) positionOrStatus;
970 }
971 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800972 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800973 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800974 if (position < end) {
975 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800976 size_t wanted = buffer->mFrameCount;
977 if (avail < wanted) {
978 buffer->mFrameCount = avail;
979 } else {
980 avail = wanted;
981 }
982 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
983 } else {
984 avail = 0;
985 buffer->mFrameCount = 0;
986 buffer->mRaw = NULL;
987 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800988 // As mFramesReady is the total remaining frames in the static audio track,
989 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -0800990 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -0800991 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -0700992 if (!ackFlush) {
993 mUnreleased = avail;
994 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800995 return NO_ERROR;
996}
997
998void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
999{
1000 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -08001001 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -07001002 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001003 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001004 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001005 buffer->mRaw = NULL;
1006 buffer->mNonContig = 0;
1007 return;
1008 }
1009 mUnreleased -= stepCount;
1010 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001011 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001012 size_t newPosition = position + stepCount;
1013 int32_t setFlags = 0;
1014 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001015 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1016 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001017 newPosition = mFrameCount;
1018 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001019 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001020 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001021 setFlags = CBLK_LOOP_CYCLE;
1022 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001023 setFlags = CBLK_LOOP_FINAL;
1024 }
1025 }
1026 if (newPosition == mFrameCount) {
1027 setFlags |= CBLK_BUFFER_END;
1028 }
Andy Hung9b461582014-12-01 17:56:29 -08001029 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001030 if (mFramesReady != INT64_MAX) {
1031 mFramesReady -= stepCount;
1032 }
1033 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001034
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001035 cblk->mServer += stepCount;
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001036 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001037 StaticAudioTrackPosLoop posLoop;
1038 posLoop.mBufferPosition = mState.mPosition;
1039 posLoop.mLoopCount = mState.mLoopCount;
1040 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001041 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001042 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001043 // this would be a good place to wake a futex
1044 }
1045
1046 buffer->mFrameCount = 0;
1047 buffer->mRaw = NULL;
1048 buffer->mNonContig = 0;
1049}
1050
Phil Burk2812d9e2016-01-04 10:34:30 -08001051void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001052{
1053 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1054 // we don't have a location to count underrun frames. The underrun frame counter
1055 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1056 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1057
1058 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001059 if (frameCount > 0) {
1060 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1061 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001062}
1063
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001064// ---------------------------------------------------------------------------
1065
Glenn Kastena8190fc2012-12-03 17:06:56 -08001066} // namespace android