blob: 285b3f65fe56442b24ede878e03eb45dee3888aa [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
ilewis926b82f2016-03-29 14:50:36 -0700109__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800110status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
111 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800112{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700113 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800114 struct timespec total; // total elapsed time spent waiting
115 total.tv_sec = 0;
116 total.tv_nsec = 0;
117 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -0800118
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800119 status_t status;
120 enum {
121 TIMEOUT_ZERO, // requested == NULL || *requested == 0
122 TIMEOUT_INFINITE, // *requested == infinity
123 TIMEOUT_FINITE, // 0 < *requested < infinity
124 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
125 } timeout;
126 if (requested == NULL) {
127 timeout = TIMEOUT_ZERO;
128 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
129 timeout = TIMEOUT_ZERO;
130 } else if (requested->tv_sec == INT_MAX) {
131 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800132 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800133 timeout = TIMEOUT_FINITE;
134 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
135 measure = true;
136 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800137 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800138 struct timespec before;
139 bool beforeIsValid = false;
140 audio_track_cblk_t* cblk = mCblk;
141 bool ignoreInitialPendingInterrupt = true;
142 // check for shared memory corruption
143 if (mIsShutdown) {
144 status = NO_INIT;
145 goto end;
146 }
147 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700148 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800149 // check for track invalidation by server, or server death detection
150 if (flags & CBLK_INVALID) {
151 ALOGV("Track invalidated");
152 status = DEAD_OBJECT;
153 goto end;
154 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800155 if (flags & CBLK_DISABLED) {
156 ALOGV("Track disabled");
157 status = NOT_ENOUGH_DATA;
158 goto end;
159 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800160 // check for obtainBuffer interrupted by client
161 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
162 ALOGV("obtainBuffer() interrupted by client");
163 status = -EINTR;
164 goto end;
165 }
166 ignoreInitialPendingInterrupt = false;
167 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
168 int32_t front;
169 int32_t rear;
170 if (mIsOut) {
171 // The barrier following the read of mFront is probably redundant.
172 // We're about to perform a conditional branch based on 'filled',
173 // which will force the processor to observe the read of mFront
174 // prior to allowing data writes starting at mRaw.
175 // However, the processor may support speculative execution,
176 // and be unable to undo speculative writes into shared memory.
177 // The barrier will prevent such speculative execution.
178 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
179 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800180 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800181 // On the other hand, this barrier is required.
182 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
183 front = cblk->u.mStreaming.mFront;
184 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800185 // write to rear, read from front
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800186 ssize_t filled = rear - front;
187 // pipe should not be overfull
188 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700189 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700190 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700191 "shutting down", filled, mFrameCount);
192 mIsShutdown = true;
193 status = NO_INIT;
194 goto end;
195 }
196 // for input, sync up on overrun
197 filled = 0;
198 cblk->u.mStreaming.mFront = rear;
199 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800200 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800201 // Don't allow filling pipe beyond the user settable size.
202 // The calculation for avail can go negative if the buffer size
203 // is suddenly dropped below the amount already in the buffer.
204 // So use a signed calculation to prevent a numeric overflow abort.
Phil Burke8972b02016-03-04 11:29:57 -0800205 ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800206 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
207 if (avail < 0) {
208 avail = 0;
209 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800210 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800211 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800212 if (mIsOut) {
213 rear &= mFrameCountP2 - 1;
214 part1 = mFrameCountP2 - rear;
215 } else {
216 front &= mFrameCountP2 - 1;
217 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800218 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800219 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800220 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800221 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800222 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800223 part1 = buffer->mFrameCount;
224 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800225 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800226 buffer->mRaw = part1 > 0 ?
227 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
228 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700229 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800230 status = NO_ERROR;
231 break;
232 }
233 struct timespec remaining;
234 const struct timespec *ts;
235 switch (timeout) {
236 case TIMEOUT_ZERO:
237 status = WOULD_BLOCK;
238 goto end;
239 case TIMEOUT_INFINITE:
240 ts = NULL;
241 break;
242 case TIMEOUT_FINITE:
243 timeout = TIMEOUT_CONTINUE;
244 if (MAX_SEC == 0) {
245 ts = requested;
246 break;
247 }
248 // fall through
249 case TIMEOUT_CONTINUE:
250 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
251 if (!measure || requested->tv_sec < total.tv_sec ||
252 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
253 status = TIMED_OUT;
254 goto end;
255 }
256 remaining.tv_sec = requested->tv_sec - total.tv_sec;
257 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
258 remaining.tv_nsec += 1000000000;
259 remaining.tv_sec++;
260 }
261 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
262 remaining.tv_sec = MAX_SEC;
263 remaining.tv_nsec = 0;
264 }
265 ts = &remaining;
266 break;
267 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800268 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800269 ts = NULL;
270 break;
271 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700272 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
273 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800274 if (measure && !beforeIsValid) {
275 clock_gettime(CLOCK_MONOTONIC, &before);
276 beforeIsValid = true;
277 }
Elliott Hughesee499292014-05-21 17:55:51 -0700278 errno = 0;
279 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700280 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800281 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800282 // update total elapsed time spent waiting
283 if (measure) {
284 struct timespec after;
285 clock_gettime(CLOCK_MONOTONIC, &after);
286 total.tv_sec += after.tv_sec - before.tv_sec;
287 long deltaNs = after.tv_nsec - before.tv_nsec;
288 if (deltaNs < 0) {
289 deltaNs += 1000000000;
290 total.tv_sec--;
291 }
292 if ((total.tv_nsec += deltaNs) >= 1000000000) {
293 total.tv_nsec -= 1000000000;
294 total.tv_sec++;
295 }
296 before = after;
297 beforeIsValid = true;
298 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800299 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700300 case 0: // normal wakeup by server, or by binderDied()
301 case EWOULDBLOCK: // benign race condition with server
302 case EINTR: // wait was interrupted by signal or other spurious wakeup
303 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700304 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800305 break;
306 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800307 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700308 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800309 goto end;
310 }
311 }
312 }
313
314end:
315 if (status != NO_ERROR) {
316 buffer->mFrameCount = 0;
317 buffer->mRaw = NULL;
318 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700319 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800320 }
321 if (elapsed != NULL) {
322 *elapsed = total;
323 }
324 if (requested == NULL) {
325 requested = &kNonBlocking;
326 }
327 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100328 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
329 requested->tv_sec, requested->tv_nsec / 1000000,
330 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800331 }
332 return status;
333}
334
ilewis926b82f2016-03-29 14:50:36 -0700335__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800336void ClientProxy::releaseBuffer(Buffer* buffer)
337{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700338 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800339 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700340 if (stepCount == 0 || mIsShutdown) {
341 // prevent accidental re-use of buffer
342 buffer->mFrameCount = 0;
343 buffer->mRaw = NULL;
344 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800345 return;
346 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700347 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
348 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800349 audio_track_cblk_t* cblk = mCblk;
350 // Both of these barriers are required
351 if (mIsOut) {
352 int32_t rear = cblk->u.mStreaming.mRear;
353 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
354 } else {
355 int32_t front = cblk->u.mStreaming.mFront;
356 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
357 }
358}
359
360void ClientProxy::binderDied()
361{
362 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700363 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900364 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800365 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700366 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
367 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800368 }
369}
370
371void ClientProxy::interrupt()
372{
373 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700374 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900375 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700376 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
377 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800378 }
379}
380
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700381__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800382size_t ClientProxy::getMisalignment()
383{
384 audio_track_cblk_t* cblk = mCblk;
385 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
386 (mFrameCountP2 - 1);
387}
388
389// ---------------------------------------------------------------------------
390
391void AudioTrackClientProxy::flush()
392{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700393 // This works for mFrameCountP2 <= 2^30
394 size_t increment = mFrameCountP2 << 1;
395 size_t mask = increment - 1;
396 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700397 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
398 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
399 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700400 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
401 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
402 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800403}
404
Eric Laurentbfb1b832013-01-07 09:53:42 -0800405bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700406 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800407}
408
409bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700410 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800411}
412
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100413status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
414{
415 struct timespec total; // total elapsed time spent waiting
416 total.tv_sec = 0;
417 total.tv_nsec = 0;
418 audio_track_cblk_t* cblk = mCblk;
419 status_t status;
420 enum {
421 TIMEOUT_ZERO, // requested == NULL || *requested == 0
422 TIMEOUT_INFINITE, // *requested == infinity
423 TIMEOUT_FINITE, // 0 < *requested < infinity
424 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
425 } timeout;
426 if (requested == NULL) {
427 timeout = TIMEOUT_ZERO;
428 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
429 timeout = TIMEOUT_ZERO;
430 } else if (requested->tv_sec == INT_MAX) {
431 timeout = TIMEOUT_INFINITE;
432 } else {
433 timeout = TIMEOUT_FINITE;
434 }
435 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700436 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100437 // check for track invalidation by server, or server death detection
438 if (flags & CBLK_INVALID) {
439 ALOGV("Track invalidated");
440 status = DEAD_OBJECT;
441 goto end;
442 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800443 // a track is not supposed to underrun at this stage but consider it done
444 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100445 ALOGV("stream end received");
446 status = NO_ERROR;
447 goto end;
448 }
449 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100450 if (flags & CBLK_INTERRUPT) {
451 ALOGV("waitStreamEndDone() interrupted by client");
452 status = -EINTR;
453 goto end;
454 }
455 struct timespec remaining;
456 const struct timespec *ts;
457 switch (timeout) {
458 case TIMEOUT_ZERO:
459 status = WOULD_BLOCK;
460 goto end;
461 case TIMEOUT_INFINITE:
462 ts = NULL;
463 break;
464 case TIMEOUT_FINITE:
465 timeout = TIMEOUT_CONTINUE;
466 if (MAX_SEC == 0) {
467 ts = requested;
468 break;
469 }
470 // fall through
471 case TIMEOUT_CONTINUE:
472 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
473 if (requested->tv_sec < total.tv_sec ||
474 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
475 status = TIMED_OUT;
476 goto end;
477 }
478 remaining.tv_sec = requested->tv_sec - total.tv_sec;
479 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
480 remaining.tv_nsec += 1000000000;
481 remaining.tv_sec++;
482 }
483 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
484 remaining.tv_sec = MAX_SEC;
485 remaining.tv_nsec = 0;
486 }
487 ts = &remaining;
488 break;
489 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800490 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100491 ts = NULL;
492 break;
493 }
494 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
495 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700496 errno = 0;
497 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100498 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700499 switch (errno) {
500 case 0: // normal wakeup by server, or by binderDied()
501 case EWOULDBLOCK: // benign race condition with server
502 case EINTR: // wait was interrupted by signal or other spurious wakeup
503 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100504 break;
505 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700506 status = errno;
507 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100508 goto end;
509 }
510 }
511 }
512
513end:
514 if (requested == NULL) {
515 requested = &kNonBlocking;
516 }
517 return status;
518}
519
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520// ---------------------------------------------------------------------------
521
522StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
523 size_t frameCount, size_t frameSize)
524 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800525 mMutator(&cblk->u.mStatic.mSingleStateQueue),
526 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800527{
Andy Hung9b461582014-12-01 17:56:29 -0800528 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800529 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800530}
531
532void StaticAudioTrackClientProxy::flush()
533{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800534 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800535}
536
537void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
538{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800539 // This can only happen on a 64-bit client
540 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
541 // FIXME Should return an error status
542 return;
543 }
Andy Hung9b461582014-12-01 17:56:29 -0800544 mState.mLoopStart = (uint32_t) loopStart;
545 mState.mLoopEnd = (uint32_t) loopEnd;
546 mState.mLoopCount = loopCount;
547 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
548 // set patch-up variables until the mState is acknowledged by the ServerProxy.
549 // observed buffer position and loop count will freeze until then to give the
550 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800551 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800552 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800553 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
554 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800555 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800556 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800557 (void) mMutator.push(mState);
558}
559
560void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
561{
562 // This can only happen on a 64-bit client
563 if (position > UINT32_MAX) {
564 // FIXME Should return an error status
565 return;
566 }
567 mState.mPosition = (uint32_t) position;
568 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800569 // set patch-up variables until the mState is acknowledged by the ServerProxy.
570 // observed buffer position and loop count will freeze until then to give the
571 // illusion of a synchronous change.
572 if (mState.mLoopCount > 0) { // only check if loop count is changing
573 getBufferPositionAndLoopCount(NULL, NULL); // get last position
574 }
575 mPosLoop.mBufferPosition = position;
576 if (position >= mState.mLoopEnd) {
577 // no ongoing loop is possible if position is greater than loopEnd.
578 mPosLoop.mLoopCount = 0;
579 }
Andy Hung9b461582014-12-01 17:56:29 -0800580 (void) mMutator.push(mState);
581}
582
583void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
584 size_t loopEnd, int loopCount)
585{
586 setLoop(loopStart, loopEnd, loopCount);
587 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800588}
589
590size_t StaticAudioTrackClientProxy::getBufferPosition()
591{
Andy Hung4ede21d2014-12-12 15:37:34 -0800592 getBufferPositionAndLoopCount(NULL, NULL);
593 return mPosLoop.mBufferPosition;
594}
595
596void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
597 size_t *position, int *loopCount)
598{
599 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
600 if (mPosLoopObserver.poll(mPosLoop)) {
601 ; // a valid mPosLoop should be available if ackDone is true.
602 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800603 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800604 if (position != NULL) {
605 *position = mPosLoop.mBufferPosition;
606 }
607 if (loopCount != NULL) {
608 *loopCount = mPosLoop.mLoopCount;
609 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800610}
611
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800612// ---------------------------------------------------------------------------
613
614ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
615 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700616 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hung3f0c9022016-01-15 17:49:46 -0800617 mAvailToClient(0), mFlush(0), mReleased(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800618 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800619{
Phil Burke8972b02016-03-04 11:29:57 -0800620 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800621}
622
ilewis926b82f2016-03-29 14:50:36 -0700623__attribute__((no_sanitize("integer")))
Glenn Kasten2e422c42013-10-18 13:00:29 -0700624status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800625{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700626 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800627 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700628 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800629 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700630 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800631 audio_track_cblk_t* cblk = mCblk;
632 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
633 // or use previous cached value from framesReady(), with added barrier if it omits.
634 int32_t front;
635 int32_t rear;
636 // See notes on barriers at ClientProxy::obtainBuffer()
637 if (mIsOut) {
638 int32_t flush = cblk->u.mStreaming.mFlush;
639 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100640 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800641 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700642 // effectively obtain then release whatever is in the buffer
Andy Hunga2d75cd2015-07-15 17:04:20 -0700643 const size_t overflowBit = mFrameCountP2 << 1;
644 const size_t mask = overflowBit - 1;
Glenn Kasten20f51b12014-10-30 10:43:19 -0700645 int32_t newFront = (front & ~mask) | (flush & mask);
646 ssize_t filled = rear - newFront;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700647 if (filled >= (ssize_t)overflowBit) {
648 // front and rear offsets span the overflow bit of the p2 mask
649 // so rebasing newFront on the front offset is off by the overflow bit.
650 // adjust newFront to match rear offset.
Glenn Kastendbd0f3c2015-07-17 11:04:04 -0700651 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hunga2d75cd2015-07-15 17:04:20 -0700652 newFront += overflowBit;
653 filled -= overflowBit;
654 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700655 // Rather than shutting down on a corrupt flush, just treat it as a full flush
656 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800657 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
Lajos Molnarf1063e22015-04-17 15:19:42 -0700658 "filled %zd=%#x",
659 mFlush, flush, front, rear,
660 (unsigned)mask, newFront, filled, (unsigned)filled);
Glenn Kasten20f51b12014-10-30 10:43:19 -0700661 newFront = rear;
662 }
663 mFlush = flush;
664 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
665 // There is no danger from a false positive, so err on the side of caution
666 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100667 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
668 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700669 (void) syscall(__NR_futex, &cblk->mFutex,
670 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100671 }
672 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700673 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800674 }
675 } else {
676 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
677 rear = cblk->u.mStreaming.mRear;
678 }
679 ssize_t filled = rear - front;
680 // pipe should not already be overfull
681 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700682 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800683 mIsShutdown = true;
684 }
685 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700686 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800687 }
688 // don't allow filling pipe beyond the nominal size
689 size_t availToServer;
690 if (mIsOut) {
691 availToServer = filled;
692 mAvailToClient = mFrameCount - filled;
693 } else {
694 availToServer = mFrameCount - filled;
695 mAvailToClient = filled;
696 }
697 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
698 size_t part1;
699 if (mIsOut) {
700 front &= mFrameCountP2 - 1;
701 part1 = mFrameCountP2 - front;
702 } else {
703 rear &= mFrameCountP2 - 1;
704 part1 = mFrameCountP2 - rear;
705 }
706 if (part1 > availToServer) {
707 part1 = availToServer;
708 }
709 size_t ask = buffer->mFrameCount;
710 if (part1 > ask) {
711 part1 = ask;
712 }
713 // is assignment redundant in some cases?
714 buffer->mFrameCount = part1;
715 buffer->mRaw = part1 > 0 ?
716 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
717 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700718 // After flush(), allow releaseBuffer() on a previously obtained buffer;
719 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
720 if (!ackFlush) {
721 mUnreleased = part1;
722 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800723 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700724 }
725no_init:
726 buffer->mFrameCount = 0;
727 buffer->mRaw = NULL;
728 buffer->mNonContig = 0;
729 mUnreleased = 0;
730 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800731}
732
ilewis926b82f2016-03-29 14:50:36 -0700733__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800734void ServerProxy::releaseBuffer(Buffer* buffer)
735{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700736 LOG_ALWAYS_FATAL_IF(buffer == NULL);
737 size_t stepCount = buffer->mFrameCount;
738 if (stepCount == 0 || mIsShutdown) {
739 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800740 buffer->mFrameCount = 0;
741 buffer->mRaw = NULL;
742 buffer->mNonContig = 0;
743 return;
744 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700745 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800746 mUnreleased -= stepCount;
747 audio_track_cblk_t* cblk = mCblk;
748 if (mIsOut) {
749 int32_t front = cblk->u.mStreaming.mFront;
750 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
751 } else {
752 int32_t rear = cblk->u.mStreaming.mRear;
753 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
754 }
755
Glenn Kasten844f88c2014-05-09 13:38:09 -0700756 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800757 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800758
759 size_t half = mFrameCount / 2;
760 if (half == 0) {
761 half = 1;
762 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800763 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800764 if (minimum == 0) {
765 minimum = mIsOut ? half : 1;
766 } else if (minimum > half) {
767 minimum = half;
768 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700769 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700770 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700771 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700772 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
773 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700774 (void) syscall(__NR_futex, &cblk->mFutex,
775 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800776 }
777 }
778
779 buffer->mFrameCount = 0;
780 buffer->mRaw = NULL;
781 buffer->mNonContig = 0;
782}
783
784// ---------------------------------------------------------------------------
785
ilewis926b82f2016-03-29 14:50:36 -0700786__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800787size_t AudioTrackServerProxy::framesReady()
788{
789 LOG_ALWAYS_FATAL_IF(!mIsOut);
790
791 if (mIsShutdown) {
792 return 0;
793 }
794 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100795
796 int32_t flush = cblk->u.mStreaming.mFlush;
797 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700798 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100799 return mFrameCount;
800 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800801 // the acquire might not be necessary since not doing a subsequent read
802 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
803 ssize_t filled = rear - cblk->u.mStreaming.mFront;
804 // pipe should not already be overfull
805 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700806 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800807 mIsShutdown = true;
808 return 0;
809 }
810 // cache this value for later use by obtainBuffer(), with added barrier
811 // and racy if called by normal mixer thread
812 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
813 return filled;
814}
815
Eric Laurentbfb1b832013-01-07 09:53:42 -0800816bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700817 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800818 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700819 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800820 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700821 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700822 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800823 }
824 return old;
825}
826
Glenn Kasten82aaf942013-07-17 16:05:07 -0700827void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
828{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700829 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800830 if (frameCount > 0) {
831 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700832
Phil Burk2812d9e2016-01-04 10:34:30 -0800833 if (!mUnderrunning) { // start of underrun?
834 mUnderrunCount++;
835 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
836 mUnderrunning = true;
837 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
838 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
839 }
840
841 // FIXME also wake futex so that underrun is noticed more quickly
842 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
843 } else {
844 ALOGV_IF(mUnderrunning,
845 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
846 frameCount, cblk->u.mStreaming.mUnderrunFrames);
847 mUnderrunning = false; // so we can detect the next edge
848 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700849}
850
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700851AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700852{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700853 mPlaybackRateObserver.poll(mPlaybackRate);
854 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700855}
856
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800857// ---------------------------------------------------------------------------
858
859StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
860 size_t frameCount, size_t frameSize)
861 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800862 mObserver(&cblk->u.mStatic.mSingleStateQueue),
863 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800864 mFramesReadySafe(frameCount), mFramesReady(frameCount),
865 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800866{
Andy Hung9b461582014-12-01 17:56:29 -0800867 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800868}
869
870void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
871{
872 mFramesReadyIsCalledByMultipleThreads = true;
873}
874
875size_t StaticAudioTrackServerProxy::framesReady()
876{
Andy Hungcb2129b2014-11-11 12:17:22 -0800877 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800878 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800879 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800880 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800881 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882}
883
Andy Hung9b461582014-12-01 17:56:29 -0800884status_t StaticAudioTrackServerProxy::updateStateWithLoop(
885 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800886{
Andy Hung9b461582014-12-01 17:56:29 -0800887 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800888 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800889 const size_t loopStart = update.mLoopStart;
890 const size_t loopEnd = update.mLoopEnd;
891 size_t position = localState->mPosition;
892 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800893 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800894 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800895 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
896 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800897 // If the current position is greater than the end of the loop
898 // we "wrap" to the loop start. This might cause an audible pop.
899 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800900 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800901 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800902 valid = true;
903 }
904 }
Andy Hung9b461582014-12-01 17:56:29 -0800905 if (!valid || position > mFrameCount) {
906 return NO_INIT;
907 }
908 localState->mPosition = position;
909 localState->mLoopCount = update.mLoopCount;
910 localState->mLoopEnd = loopEnd;
911 localState->mLoopStart = loopStart;
912 localState->mLoopSequence = update.mLoopSequence;
913 }
914 return OK;
915}
916
917status_t StaticAudioTrackServerProxy::updateStateWithPosition(
918 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
919{
920 if (localState->mPositionSequence != update.mPositionSequence) {
921 if (update.mPosition > mFrameCount) {
922 return NO_INIT;
923 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
924 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
925 }
926 localState->mPosition = update.mPosition;
927 localState->mPositionSequence = update.mPositionSequence;
928 }
929 return OK;
930}
931
932ssize_t StaticAudioTrackServerProxy::pollPosition()
933{
934 StaticAudioTrackState state;
935 if (mObserver.poll(state)) {
936 StaticAudioTrackState trystate = mState;
937 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700938 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800939
940 if (diffSeq < 0) {
941 result = updateStateWithLoop(&trystate, state) == OK &&
942 updateStateWithPosition(&trystate, state) == OK;
943 } else {
944 result = updateStateWithPosition(&trystate, state) == OK &&
945 updateStateWithLoop(&trystate, state) == OK;
946 }
947 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800948 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800949 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800950 ALOGE("%s client pushed an invalid state, shutting down", __func__);
951 mIsShutdown = true;
952 return (ssize_t) NO_INIT;
953 }
Andy Hung9b461582014-12-01 17:56:29 -0800954 mState = trystate;
955 if (mState.mLoopCount == -1) {
956 mFramesReady = INT64_MAX;
957 } else if (mState.mLoopCount == 0) {
958 mFramesReady = mFrameCount - mState.mPosition;
959 } else if (mState.mLoopCount > 0) {
960 // TODO: Later consider fixing overflow, but does not seem needed now
961 // as will not overflow if loopStart and loopEnd are Java "ints".
962 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
963 + mFrameCount - mState.mPosition;
964 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800965 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800966 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800967 StaticAudioTrackPosLoop posLoop;
968
969 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
970 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
971 mPosLoopMutator.push(posLoop);
972 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800973 }
Andy Hung9b461582014-12-01 17:56:29 -0800974 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800975}
976
Andy Hung954ca452015-09-09 14:39:02 -0700977status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800978{
979 if (mIsShutdown) {
980 buffer->mFrameCount = 0;
981 buffer->mRaw = NULL;
982 buffer->mNonContig = 0;
983 mUnreleased = 0;
984 return NO_INIT;
985 }
986 ssize_t positionOrStatus = pollPosition();
987 if (positionOrStatus < 0) {
988 buffer->mFrameCount = 0;
989 buffer->mRaw = NULL;
990 buffer->mNonContig = 0;
991 mUnreleased = 0;
992 return (status_t) positionOrStatus;
993 }
994 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800995 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800996 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800997 if (position < end) {
998 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800999 size_t wanted = buffer->mFrameCount;
1000 if (avail < wanted) {
1001 buffer->mFrameCount = avail;
1002 } else {
1003 avail = wanted;
1004 }
1005 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1006 } else {
1007 avail = 0;
1008 buffer->mFrameCount = 0;
1009 buffer->mRaw = NULL;
1010 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001011 // As mFramesReady is the total remaining frames in the static audio track,
1012 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -08001013 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001014 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001015 if (!ackFlush) {
1016 mUnreleased = avail;
1017 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001018 return NO_ERROR;
1019}
1020
1021void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1022{
1023 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -08001024 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -07001025 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001027 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001028 buffer->mRaw = NULL;
1029 buffer->mNonContig = 0;
1030 return;
1031 }
1032 mUnreleased -= stepCount;
1033 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001034 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001035 size_t newPosition = position + stepCount;
1036 int32_t setFlags = 0;
1037 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001038 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1039 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001040 newPosition = mFrameCount;
1041 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001042 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001043 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001044 setFlags = CBLK_LOOP_CYCLE;
1045 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001046 setFlags = CBLK_LOOP_FINAL;
1047 }
1048 }
1049 if (newPosition == mFrameCount) {
1050 setFlags |= CBLK_BUFFER_END;
1051 }
Andy Hung9b461582014-12-01 17:56:29 -08001052 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001053 if (mFramesReady != INT64_MAX) {
1054 mFramesReady -= stepCount;
1055 }
1056 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001057
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001058 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001059 mReleased += stepCount;
1060
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001061 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001062 StaticAudioTrackPosLoop posLoop;
1063 posLoop.mBufferPosition = mState.mPosition;
1064 posLoop.mLoopCount = mState.mLoopCount;
1065 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001066 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001067 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001068 // this would be a good place to wake a futex
1069 }
1070
1071 buffer->mFrameCount = 0;
1072 buffer->mRaw = NULL;
1073 buffer->mNonContig = 0;
1074}
1075
Phil Burk2812d9e2016-01-04 10:34:30 -08001076void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001077{
1078 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1079 // we don't have a location to count underrun frames. The underrun frame counter
1080 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1081 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1082
1083 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001084 if (frameCount > 0) {
1085 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1086 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001087}
1088
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001089// ---------------------------------------------------------------------------
1090
Glenn Kastena8190fc2012-12-03 17:06:56 -08001091} // namespace android