blob: e5d6fc30ad5588474fa080aaa2799cb9b1607899 [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 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800154 if (flags & CBLK_DISABLED) {
155 ALOGV("Track disabled");
156 status = NOT_ENOUGH_DATA;
157 goto end;
158 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800159 // check for obtainBuffer interrupted by client
160 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
161 ALOGV("obtainBuffer() interrupted by client");
162 status = -EINTR;
163 goto end;
164 }
165 ignoreInitialPendingInterrupt = false;
166 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
167 int32_t front;
168 int32_t rear;
169 if (mIsOut) {
170 // The barrier following the read of mFront is probably redundant.
171 // We're about to perform a conditional branch based on 'filled',
172 // which will force the processor to observe the read of mFront
173 // prior to allowing data writes starting at mRaw.
174 // However, the processor may support speculative execution,
175 // and be unable to undo speculative writes into shared memory.
176 // The barrier will prevent such speculative execution.
177 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
178 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800179 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800180 // On the other hand, this barrier is required.
181 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
182 front = cblk->u.mStreaming.mFront;
183 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800184 // write to rear, read from front
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800185 ssize_t filled = rear - front;
186 // pipe should not be overfull
187 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700188 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700189 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700190 "shutting down", filled, mFrameCount);
191 mIsShutdown = true;
192 status = NO_INIT;
193 goto end;
194 }
195 // for input, sync up on overrun
196 filled = 0;
197 cblk->u.mStreaming.mFront = rear;
198 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800199 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800200 // Don't allow filling pipe beyond the user settable size.
201 // The calculation for avail can go negative if the buffer size
202 // is suddenly dropped below the amount already in the buffer.
203 // So use a signed calculation to prevent a numeric overflow abort.
Phil Burke8972b02016-03-04 11:29:57 -0800204 ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800205 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
206 if (avail < 0) {
207 avail = 0;
208 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800209 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800210 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800211 if (mIsOut) {
212 rear &= mFrameCountP2 - 1;
213 part1 = mFrameCountP2 - rear;
214 } else {
215 front &= mFrameCountP2 - 1;
216 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800217 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800218 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800219 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800220 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800221 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800222 part1 = buffer->mFrameCount;
223 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800224 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800225 buffer->mRaw = part1 > 0 ?
226 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
227 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700228 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800229 status = NO_ERROR;
230 break;
231 }
232 struct timespec remaining;
233 const struct timespec *ts;
234 switch (timeout) {
235 case TIMEOUT_ZERO:
236 status = WOULD_BLOCK;
237 goto end;
238 case TIMEOUT_INFINITE:
239 ts = NULL;
240 break;
241 case TIMEOUT_FINITE:
242 timeout = TIMEOUT_CONTINUE;
243 if (MAX_SEC == 0) {
244 ts = requested;
245 break;
246 }
247 // fall through
248 case TIMEOUT_CONTINUE:
249 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
250 if (!measure || requested->tv_sec < total.tv_sec ||
251 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
252 status = TIMED_OUT;
253 goto end;
254 }
255 remaining.tv_sec = requested->tv_sec - total.tv_sec;
256 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
257 remaining.tv_nsec += 1000000000;
258 remaining.tv_sec++;
259 }
260 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
261 remaining.tv_sec = MAX_SEC;
262 remaining.tv_nsec = 0;
263 }
264 ts = &remaining;
265 break;
266 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800267 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800268 ts = NULL;
269 break;
270 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700271 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
272 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800273 if (measure && !beforeIsValid) {
274 clock_gettime(CLOCK_MONOTONIC, &before);
275 beforeIsValid = true;
276 }
Elliott Hughesee499292014-05-21 17:55:51 -0700277 errno = 0;
278 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700279 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800280 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800281 // update total elapsed time spent waiting
282 if (measure) {
283 struct timespec after;
284 clock_gettime(CLOCK_MONOTONIC, &after);
285 total.tv_sec += after.tv_sec - before.tv_sec;
286 long deltaNs = after.tv_nsec - before.tv_nsec;
287 if (deltaNs < 0) {
288 deltaNs += 1000000000;
289 total.tv_sec--;
290 }
291 if ((total.tv_nsec += deltaNs) >= 1000000000) {
292 total.tv_nsec -= 1000000000;
293 total.tv_sec++;
294 }
295 before = after;
296 beforeIsValid = true;
297 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800298 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700299 case 0: // normal wakeup by server, or by binderDied()
300 case EWOULDBLOCK: // benign race condition with server
301 case EINTR: // wait was interrupted by signal or other spurious wakeup
302 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700303 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800304 break;
305 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800306 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700307 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800308 goto end;
309 }
310 }
311 }
312
313end:
314 if (status != NO_ERROR) {
315 buffer->mFrameCount = 0;
316 buffer->mRaw = NULL;
317 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700318 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800319 }
320 if (elapsed != NULL) {
321 *elapsed = total;
322 }
323 if (requested == NULL) {
324 requested = &kNonBlocking;
325 }
326 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100327 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
328 requested->tv_sec, requested->tv_nsec / 1000000,
329 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800330 }
331 return status;
332}
333
334void ClientProxy::releaseBuffer(Buffer* buffer)
335{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700336 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800337 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700338 if (stepCount == 0 || mIsShutdown) {
339 // prevent accidental re-use of buffer
340 buffer->mFrameCount = 0;
341 buffer->mRaw = NULL;
342 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800343 return;
344 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700345 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
346 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800347 audio_track_cblk_t* cblk = mCblk;
348 // Both of these barriers are required
349 if (mIsOut) {
350 int32_t rear = cblk->u.mStreaming.mRear;
351 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
352 } else {
353 int32_t front = cblk->u.mStreaming.mFront;
354 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
355 }
356}
357
358void ClientProxy::binderDied()
359{
360 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700361 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900362 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800363 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700364 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
365 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800366 }
367}
368
369void ClientProxy::interrupt()
370{
371 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700372 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900373 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700374 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
375 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800376 }
377}
378
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700379__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800380size_t ClientProxy::getMisalignment()
381{
382 audio_track_cblk_t* cblk = mCblk;
383 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
384 (mFrameCountP2 - 1);
385}
386
387// ---------------------------------------------------------------------------
388
389void AudioTrackClientProxy::flush()
390{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700391 // This works for mFrameCountP2 <= 2^30
392 size_t increment = mFrameCountP2 << 1;
393 size_t mask = increment - 1;
394 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700395 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
396 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
397 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700398 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
399 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
400 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800401}
402
Eric Laurentbfb1b832013-01-07 09:53:42 -0800403bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700404 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800405}
406
407bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700408 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800409}
410
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100411status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
412{
413 struct timespec total; // total elapsed time spent waiting
414 total.tv_sec = 0;
415 total.tv_nsec = 0;
416 audio_track_cblk_t* cblk = mCblk;
417 status_t status;
418 enum {
419 TIMEOUT_ZERO, // requested == NULL || *requested == 0
420 TIMEOUT_INFINITE, // *requested == infinity
421 TIMEOUT_FINITE, // 0 < *requested < infinity
422 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
423 } timeout;
424 if (requested == NULL) {
425 timeout = TIMEOUT_ZERO;
426 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
427 timeout = TIMEOUT_ZERO;
428 } else if (requested->tv_sec == INT_MAX) {
429 timeout = TIMEOUT_INFINITE;
430 } else {
431 timeout = TIMEOUT_FINITE;
432 }
433 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700434 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100435 // check for track invalidation by server, or server death detection
436 if (flags & CBLK_INVALID) {
437 ALOGV("Track invalidated");
438 status = DEAD_OBJECT;
439 goto end;
440 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800441 // a track is not supposed to underrun at this stage but consider it done
442 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100443 ALOGV("stream end received");
444 status = NO_ERROR;
445 goto end;
446 }
447 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100448 if (flags & CBLK_INTERRUPT) {
449 ALOGV("waitStreamEndDone() interrupted by client");
450 status = -EINTR;
451 goto end;
452 }
453 struct timespec remaining;
454 const struct timespec *ts;
455 switch (timeout) {
456 case TIMEOUT_ZERO:
457 status = WOULD_BLOCK;
458 goto end;
459 case TIMEOUT_INFINITE:
460 ts = NULL;
461 break;
462 case TIMEOUT_FINITE:
463 timeout = TIMEOUT_CONTINUE;
464 if (MAX_SEC == 0) {
465 ts = requested;
466 break;
467 }
468 // fall through
469 case TIMEOUT_CONTINUE:
470 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
471 if (requested->tv_sec < total.tv_sec ||
472 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
473 status = TIMED_OUT;
474 goto end;
475 }
476 remaining.tv_sec = requested->tv_sec - total.tv_sec;
477 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
478 remaining.tv_nsec += 1000000000;
479 remaining.tv_sec++;
480 }
481 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
482 remaining.tv_sec = MAX_SEC;
483 remaining.tv_nsec = 0;
484 }
485 ts = &remaining;
486 break;
487 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800488 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100489 ts = NULL;
490 break;
491 }
492 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
493 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700494 errno = 0;
495 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100496 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700497 switch (errno) {
498 case 0: // normal wakeup by server, or by binderDied()
499 case EWOULDBLOCK: // benign race condition with server
500 case EINTR: // wait was interrupted by signal or other spurious wakeup
501 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100502 break;
503 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700504 status = errno;
505 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100506 goto end;
507 }
508 }
509 }
510
511end:
512 if (requested == NULL) {
513 requested = &kNonBlocking;
514 }
515 return status;
516}
517
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800518// ---------------------------------------------------------------------------
519
520StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
521 size_t frameCount, size_t frameSize)
522 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800523 mMutator(&cblk->u.mStatic.mSingleStateQueue),
524 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800525{
Andy Hung9b461582014-12-01 17:56:29 -0800526 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800527 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800528}
529
530void StaticAudioTrackClientProxy::flush()
531{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800532 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800533}
534
535void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
536{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800537 // This can only happen on a 64-bit client
538 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
539 // FIXME Should return an error status
540 return;
541 }
Andy Hung9b461582014-12-01 17:56:29 -0800542 mState.mLoopStart = (uint32_t) loopStart;
543 mState.mLoopEnd = (uint32_t) loopEnd;
544 mState.mLoopCount = loopCount;
545 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
546 // set patch-up variables until the mState is acknowledged by the ServerProxy.
547 // observed buffer position and loop count will freeze until then to give the
548 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800549 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800550 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800551 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
552 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800553 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800554 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800555 (void) mMutator.push(mState);
556}
557
558void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
559{
560 // This can only happen on a 64-bit client
561 if (position > UINT32_MAX) {
562 // FIXME Should return an error status
563 return;
564 }
565 mState.mPosition = (uint32_t) position;
566 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800567 // set patch-up variables until the mState is acknowledged by the ServerProxy.
568 // observed buffer position and loop count will freeze until then to give the
569 // illusion of a synchronous change.
570 if (mState.mLoopCount > 0) { // only check if loop count is changing
571 getBufferPositionAndLoopCount(NULL, NULL); // get last position
572 }
573 mPosLoop.mBufferPosition = position;
574 if (position >= mState.mLoopEnd) {
575 // no ongoing loop is possible if position is greater than loopEnd.
576 mPosLoop.mLoopCount = 0;
577 }
Andy Hung9b461582014-12-01 17:56:29 -0800578 (void) mMutator.push(mState);
579}
580
581void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
582 size_t loopEnd, int loopCount)
583{
584 setLoop(loopStart, loopEnd, loopCount);
585 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800586}
587
588size_t StaticAudioTrackClientProxy::getBufferPosition()
589{
Andy Hung4ede21d2014-12-12 15:37:34 -0800590 getBufferPositionAndLoopCount(NULL, NULL);
591 return mPosLoop.mBufferPosition;
592}
593
594void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
595 size_t *position, int *loopCount)
596{
597 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
598 if (mPosLoopObserver.poll(mPosLoop)) {
599 ; // a valid mPosLoop should be available if ackDone is true.
600 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800601 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800602 if (position != NULL) {
603 *position = mPosLoop.mBufferPosition;
604 }
605 if (loopCount != NULL) {
606 *loopCount = mPosLoop.mLoopCount;
607 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800608}
609
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800610// ---------------------------------------------------------------------------
611
612ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
613 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700614 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hung3f0c9022016-01-15 17:49:46 -0800615 mAvailToClient(0), mFlush(0), mReleased(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800616 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800617{
Phil Burke8972b02016-03-04 11:29:57 -0800618 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800619}
620
Glenn Kasten2e422c42013-10-18 13:00:29 -0700621status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800622{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700623 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800624 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700625 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800626 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700627 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800628 audio_track_cblk_t* cblk = mCblk;
629 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
630 // or use previous cached value from framesReady(), with added barrier if it omits.
631 int32_t front;
632 int32_t rear;
633 // See notes on barriers at ClientProxy::obtainBuffer()
634 if (mIsOut) {
635 int32_t flush = cblk->u.mStreaming.mFlush;
636 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100637 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800638 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700639 // effectively obtain then release whatever is in the buffer
Andy Hunga2d75cd2015-07-15 17:04:20 -0700640 const size_t overflowBit = mFrameCountP2 << 1;
641 const size_t mask = overflowBit - 1;
Glenn Kasten20f51b12014-10-30 10:43:19 -0700642 int32_t newFront = (front & ~mask) | (flush & mask);
643 ssize_t filled = rear - newFront;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700644 if (filled >= (ssize_t)overflowBit) {
645 // front and rear offsets span the overflow bit of the p2 mask
646 // so rebasing newFront on the front offset is off by the overflow bit.
647 // adjust newFront to match rear offset.
Glenn Kastendbd0f3c2015-07-17 11:04:04 -0700648 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hunga2d75cd2015-07-15 17:04:20 -0700649 newFront += overflowBit;
650 filled -= overflowBit;
651 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700652 // Rather than shutting down on a corrupt flush, just treat it as a full flush
653 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800654 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
Lajos Molnarf1063e22015-04-17 15:19:42 -0700655 "filled %zd=%#x",
656 mFlush, flush, front, rear,
657 (unsigned)mask, newFront, filled, (unsigned)filled);
Glenn Kasten20f51b12014-10-30 10:43:19 -0700658 newFront = rear;
659 }
660 mFlush = flush;
661 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
662 // There is no danger from a false positive, so err on the side of caution
663 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100664 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
665 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700666 (void) syscall(__NR_futex, &cblk->mFutex,
667 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100668 }
669 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700670 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800671 }
672 } else {
673 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
674 rear = cblk->u.mStreaming.mRear;
675 }
676 ssize_t filled = rear - front;
677 // pipe should not already be overfull
678 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700679 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800680 mIsShutdown = true;
681 }
682 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700683 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800684 }
685 // don't allow filling pipe beyond the nominal size
686 size_t availToServer;
687 if (mIsOut) {
688 availToServer = filled;
689 mAvailToClient = mFrameCount - filled;
690 } else {
691 availToServer = mFrameCount - filled;
692 mAvailToClient = filled;
693 }
694 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
695 size_t part1;
696 if (mIsOut) {
697 front &= mFrameCountP2 - 1;
698 part1 = mFrameCountP2 - front;
699 } else {
700 rear &= mFrameCountP2 - 1;
701 part1 = mFrameCountP2 - rear;
702 }
703 if (part1 > availToServer) {
704 part1 = availToServer;
705 }
706 size_t ask = buffer->mFrameCount;
707 if (part1 > ask) {
708 part1 = ask;
709 }
710 // is assignment redundant in some cases?
711 buffer->mFrameCount = part1;
712 buffer->mRaw = part1 > 0 ?
713 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
714 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700715 // After flush(), allow releaseBuffer() on a previously obtained buffer;
716 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
717 if (!ackFlush) {
718 mUnreleased = part1;
719 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800720 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700721 }
722no_init:
723 buffer->mFrameCount = 0;
724 buffer->mRaw = NULL;
725 buffer->mNonContig = 0;
726 mUnreleased = 0;
727 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800728}
729
730void ServerProxy::releaseBuffer(Buffer* buffer)
731{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700732 LOG_ALWAYS_FATAL_IF(buffer == NULL);
733 size_t stepCount = buffer->mFrameCount;
734 if (stepCount == 0 || mIsShutdown) {
735 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800736 buffer->mFrameCount = 0;
737 buffer->mRaw = NULL;
738 buffer->mNonContig = 0;
739 return;
740 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700741 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800742 mUnreleased -= stepCount;
743 audio_track_cblk_t* cblk = mCblk;
744 if (mIsOut) {
745 int32_t front = cblk->u.mStreaming.mFront;
746 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
747 } else {
748 int32_t rear = cblk->u.mStreaming.mRear;
749 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
750 }
751
Glenn Kasten844f88c2014-05-09 13:38:09 -0700752 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800753 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800754
755 size_t half = mFrameCount / 2;
756 if (half == 0) {
757 half = 1;
758 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800759 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800760 if (minimum == 0) {
761 minimum = mIsOut ? half : 1;
762 } else if (minimum > half) {
763 minimum = half;
764 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700765 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700766 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700767 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700768 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
769 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700770 (void) syscall(__NR_futex, &cblk->mFutex,
771 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800772 }
773 }
774
775 buffer->mFrameCount = 0;
776 buffer->mRaw = NULL;
777 buffer->mNonContig = 0;
778}
779
780// ---------------------------------------------------------------------------
781
782size_t AudioTrackServerProxy::framesReady()
783{
784 LOG_ALWAYS_FATAL_IF(!mIsOut);
785
786 if (mIsShutdown) {
787 return 0;
788 }
789 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100790
791 int32_t flush = cblk->u.mStreaming.mFlush;
792 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700793 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100794 return mFrameCount;
795 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800796 // the acquire might not be necessary since not doing a subsequent read
797 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
798 ssize_t filled = rear - cblk->u.mStreaming.mFront;
799 // pipe should not already be overfull
800 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700801 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800802 mIsShutdown = true;
803 return 0;
804 }
805 // cache this value for later use by obtainBuffer(), with added barrier
806 // and racy if called by normal mixer thread
807 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
808 return filled;
809}
810
Eric Laurentbfb1b832013-01-07 09:53:42 -0800811bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700812 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800813 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700814 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800815 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700816 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700817 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800818 }
819 return old;
820}
821
Glenn Kasten82aaf942013-07-17 16:05:07 -0700822void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
823{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700824 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800825 if (frameCount > 0) {
826 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700827
Phil Burk2812d9e2016-01-04 10:34:30 -0800828 if (!mUnderrunning) { // start of underrun?
829 mUnderrunCount++;
830 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
831 mUnderrunning = true;
832 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
833 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
834 }
835
836 // FIXME also wake futex so that underrun is noticed more quickly
837 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
838 } else {
839 ALOGV_IF(mUnderrunning,
840 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
841 frameCount, cblk->u.mStreaming.mUnderrunFrames);
842 mUnderrunning = false; // so we can detect the next edge
843 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700844}
845
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700846AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700847{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700848 mPlaybackRateObserver.poll(mPlaybackRate);
849 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700850}
851
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800852// ---------------------------------------------------------------------------
853
854StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
855 size_t frameCount, size_t frameSize)
856 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800857 mObserver(&cblk->u.mStatic.mSingleStateQueue),
858 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800859 mFramesReadySafe(frameCount), mFramesReady(frameCount),
860 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800861{
Andy Hung9b461582014-12-01 17:56:29 -0800862 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800863}
864
865void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
866{
867 mFramesReadyIsCalledByMultipleThreads = true;
868}
869
870size_t StaticAudioTrackServerProxy::framesReady()
871{
Andy Hungcb2129b2014-11-11 12:17:22 -0800872 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800873 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800874 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800875 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800876 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800877}
878
Andy Hung9b461582014-12-01 17:56:29 -0800879status_t StaticAudioTrackServerProxy::updateStateWithLoop(
880 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800881{
Andy Hung9b461582014-12-01 17:56:29 -0800882 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800883 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800884 const size_t loopStart = update.mLoopStart;
885 const size_t loopEnd = update.mLoopEnd;
886 size_t position = localState->mPosition;
887 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800888 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800889 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800890 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
891 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800892 // If the current position is greater than the end of the loop
893 // we "wrap" to the loop start. This might cause an audible pop.
894 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800895 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800896 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800897 valid = true;
898 }
899 }
Andy Hung9b461582014-12-01 17:56:29 -0800900 if (!valid || position > mFrameCount) {
901 return NO_INIT;
902 }
903 localState->mPosition = position;
904 localState->mLoopCount = update.mLoopCount;
905 localState->mLoopEnd = loopEnd;
906 localState->mLoopStart = loopStart;
907 localState->mLoopSequence = update.mLoopSequence;
908 }
909 return OK;
910}
911
912status_t StaticAudioTrackServerProxy::updateStateWithPosition(
913 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
914{
915 if (localState->mPositionSequence != update.mPositionSequence) {
916 if (update.mPosition > mFrameCount) {
917 return NO_INIT;
918 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
919 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
920 }
921 localState->mPosition = update.mPosition;
922 localState->mPositionSequence = update.mPositionSequence;
923 }
924 return OK;
925}
926
927ssize_t StaticAudioTrackServerProxy::pollPosition()
928{
929 StaticAudioTrackState state;
930 if (mObserver.poll(state)) {
931 StaticAudioTrackState trystate = mState;
932 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700933 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800934
935 if (diffSeq < 0) {
936 result = updateStateWithLoop(&trystate, state) == OK &&
937 updateStateWithPosition(&trystate, state) == OK;
938 } else {
939 result = updateStateWithPosition(&trystate, state) == OK &&
940 updateStateWithLoop(&trystate, state) == OK;
941 }
942 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800943 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800944 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800945 ALOGE("%s client pushed an invalid state, shutting down", __func__);
946 mIsShutdown = true;
947 return (ssize_t) NO_INIT;
948 }
Andy Hung9b461582014-12-01 17:56:29 -0800949 mState = trystate;
950 if (mState.mLoopCount == -1) {
951 mFramesReady = INT64_MAX;
952 } else if (mState.mLoopCount == 0) {
953 mFramesReady = mFrameCount - mState.mPosition;
954 } else if (mState.mLoopCount > 0) {
955 // TODO: Later consider fixing overflow, but does not seem needed now
956 // as will not overflow if loopStart and loopEnd are Java "ints".
957 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
958 + mFrameCount - mState.mPosition;
959 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800960 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800961 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800962 StaticAudioTrackPosLoop posLoop;
963
964 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
965 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
966 mPosLoopMutator.push(posLoop);
967 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800968 }
Andy Hung9b461582014-12-01 17:56:29 -0800969 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800970}
971
Andy Hung954ca452015-09-09 14:39:02 -0700972status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800973{
974 if (mIsShutdown) {
975 buffer->mFrameCount = 0;
976 buffer->mRaw = NULL;
977 buffer->mNonContig = 0;
978 mUnreleased = 0;
979 return NO_INIT;
980 }
981 ssize_t positionOrStatus = pollPosition();
982 if (positionOrStatus < 0) {
983 buffer->mFrameCount = 0;
984 buffer->mRaw = NULL;
985 buffer->mNonContig = 0;
986 mUnreleased = 0;
987 return (status_t) positionOrStatus;
988 }
989 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800990 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800991 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800992 if (position < end) {
993 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800994 size_t wanted = buffer->mFrameCount;
995 if (avail < wanted) {
996 buffer->mFrameCount = avail;
997 } else {
998 avail = wanted;
999 }
1000 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1001 } else {
1002 avail = 0;
1003 buffer->mFrameCount = 0;
1004 buffer->mRaw = NULL;
1005 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001006 // As mFramesReady is the total remaining frames in the static audio track,
1007 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -08001008 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001009 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001010 if (!ackFlush) {
1011 mUnreleased = avail;
1012 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001013 return NO_ERROR;
1014}
1015
1016void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1017{
1018 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -08001019 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -07001020 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001021 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001022 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001023 buffer->mRaw = NULL;
1024 buffer->mNonContig = 0;
1025 return;
1026 }
1027 mUnreleased -= stepCount;
1028 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001029 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001030 size_t newPosition = position + stepCount;
1031 int32_t setFlags = 0;
1032 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001033 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1034 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001035 newPosition = mFrameCount;
1036 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001037 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001038 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001039 setFlags = CBLK_LOOP_CYCLE;
1040 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001041 setFlags = CBLK_LOOP_FINAL;
1042 }
1043 }
1044 if (newPosition == mFrameCount) {
1045 setFlags |= CBLK_BUFFER_END;
1046 }
Andy Hung9b461582014-12-01 17:56:29 -08001047 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001048 if (mFramesReady != INT64_MAX) {
1049 mFramesReady -= stepCount;
1050 }
1051 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001052
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001053 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001054 mReleased += stepCount;
1055
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001056 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001057 StaticAudioTrackPosLoop posLoop;
1058 posLoop.mBufferPosition = mState.mPosition;
1059 posLoop.mLoopCount = mState.mLoopCount;
1060 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001061 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001062 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001063 // this would be a good place to wake a futex
1064 }
1065
1066 buffer->mFrameCount = 0;
1067 buffer->mRaw = NULL;
1068 buffer->mNonContig = 0;
1069}
1070
Phil Burk2812d9e2016-01-04 10:34:30 -08001071void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001072{
1073 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1074 // we don't have a location to count underrun frames. The underrun frame counter
1075 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1076 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1077
1078 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001079 if (frameCount > 0) {
1080 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1081 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001082}
1083
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001084// ---------------------------------------------------------------------------
1085
Glenn Kastena8190fc2012-12-03 17:06:56 -08001086} // namespace android