blob: 7d7134ac5b9822f6109c6aa4cc03d94b243d21e2 [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()
Phil Burke8972b02016-03-04 11:29:57 -080049 : mServer(0), mFutex(0), mMinimum(0)
50 , mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0)
51 , mBufferSizeInFrames(0)
52 , mFlags(0)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080053{
54 memset(&u, 0, sizeof(u));
55}
56
57// ---------------------------------------------------------------------------
58
59Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
60 bool isOut, bool clientInServer)
61 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
62 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
Glenn Kasten7db7df02013-06-25 16:13:23 -070063 mIsShutdown(false), mUnreleased(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080064{
65}
66
Glenn Kasten9f80dd22012-12-18 15:57:32 -080067// ---------------------------------------------------------------------------
68
69ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
70 size_t frameSize, bool isOut, bool clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080071 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080072 , mEpoch(0)
Andy Hung6ae58432016-02-16 18:32:24 -080073 , mTimestampObserver(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -080074{
Phil Burke8972b02016-03-04 11:29:57 -080075 setBufferSizeInFrames(frameCount);
Glenn Kastena8190fc2012-12-03 17:06:56 -080076}
77
Glenn Kasten9f80dd22012-12-18 15:57:32 -080078const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
79const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
80
81#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
82
83// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
84// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
85// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
86// order of minutes.
87#define MAX_SEC 5
88
Phil Burke8972b02016-03-04 11:29:57 -080089uint32_t ClientProxy::setBufferSizeInFrames(uint32_t size)
90{
91 // TODO set minimum to 2X the fast mixer buffer size.
92 // The minimum should be greater than zero and less than the size
93 // at which underruns will occur.
94 const uint32_t minimum = 128 * 2; // arbitrary
95 const uint32_t maximum = frameCount();
96 uint32_t clippedSize = size;
97 if (clippedSize < minimum) {
98 clippedSize = minimum;
99 } else if (clippedSize > maximum) {
100 clippedSize = maximum;
101 }
102 // for server to read
103 android_atomic_release_store(clippedSize, (int32_t *)&mCblk->mBufferSizeInFrames);
104 // for client to read
105 mBufferSizeInFrames = clippedSize;
106 return clippedSize;
107}
108
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800109status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
110 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800111{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700112 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800113 struct timespec total; // total elapsed time spent waiting
114 total.tv_sec = 0;
115 total.tv_nsec = 0;
116 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -0800117
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800118 status_t status;
119 enum {
120 TIMEOUT_ZERO, // requested == NULL || *requested == 0
121 TIMEOUT_INFINITE, // *requested == infinity
122 TIMEOUT_FINITE, // 0 < *requested < infinity
123 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
124 } timeout;
125 if (requested == NULL) {
126 timeout = TIMEOUT_ZERO;
127 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
128 timeout = TIMEOUT_ZERO;
129 } else if (requested->tv_sec == INT_MAX) {
130 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800131 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800132 timeout = TIMEOUT_FINITE;
133 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
134 measure = true;
135 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800136 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800137 struct timespec before;
138 bool beforeIsValid = false;
139 audio_track_cblk_t* cblk = mCblk;
140 bool ignoreInitialPendingInterrupt = true;
141 // check for shared memory corruption
142 if (mIsShutdown) {
143 status = NO_INIT;
144 goto end;
145 }
146 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700147 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800148 // check for track invalidation by server, or server death detection
149 if (flags & CBLK_INVALID) {
150 ALOGV("Track invalidated");
151 status = DEAD_OBJECT;
152 goto end;
153 }
154 // check for obtainBuffer interrupted by client
155 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
156 ALOGV("obtainBuffer() interrupted by client");
157 status = -EINTR;
158 goto end;
159 }
160 ignoreInitialPendingInterrupt = false;
161 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
162 int32_t front;
163 int32_t rear;
164 if (mIsOut) {
165 // The barrier following the read of mFront is probably redundant.
166 // We're about to perform a conditional branch based on 'filled',
167 // which will force the processor to observe the read of mFront
168 // prior to allowing data writes starting at mRaw.
169 // However, the processor may support speculative execution,
170 // and be unable to undo speculative writes into shared memory.
171 // The barrier will prevent such speculative execution.
172 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
173 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800174 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800175 // On the other hand, this barrier is required.
176 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
177 front = cblk->u.mStreaming.mFront;
178 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800179 // write to rear, read from front
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800180 ssize_t filled = rear - front;
181 // pipe should not be overfull
182 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700183 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700184 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700185 "shutting down", filled, mFrameCount);
186 mIsShutdown = true;
187 status = NO_INIT;
188 goto end;
189 }
190 // for input, sync up on overrun
191 filled = 0;
192 cblk->u.mStreaming.mFront = rear;
193 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800194 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800195 // Don't allow filling pipe beyond the user settable size.
196 // The calculation for avail can go negative if the buffer size
197 // is suddenly dropped below the amount already in the buffer.
198 // So use a signed calculation to prevent a numeric overflow abort.
Phil Burke8972b02016-03-04 11:29:57 -0800199 ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800200 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
201 if (avail < 0) {
202 avail = 0;
203 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800204 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800205 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800206 if (mIsOut) {
207 rear &= mFrameCountP2 - 1;
208 part1 = mFrameCountP2 - rear;
209 } else {
210 front &= mFrameCountP2 - 1;
211 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800212 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800213 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800214 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800215 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800216 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800217 part1 = buffer->mFrameCount;
218 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800219 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800220 buffer->mRaw = part1 > 0 ?
221 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
222 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700223 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224 status = NO_ERROR;
225 break;
226 }
227 struct timespec remaining;
228 const struct timespec *ts;
229 switch (timeout) {
230 case TIMEOUT_ZERO:
231 status = WOULD_BLOCK;
232 goto end;
233 case TIMEOUT_INFINITE:
234 ts = NULL;
235 break;
236 case TIMEOUT_FINITE:
237 timeout = TIMEOUT_CONTINUE;
238 if (MAX_SEC == 0) {
239 ts = requested;
240 break;
241 }
242 // fall through
243 case TIMEOUT_CONTINUE:
244 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
245 if (!measure || requested->tv_sec < total.tv_sec ||
246 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
247 status = TIMED_OUT;
248 goto end;
249 }
250 remaining.tv_sec = requested->tv_sec - total.tv_sec;
251 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
252 remaining.tv_nsec += 1000000000;
253 remaining.tv_sec++;
254 }
255 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
256 remaining.tv_sec = MAX_SEC;
257 remaining.tv_nsec = 0;
258 }
259 ts = &remaining;
260 break;
261 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800262 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800263 ts = NULL;
264 break;
265 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700266 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
267 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800268 if (measure && !beforeIsValid) {
269 clock_gettime(CLOCK_MONOTONIC, &before);
270 beforeIsValid = true;
271 }
Elliott Hughesee499292014-05-21 17:55:51 -0700272 errno = 0;
273 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700274 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800275 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800276 // update total elapsed time spent waiting
277 if (measure) {
278 struct timespec after;
279 clock_gettime(CLOCK_MONOTONIC, &after);
280 total.tv_sec += after.tv_sec - before.tv_sec;
281 long deltaNs = after.tv_nsec - before.tv_nsec;
282 if (deltaNs < 0) {
283 deltaNs += 1000000000;
284 total.tv_sec--;
285 }
286 if ((total.tv_nsec += deltaNs) >= 1000000000) {
287 total.tv_nsec -= 1000000000;
288 total.tv_sec++;
289 }
290 before = after;
291 beforeIsValid = true;
292 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800293 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700294 case 0: // normal wakeup by server, or by binderDied()
295 case EWOULDBLOCK: // benign race condition with server
296 case EINTR: // wait was interrupted by signal or other spurious wakeup
297 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700298 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800299 break;
300 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800301 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700302 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800303 goto end;
304 }
305 }
306 }
307
308end:
309 if (status != NO_ERROR) {
310 buffer->mFrameCount = 0;
311 buffer->mRaw = NULL;
312 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700313 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800314 }
315 if (elapsed != NULL) {
316 *elapsed = total;
317 }
318 if (requested == NULL) {
319 requested = &kNonBlocking;
320 }
321 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100322 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
323 requested->tv_sec, requested->tv_nsec / 1000000,
324 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800325 }
326 return status;
327}
328
329void ClientProxy::releaseBuffer(Buffer* buffer)
330{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700331 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800332 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700333 if (stepCount == 0 || mIsShutdown) {
334 // prevent accidental re-use of buffer
335 buffer->mFrameCount = 0;
336 buffer->mRaw = NULL;
337 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800338 return;
339 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700340 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
341 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800342 audio_track_cblk_t* cblk = mCblk;
343 // Both of these barriers are required
344 if (mIsOut) {
345 int32_t rear = cblk->u.mStreaming.mRear;
346 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
347 } else {
348 int32_t front = cblk->u.mStreaming.mFront;
349 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
350 }
351}
352
353void ClientProxy::binderDied()
354{
355 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700356 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900357 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800358 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700359 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
360 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800361 }
362}
363
364void ClientProxy::interrupt()
365{
366 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700367 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900368 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700369 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
370 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800371 }
372}
373
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700374__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800375size_t ClientProxy::getMisalignment()
376{
377 audio_track_cblk_t* cblk = mCblk;
378 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
379 (mFrameCountP2 - 1);
380}
381
382// ---------------------------------------------------------------------------
383
384void AudioTrackClientProxy::flush()
385{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700386 // This works for mFrameCountP2 <= 2^30
387 size_t increment = mFrameCountP2 << 1;
388 size_t mask = increment - 1;
389 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700390 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
391 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
392 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700393 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
394 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
395 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800396}
397
Eric Laurentbfb1b832013-01-07 09:53:42 -0800398bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700399 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800400}
401
402bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700403 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800404}
405
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100406status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
407{
408 struct timespec total; // total elapsed time spent waiting
409 total.tv_sec = 0;
410 total.tv_nsec = 0;
411 audio_track_cblk_t* cblk = mCblk;
412 status_t status;
413 enum {
414 TIMEOUT_ZERO, // requested == NULL || *requested == 0
415 TIMEOUT_INFINITE, // *requested == infinity
416 TIMEOUT_FINITE, // 0 < *requested < infinity
417 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
418 } timeout;
419 if (requested == NULL) {
420 timeout = TIMEOUT_ZERO;
421 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
422 timeout = TIMEOUT_ZERO;
423 } else if (requested->tv_sec == INT_MAX) {
424 timeout = TIMEOUT_INFINITE;
425 } else {
426 timeout = TIMEOUT_FINITE;
427 }
428 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700429 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100430 // check for track invalidation by server, or server death detection
431 if (flags & CBLK_INVALID) {
432 ALOGV("Track invalidated");
433 status = DEAD_OBJECT;
434 goto end;
435 }
436 if (flags & CBLK_STREAM_END_DONE) {
437 ALOGV("stream end received");
438 status = NO_ERROR;
439 goto end;
440 }
441 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100442 if (flags & CBLK_INTERRUPT) {
443 ALOGV("waitStreamEndDone() interrupted by client");
444 status = -EINTR;
445 goto end;
446 }
447 struct timespec remaining;
448 const struct timespec *ts;
449 switch (timeout) {
450 case TIMEOUT_ZERO:
451 status = WOULD_BLOCK;
452 goto end;
453 case TIMEOUT_INFINITE:
454 ts = NULL;
455 break;
456 case TIMEOUT_FINITE:
457 timeout = TIMEOUT_CONTINUE;
458 if (MAX_SEC == 0) {
459 ts = requested;
460 break;
461 }
462 // fall through
463 case TIMEOUT_CONTINUE:
464 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
465 if (requested->tv_sec < total.tv_sec ||
466 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
467 status = TIMED_OUT;
468 goto end;
469 }
470 remaining.tv_sec = requested->tv_sec - total.tv_sec;
471 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
472 remaining.tv_nsec += 1000000000;
473 remaining.tv_sec++;
474 }
475 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
476 remaining.tv_sec = MAX_SEC;
477 remaining.tv_nsec = 0;
478 }
479 ts = &remaining;
480 break;
481 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800482 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100483 ts = NULL;
484 break;
485 }
486 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
487 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700488 errno = 0;
489 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100490 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700491 switch (errno) {
492 case 0: // normal wakeup by server, or by binderDied()
493 case EWOULDBLOCK: // benign race condition with server
494 case EINTR: // wait was interrupted by signal or other spurious wakeup
495 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100496 break;
497 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700498 status = errno;
499 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100500 goto end;
501 }
502 }
503 }
504
505end:
506 if (requested == NULL) {
507 requested = &kNonBlocking;
508 }
509 return status;
510}
511
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800512// ---------------------------------------------------------------------------
513
514StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
515 size_t frameCount, size_t frameSize)
516 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800517 mMutator(&cblk->u.mStatic.mSingleStateQueue),
518 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519{
Andy Hung9b461582014-12-01 17:56:29 -0800520 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800521 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800522}
523
524void StaticAudioTrackClientProxy::flush()
525{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800526 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527}
528
529void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
530{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800531 // This can only happen on a 64-bit client
532 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
533 // FIXME Should return an error status
534 return;
535 }
Andy Hung9b461582014-12-01 17:56:29 -0800536 mState.mLoopStart = (uint32_t) loopStart;
537 mState.mLoopEnd = (uint32_t) loopEnd;
538 mState.mLoopCount = loopCount;
539 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
540 // set patch-up variables until the mState is acknowledged by the ServerProxy.
541 // observed buffer position and loop count will freeze until then to give the
542 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800543 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800544 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800545 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
546 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800547 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800548 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800549 (void) mMutator.push(mState);
550}
551
552void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
553{
554 // This can only happen on a 64-bit client
555 if (position > UINT32_MAX) {
556 // FIXME Should return an error status
557 return;
558 }
559 mState.mPosition = (uint32_t) position;
560 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800561 // set patch-up variables until the mState is acknowledged by the ServerProxy.
562 // observed buffer position and loop count will freeze until then to give the
563 // illusion of a synchronous change.
564 if (mState.mLoopCount > 0) { // only check if loop count is changing
565 getBufferPositionAndLoopCount(NULL, NULL); // get last position
566 }
567 mPosLoop.mBufferPosition = position;
568 if (position >= mState.mLoopEnd) {
569 // no ongoing loop is possible if position is greater than loopEnd.
570 mPosLoop.mLoopCount = 0;
571 }
Andy Hung9b461582014-12-01 17:56:29 -0800572 (void) mMutator.push(mState);
573}
574
575void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
576 size_t loopEnd, int loopCount)
577{
578 setLoop(loopStart, loopEnd, loopCount);
579 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800580}
581
582size_t StaticAudioTrackClientProxy::getBufferPosition()
583{
Andy Hung4ede21d2014-12-12 15:37:34 -0800584 getBufferPositionAndLoopCount(NULL, NULL);
585 return mPosLoop.mBufferPosition;
586}
587
588void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
589 size_t *position, int *loopCount)
590{
591 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
592 if (mPosLoopObserver.poll(mPosLoop)) {
593 ; // a valid mPosLoop should be available if ackDone is true.
594 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800595 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800596 if (position != NULL) {
597 *position = mPosLoop.mBufferPosition;
598 }
599 if (loopCount != NULL) {
600 *loopCount = mPosLoop.mLoopCount;
601 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800602}
603
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604// ---------------------------------------------------------------------------
605
606ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
607 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700608 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hung3f0c9022016-01-15 17:49:46 -0800609 mAvailToClient(0), mFlush(0), mReleased(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800610 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800611{
Phil Burke8972b02016-03-04 11:29:57 -0800612 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800613}
614
Glenn Kasten2e422c42013-10-18 13:00:29 -0700615status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800616{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700617 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800618 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700619 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800620 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700621 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800622 audio_track_cblk_t* cblk = mCblk;
623 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
624 // or use previous cached value from framesReady(), with added barrier if it omits.
625 int32_t front;
626 int32_t rear;
627 // See notes on barriers at ClientProxy::obtainBuffer()
628 if (mIsOut) {
629 int32_t flush = cblk->u.mStreaming.mFlush;
630 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100631 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800632 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700633 // effectively obtain then release whatever is in the buffer
Andy Hunga2d75cd2015-07-15 17:04:20 -0700634 const size_t overflowBit = mFrameCountP2 << 1;
635 const size_t mask = overflowBit - 1;
Glenn Kasten20f51b12014-10-30 10:43:19 -0700636 int32_t newFront = (front & ~mask) | (flush & mask);
637 ssize_t filled = rear - newFront;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700638 if (filled >= (ssize_t)overflowBit) {
639 // front and rear offsets span the overflow bit of the p2 mask
640 // so rebasing newFront on the front offset is off by the overflow bit.
641 // adjust newFront to match rear offset.
Glenn Kastendbd0f3c2015-07-17 11:04:04 -0700642 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hunga2d75cd2015-07-15 17:04:20 -0700643 newFront += overflowBit;
644 filled -= overflowBit;
645 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700646 // Rather than shutting down on a corrupt flush, just treat it as a full flush
647 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800648 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
Lajos Molnarf1063e22015-04-17 15:19:42 -0700649 "filled %zd=%#x",
650 mFlush, flush, front, rear,
651 (unsigned)mask, newFront, filled, (unsigned)filled);
Glenn Kasten20f51b12014-10-30 10:43:19 -0700652 newFront = rear;
653 }
654 mFlush = flush;
655 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
656 // There is no danger from a false positive, so err on the side of caution
657 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100658 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
659 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700660 (void) syscall(__NR_futex, &cblk->mFutex,
661 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100662 }
663 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700664 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800665 }
666 } else {
667 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
668 rear = cblk->u.mStreaming.mRear;
669 }
670 ssize_t filled = rear - front;
671 // pipe should not already be overfull
672 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700673 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800674 mIsShutdown = true;
675 }
676 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700677 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800678 }
679 // don't allow filling pipe beyond the nominal size
680 size_t availToServer;
681 if (mIsOut) {
682 availToServer = filled;
683 mAvailToClient = mFrameCount - filled;
684 } else {
685 availToServer = mFrameCount - filled;
686 mAvailToClient = filled;
687 }
688 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
689 size_t part1;
690 if (mIsOut) {
691 front &= mFrameCountP2 - 1;
692 part1 = mFrameCountP2 - front;
693 } else {
694 rear &= mFrameCountP2 - 1;
695 part1 = mFrameCountP2 - rear;
696 }
697 if (part1 > availToServer) {
698 part1 = availToServer;
699 }
700 size_t ask = buffer->mFrameCount;
701 if (part1 > ask) {
702 part1 = ask;
703 }
704 // is assignment redundant in some cases?
705 buffer->mFrameCount = part1;
706 buffer->mRaw = part1 > 0 ?
707 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
708 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700709 // After flush(), allow releaseBuffer() on a previously obtained buffer;
710 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
711 if (!ackFlush) {
712 mUnreleased = part1;
713 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800714 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700715 }
716no_init:
717 buffer->mFrameCount = 0;
718 buffer->mRaw = NULL;
719 buffer->mNonContig = 0;
720 mUnreleased = 0;
721 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800722}
723
724void ServerProxy::releaseBuffer(Buffer* buffer)
725{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700726 LOG_ALWAYS_FATAL_IF(buffer == NULL);
727 size_t stepCount = buffer->mFrameCount;
728 if (stepCount == 0 || mIsShutdown) {
729 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800730 buffer->mFrameCount = 0;
731 buffer->mRaw = NULL;
732 buffer->mNonContig = 0;
733 return;
734 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700735 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800736 mUnreleased -= stepCount;
737 audio_track_cblk_t* cblk = mCblk;
738 if (mIsOut) {
739 int32_t front = cblk->u.mStreaming.mFront;
740 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
741 } else {
742 int32_t rear = cblk->u.mStreaming.mRear;
743 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
744 }
745
Glenn Kasten844f88c2014-05-09 13:38:09 -0700746 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800747 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800748
749 size_t half = mFrameCount / 2;
750 if (half == 0) {
751 half = 1;
752 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800753 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800754 if (minimum == 0) {
755 minimum = mIsOut ? half : 1;
756 } else if (minimum > half) {
757 minimum = half;
758 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700759 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700760 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700761 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700762 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
763 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700764 (void) syscall(__NR_futex, &cblk->mFutex,
765 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800766 }
767 }
768
769 buffer->mFrameCount = 0;
770 buffer->mRaw = NULL;
771 buffer->mNonContig = 0;
772}
773
774// ---------------------------------------------------------------------------
775
776size_t AudioTrackServerProxy::framesReady()
777{
778 LOG_ALWAYS_FATAL_IF(!mIsOut);
779
780 if (mIsShutdown) {
781 return 0;
782 }
783 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100784
785 int32_t flush = cblk->u.mStreaming.mFlush;
786 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700787 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100788 return mFrameCount;
789 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800790 // the acquire might not be necessary since not doing a subsequent read
791 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
792 ssize_t filled = rear - cblk->u.mStreaming.mFront;
793 // pipe should not already be overfull
794 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700795 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800796 mIsShutdown = true;
797 return 0;
798 }
799 // cache this value for later use by obtainBuffer(), with added barrier
800 // and racy if called by normal mixer thread
801 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
802 return filled;
803}
804
Eric Laurentbfb1b832013-01-07 09:53:42 -0800805bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700806 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800807 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700808 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800809 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700810 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700811 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800812 }
813 return old;
814}
815
Glenn Kasten82aaf942013-07-17 16:05:07 -0700816void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
817{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700818 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800819 if (frameCount > 0) {
820 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700821
Phil Burk2812d9e2016-01-04 10:34:30 -0800822 if (!mUnderrunning) { // start of underrun?
823 mUnderrunCount++;
824 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
825 mUnderrunning = true;
826 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
827 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
828 }
829
830 // FIXME also wake futex so that underrun is noticed more quickly
831 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
832 } else {
833 ALOGV_IF(mUnderrunning,
834 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
835 frameCount, cblk->u.mStreaming.mUnderrunFrames);
836 mUnderrunning = false; // so we can detect the next edge
837 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700838}
839
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700840AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700841{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700842 mPlaybackRateObserver.poll(mPlaybackRate);
843 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700844}
845
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800846// ---------------------------------------------------------------------------
847
848StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
849 size_t frameCount, size_t frameSize)
850 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800851 mObserver(&cblk->u.mStatic.mSingleStateQueue),
852 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800853 mFramesReadySafe(frameCount), mFramesReady(frameCount),
854 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800855{
Andy Hung9b461582014-12-01 17:56:29 -0800856 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800857}
858
859void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
860{
861 mFramesReadyIsCalledByMultipleThreads = true;
862}
863
864size_t StaticAudioTrackServerProxy::framesReady()
865{
Andy Hungcb2129b2014-11-11 12:17:22 -0800866 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800867 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800868 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800869 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800870 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800871}
872
Andy Hung9b461582014-12-01 17:56:29 -0800873status_t StaticAudioTrackServerProxy::updateStateWithLoop(
874 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800875{
Andy Hung9b461582014-12-01 17:56:29 -0800876 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800877 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800878 const size_t loopStart = update.mLoopStart;
879 const size_t loopEnd = update.mLoopEnd;
880 size_t position = localState->mPosition;
881 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800883 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800884 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
885 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800886 // If the current position is greater than the end of the loop
887 // we "wrap" to the loop start. This might cause an audible pop.
888 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800889 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800891 valid = true;
892 }
893 }
Andy Hung9b461582014-12-01 17:56:29 -0800894 if (!valid || position > mFrameCount) {
895 return NO_INIT;
896 }
897 localState->mPosition = position;
898 localState->mLoopCount = update.mLoopCount;
899 localState->mLoopEnd = loopEnd;
900 localState->mLoopStart = loopStart;
901 localState->mLoopSequence = update.mLoopSequence;
902 }
903 return OK;
904}
905
906status_t StaticAudioTrackServerProxy::updateStateWithPosition(
907 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
908{
909 if (localState->mPositionSequence != update.mPositionSequence) {
910 if (update.mPosition > mFrameCount) {
911 return NO_INIT;
912 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
913 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
914 }
915 localState->mPosition = update.mPosition;
916 localState->mPositionSequence = update.mPositionSequence;
917 }
918 return OK;
919}
920
921ssize_t StaticAudioTrackServerProxy::pollPosition()
922{
923 StaticAudioTrackState state;
924 if (mObserver.poll(state)) {
925 StaticAudioTrackState trystate = mState;
926 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700927 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800928
929 if (diffSeq < 0) {
930 result = updateStateWithLoop(&trystate, state) == OK &&
931 updateStateWithPosition(&trystate, state) == OK;
932 } else {
933 result = updateStateWithPosition(&trystate, state) == OK &&
934 updateStateWithLoop(&trystate, state) == OK;
935 }
936 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800937 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800938 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800939 ALOGE("%s client pushed an invalid state, shutting down", __func__);
940 mIsShutdown = true;
941 return (ssize_t) NO_INIT;
942 }
Andy Hung9b461582014-12-01 17:56:29 -0800943 mState = trystate;
944 if (mState.mLoopCount == -1) {
945 mFramesReady = INT64_MAX;
946 } else if (mState.mLoopCount == 0) {
947 mFramesReady = mFrameCount - mState.mPosition;
948 } else if (mState.mLoopCount > 0) {
949 // TODO: Later consider fixing overflow, but does not seem needed now
950 // as will not overflow if loopStart and loopEnd are Java "ints".
951 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
952 + mFrameCount - mState.mPosition;
953 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800954 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800955 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800956 StaticAudioTrackPosLoop posLoop;
957
958 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
959 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
960 mPosLoopMutator.push(posLoop);
961 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800962 }
Andy Hung9b461582014-12-01 17:56:29 -0800963 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800964}
965
Andy Hung954ca452015-09-09 14:39:02 -0700966status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800967{
968 if (mIsShutdown) {
969 buffer->mFrameCount = 0;
970 buffer->mRaw = NULL;
971 buffer->mNonContig = 0;
972 mUnreleased = 0;
973 return NO_INIT;
974 }
975 ssize_t positionOrStatus = pollPosition();
976 if (positionOrStatus < 0) {
977 buffer->mFrameCount = 0;
978 buffer->mRaw = NULL;
979 buffer->mNonContig = 0;
980 mUnreleased = 0;
981 return (status_t) positionOrStatus;
982 }
983 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800984 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800985 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800986 if (position < end) {
987 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800988 size_t wanted = buffer->mFrameCount;
989 if (avail < wanted) {
990 buffer->mFrameCount = avail;
991 } else {
992 avail = wanted;
993 }
994 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
995 } else {
996 avail = 0;
997 buffer->mFrameCount = 0;
998 buffer->mRaw = NULL;
999 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001000 // As mFramesReady is the total remaining frames in the static audio track,
1001 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -08001002 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001003 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001004 if (!ackFlush) {
1005 mUnreleased = avail;
1006 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001007 return NO_ERROR;
1008}
1009
1010void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1011{
1012 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -08001013 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -07001014 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001015 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001016 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001017 buffer->mRaw = NULL;
1018 buffer->mNonContig = 0;
1019 return;
1020 }
1021 mUnreleased -= stepCount;
1022 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001023 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001024 size_t newPosition = position + stepCount;
1025 int32_t setFlags = 0;
1026 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001027 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1028 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001029 newPosition = mFrameCount;
1030 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001031 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001032 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001033 setFlags = CBLK_LOOP_CYCLE;
1034 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001035 setFlags = CBLK_LOOP_FINAL;
1036 }
1037 }
1038 if (newPosition == mFrameCount) {
1039 setFlags |= CBLK_BUFFER_END;
1040 }
Andy Hung9b461582014-12-01 17:56:29 -08001041 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001042 if (mFramesReady != INT64_MAX) {
1043 mFramesReady -= stepCount;
1044 }
1045 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001046
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001047 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001048 mReleased += stepCount;
1049
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001050 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001051 StaticAudioTrackPosLoop posLoop;
1052 posLoop.mBufferPosition = mState.mPosition;
1053 posLoop.mLoopCount = mState.mLoopCount;
1054 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001055 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001056 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001057 // this would be a good place to wake a futex
1058 }
1059
1060 buffer->mFrameCount = 0;
1061 buffer->mRaw = NULL;
1062 buffer->mNonContig = 0;
1063}
1064
Phil Burk2812d9e2016-01-04 10:34:30 -08001065void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001066{
1067 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1068 // we don't have a location to count underrun frames. The underrun frame counter
1069 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1070 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1071
1072 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001073 if (frameCount > 0) {
1074 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1075 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001076}
1077
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001078// ---------------------------------------------------------------------------
1079
Glenn Kastena8190fc2012-12-03 17:06:56 -08001080} // namespace android