blob: f7baa157b6146ef7c554188a32283867c34d1fd8 [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{
Phil Burke8972b02016-03-04 11:29:57 -080091 // The minimum should be greater than zero and less than the size
92 // at which underruns will occur.
Phil Burk26760d12016-03-21 11:53:07 -070093 const uint32_t minimum = 16; // based on AudioMixer::BLOCKSIZE
Phil Burke8972b02016-03-04 11:29:57 -080094 const uint32_t maximum = frameCount();
95 uint32_t clippedSize = size;
Phil Burk26760d12016-03-21 11:53:07 -070096 if (maximum < minimum) {
97 clippedSize = maximum;
98 } else if (clippedSize < minimum) {
Phil Burke8972b02016-03-04 11:29:57 -080099 clippedSize = minimum;
100 } else if (clippedSize > maximum) {
101 clippedSize = maximum;
102 }
103 // for server to read
104 android_atomic_release_store(clippedSize, (int32_t *)&mCblk->mBufferSizeInFrames);
105 // for client to read
106 mBufferSizeInFrames = clippedSize;
107 return clippedSize;
108}
109
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
335void ClientProxy::releaseBuffer(Buffer* buffer)
336{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700337 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800338 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700339 if (stepCount == 0 || mIsShutdown) {
340 // prevent accidental re-use of buffer
341 buffer->mFrameCount = 0;
342 buffer->mRaw = NULL;
343 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800344 return;
345 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700346 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
347 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800348 audio_track_cblk_t* cblk = mCblk;
349 // Both of these barriers are required
350 if (mIsOut) {
351 int32_t rear = cblk->u.mStreaming.mRear;
352 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
353 } else {
354 int32_t front = cblk->u.mStreaming.mFront;
355 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
356 }
357}
358
359void ClientProxy::binderDied()
360{
361 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700362 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900363 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800364 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700365 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
366 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800367 }
368}
369
370void ClientProxy::interrupt()
371{
372 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700373 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900374 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700375 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
376 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800377 }
378}
379
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700380__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800381size_t ClientProxy::getMisalignment()
382{
383 audio_track_cblk_t* cblk = mCblk;
384 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
385 (mFrameCountP2 - 1);
386}
387
388// ---------------------------------------------------------------------------
389
390void AudioTrackClientProxy::flush()
391{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700392 // This works for mFrameCountP2 <= 2^30
393 size_t increment = mFrameCountP2 << 1;
394 size_t mask = increment - 1;
395 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700396 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
397 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
398 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700399 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
400 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
401 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800402}
403
Eric Laurentbfb1b832013-01-07 09:53:42 -0800404bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700405 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800406}
407
408bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700409 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800410}
411
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100412status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
413{
414 struct timespec total; // total elapsed time spent waiting
415 total.tv_sec = 0;
416 total.tv_nsec = 0;
417 audio_track_cblk_t* cblk = mCblk;
418 status_t status;
419 enum {
420 TIMEOUT_ZERO, // requested == NULL || *requested == 0
421 TIMEOUT_INFINITE, // *requested == infinity
422 TIMEOUT_FINITE, // 0 < *requested < infinity
423 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
424 } timeout;
425 if (requested == NULL) {
426 timeout = TIMEOUT_ZERO;
427 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
428 timeout = TIMEOUT_ZERO;
429 } else if (requested->tv_sec == INT_MAX) {
430 timeout = TIMEOUT_INFINITE;
431 } else {
432 timeout = TIMEOUT_FINITE;
433 }
434 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700435 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100436 // check for track invalidation by server, or server death detection
437 if (flags & CBLK_INVALID) {
438 ALOGV("Track invalidated");
439 status = DEAD_OBJECT;
440 goto end;
441 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800442 // a track is not supposed to underrun at this stage but consider it done
443 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100444 ALOGV("stream end received");
445 status = NO_ERROR;
446 goto end;
447 }
448 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100449 if (flags & CBLK_INTERRUPT) {
450 ALOGV("waitStreamEndDone() interrupted by client");
451 status = -EINTR;
452 goto end;
453 }
454 struct timespec remaining;
455 const struct timespec *ts;
456 switch (timeout) {
457 case TIMEOUT_ZERO:
458 status = WOULD_BLOCK;
459 goto end;
460 case TIMEOUT_INFINITE:
461 ts = NULL;
462 break;
463 case TIMEOUT_FINITE:
464 timeout = TIMEOUT_CONTINUE;
465 if (MAX_SEC == 0) {
466 ts = requested;
467 break;
468 }
469 // fall through
470 case TIMEOUT_CONTINUE:
471 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
472 if (requested->tv_sec < total.tv_sec ||
473 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
474 status = TIMED_OUT;
475 goto end;
476 }
477 remaining.tv_sec = requested->tv_sec - total.tv_sec;
478 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
479 remaining.tv_nsec += 1000000000;
480 remaining.tv_sec++;
481 }
482 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
483 remaining.tv_sec = MAX_SEC;
484 remaining.tv_nsec = 0;
485 }
486 ts = &remaining;
487 break;
488 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800489 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100490 ts = NULL;
491 break;
492 }
493 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
494 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700495 errno = 0;
496 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100497 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700498 switch (errno) {
499 case 0: // normal wakeup by server, or by binderDied()
500 case EWOULDBLOCK: // benign race condition with server
501 case EINTR: // wait was interrupted by signal or other spurious wakeup
502 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100503 break;
504 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700505 status = errno;
506 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100507 goto end;
508 }
509 }
510 }
511
512end:
513 if (requested == NULL) {
514 requested = &kNonBlocking;
515 }
516 return status;
517}
518
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800519// ---------------------------------------------------------------------------
520
521StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
522 size_t frameCount, size_t frameSize)
523 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800524 mMutator(&cblk->u.mStatic.mSingleStateQueue),
525 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800526{
Andy Hung9b461582014-12-01 17:56:29 -0800527 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800528 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800529}
530
531void StaticAudioTrackClientProxy::flush()
532{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800533 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800534}
535
536void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
537{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800538 // This can only happen on a 64-bit client
539 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
540 // FIXME Should return an error status
541 return;
542 }
Andy Hung9b461582014-12-01 17:56:29 -0800543 mState.mLoopStart = (uint32_t) loopStart;
544 mState.mLoopEnd = (uint32_t) loopEnd;
545 mState.mLoopCount = loopCount;
546 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
547 // set patch-up variables until the mState is acknowledged by the ServerProxy.
548 // observed buffer position and loop count will freeze until then to give the
549 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800550 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800551 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800552 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
553 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800554 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800555 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800556 (void) mMutator.push(mState);
557}
558
559void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
560{
561 // This can only happen on a 64-bit client
562 if (position > UINT32_MAX) {
563 // FIXME Should return an error status
564 return;
565 }
566 mState.mPosition = (uint32_t) position;
567 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800568 // set patch-up variables until the mState is acknowledged by the ServerProxy.
569 // observed buffer position and loop count will freeze until then to give the
570 // illusion of a synchronous change.
571 if (mState.mLoopCount > 0) { // only check if loop count is changing
572 getBufferPositionAndLoopCount(NULL, NULL); // get last position
573 }
574 mPosLoop.mBufferPosition = position;
575 if (position >= mState.mLoopEnd) {
576 // no ongoing loop is possible if position is greater than loopEnd.
577 mPosLoop.mLoopCount = 0;
578 }
Andy Hung9b461582014-12-01 17:56:29 -0800579 (void) mMutator.push(mState);
580}
581
582void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
583 size_t loopEnd, int loopCount)
584{
585 setLoop(loopStart, loopEnd, loopCount);
586 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800587}
588
589size_t StaticAudioTrackClientProxy::getBufferPosition()
590{
Andy Hung4ede21d2014-12-12 15:37:34 -0800591 getBufferPositionAndLoopCount(NULL, NULL);
592 return mPosLoop.mBufferPosition;
593}
594
595void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
596 size_t *position, int *loopCount)
597{
598 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
599 if (mPosLoopObserver.poll(mPosLoop)) {
600 ; // a valid mPosLoop should be available if ackDone is true.
601 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800602 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800603 if (position != NULL) {
604 *position = mPosLoop.mBufferPosition;
605 }
606 if (loopCount != NULL) {
607 *loopCount = mPosLoop.mLoopCount;
608 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800609}
610
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800611// ---------------------------------------------------------------------------
612
613ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
614 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700615 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hung3f0c9022016-01-15 17:49:46 -0800616 mAvailToClient(0), mFlush(0), mReleased(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800617 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800618{
Phil Burke8972b02016-03-04 11:29:57 -0800619 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800620}
621
Glenn Kasten2e422c42013-10-18 13:00:29 -0700622status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800623{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700624 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800625 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700626 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800627 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700628 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800629 audio_track_cblk_t* cblk = mCblk;
630 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
631 // or use previous cached value from framesReady(), with added barrier if it omits.
632 int32_t front;
633 int32_t rear;
634 // See notes on barriers at ClientProxy::obtainBuffer()
635 if (mIsOut) {
636 int32_t flush = cblk->u.mStreaming.mFlush;
637 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100638 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800639 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700640 // effectively obtain then release whatever is in the buffer
Andy Hunga2d75cd2015-07-15 17:04:20 -0700641 const size_t overflowBit = mFrameCountP2 << 1;
642 const size_t mask = overflowBit - 1;
Glenn Kasten20f51b12014-10-30 10:43:19 -0700643 int32_t newFront = (front & ~mask) | (flush & mask);
644 ssize_t filled = rear - newFront;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700645 if (filled >= (ssize_t)overflowBit) {
646 // front and rear offsets span the overflow bit of the p2 mask
647 // so rebasing newFront on the front offset is off by the overflow bit.
648 // adjust newFront to match rear offset.
Glenn Kastendbd0f3c2015-07-17 11:04:04 -0700649 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hunga2d75cd2015-07-15 17:04:20 -0700650 newFront += overflowBit;
651 filled -= overflowBit;
652 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700653 // Rather than shutting down on a corrupt flush, just treat it as a full flush
654 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800655 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
Lajos Molnarf1063e22015-04-17 15:19:42 -0700656 "filled %zd=%#x",
657 mFlush, flush, front, rear,
658 (unsigned)mask, newFront, filled, (unsigned)filled);
Glenn Kasten20f51b12014-10-30 10:43:19 -0700659 newFront = rear;
660 }
661 mFlush = flush;
662 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
663 // There is no danger from a false positive, so err on the side of caution
664 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100665 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
666 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700667 (void) syscall(__NR_futex, &cblk->mFutex,
668 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100669 }
670 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700671 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800672 }
673 } else {
674 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
675 rear = cblk->u.mStreaming.mRear;
676 }
677 ssize_t filled = rear - front;
678 // pipe should not already be overfull
679 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700680 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800681 mIsShutdown = true;
682 }
683 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700684 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800685 }
686 // don't allow filling pipe beyond the nominal size
687 size_t availToServer;
688 if (mIsOut) {
689 availToServer = filled;
690 mAvailToClient = mFrameCount - filled;
691 } else {
692 availToServer = mFrameCount - filled;
693 mAvailToClient = filled;
694 }
695 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
696 size_t part1;
697 if (mIsOut) {
698 front &= mFrameCountP2 - 1;
699 part1 = mFrameCountP2 - front;
700 } else {
701 rear &= mFrameCountP2 - 1;
702 part1 = mFrameCountP2 - rear;
703 }
704 if (part1 > availToServer) {
705 part1 = availToServer;
706 }
707 size_t ask = buffer->mFrameCount;
708 if (part1 > ask) {
709 part1 = ask;
710 }
711 // is assignment redundant in some cases?
712 buffer->mFrameCount = part1;
713 buffer->mRaw = part1 > 0 ?
714 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
715 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700716 // After flush(), allow releaseBuffer() on a previously obtained buffer;
717 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
718 if (!ackFlush) {
719 mUnreleased = part1;
720 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800721 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700722 }
723no_init:
724 buffer->mFrameCount = 0;
725 buffer->mRaw = NULL;
726 buffer->mNonContig = 0;
727 mUnreleased = 0;
728 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800729}
730
731void ServerProxy::releaseBuffer(Buffer* buffer)
732{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700733 LOG_ALWAYS_FATAL_IF(buffer == NULL);
734 size_t stepCount = buffer->mFrameCount;
735 if (stepCount == 0 || mIsShutdown) {
736 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800737 buffer->mFrameCount = 0;
738 buffer->mRaw = NULL;
739 buffer->mNonContig = 0;
740 return;
741 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700742 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800743 mUnreleased -= stepCount;
744 audio_track_cblk_t* cblk = mCblk;
745 if (mIsOut) {
746 int32_t front = cblk->u.mStreaming.mFront;
747 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
748 } else {
749 int32_t rear = cblk->u.mStreaming.mRear;
750 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
751 }
752
Glenn Kasten844f88c2014-05-09 13:38:09 -0700753 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800754 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800755
756 size_t half = mFrameCount / 2;
757 if (half == 0) {
758 half = 1;
759 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800760 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800761 if (minimum == 0) {
762 minimum = mIsOut ? half : 1;
763 } else if (minimum > half) {
764 minimum = half;
765 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700766 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700767 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700768 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700769 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
770 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700771 (void) syscall(__NR_futex, &cblk->mFutex,
772 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800773 }
774 }
775
776 buffer->mFrameCount = 0;
777 buffer->mRaw = NULL;
778 buffer->mNonContig = 0;
779}
780
781// ---------------------------------------------------------------------------
782
783size_t AudioTrackServerProxy::framesReady()
784{
785 LOG_ALWAYS_FATAL_IF(!mIsOut);
786
787 if (mIsShutdown) {
788 return 0;
789 }
790 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100791
792 int32_t flush = cblk->u.mStreaming.mFlush;
793 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700794 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100795 return mFrameCount;
796 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800797 // the acquire might not be necessary since not doing a subsequent read
798 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
799 ssize_t filled = rear - cblk->u.mStreaming.mFront;
800 // pipe should not already be overfull
801 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700802 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800803 mIsShutdown = true;
804 return 0;
805 }
806 // cache this value for later use by obtainBuffer(), with added barrier
807 // and racy if called by normal mixer thread
808 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
809 return filled;
810}
811
Eric Laurentbfb1b832013-01-07 09:53:42 -0800812bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700813 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800814 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700815 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800816 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700817 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700818 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800819 }
820 return old;
821}
822
Glenn Kasten82aaf942013-07-17 16:05:07 -0700823void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
824{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700825 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800826 if (frameCount > 0) {
827 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700828
Phil Burk2812d9e2016-01-04 10:34:30 -0800829 if (!mUnderrunning) { // start of underrun?
830 mUnderrunCount++;
831 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
832 mUnderrunning = true;
833 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
834 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
835 }
836
837 // FIXME also wake futex so that underrun is noticed more quickly
838 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
839 } else {
840 ALOGV_IF(mUnderrunning,
841 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
842 frameCount, cblk->u.mStreaming.mUnderrunFrames);
843 mUnderrunning = false; // so we can detect the next edge
844 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700845}
846
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700847AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700848{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700849 mPlaybackRateObserver.poll(mPlaybackRate);
850 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700851}
852
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800853// ---------------------------------------------------------------------------
854
855StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
856 size_t frameCount, size_t frameSize)
857 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800858 mObserver(&cblk->u.mStatic.mSingleStateQueue),
859 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800860 mFramesReadySafe(frameCount), mFramesReady(frameCount),
861 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800862{
Andy Hung9b461582014-12-01 17:56:29 -0800863 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800864}
865
866void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
867{
868 mFramesReadyIsCalledByMultipleThreads = true;
869}
870
871size_t StaticAudioTrackServerProxy::framesReady()
872{
Andy Hungcb2129b2014-11-11 12:17:22 -0800873 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800874 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800875 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800876 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800877 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800878}
879
Andy Hung9b461582014-12-01 17:56:29 -0800880status_t StaticAudioTrackServerProxy::updateStateWithLoop(
881 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800882{
Andy Hung9b461582014-12-01 17:56:29 -0800883 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800884 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800885 const size_t loopStart = update.mLoopStart;
886 const size_t loopEnd = update.mLoopEnd;
887 size_t position = localState->mPosition;
888 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800889 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800890 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800891 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
892 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800893 // If the current position is greater than the end of the loop
894 // we "wrap" to the loop start. This might cause an audible pop.
895 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800896 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800897 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800898 valid = true;
899 }
900 }
Andy Hung9b461582014-12-01 17:56:29 -0800901 if (!valid || position > mFrameCount) {
902 return NO_INIT;
903 }
904 localState->mPosition = position;
905 localState->mLoopCount = update.mLoopCount;
906 localState->mLoopEnd = loopEnd;
907 localState->mLoopStart = loopStart;
908 localState->mLoopSequence = update.mLoopSequence;
909 }
910 return OK;
911}
912
913status_t StaticAudioTrackServerProxy::updateStateWithPosition(
914 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
915{
916 if (localState->mPositionSequence != update.mPositionSequence) {
917 if (update.mPosition > mFrameCount) {
918 return NO_INIT;
919 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
920 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
921 }
922 localState->mPosition = update.mPosition;
923 localState->mPositionSequence = update.mPositionSequence;
924 }
925 return OK;
926}
927
928ssize_t StaticAudioTrackServerProxy::pollPosition()
929{
930 StaticAudioTrackState state;
931 if (mObserver.poll(state)) {
932 StaticAudioTrackState trystate = mState;
933 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700934 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800935
936 if (diffSeq < 0) {
937 result = updateStateWithLoop(&trystate, state) == OK &&
938 updateStateWithPosition(&trystate, state) == OK;
939 } else {
940 result = updateStateWithPosition(&trystate, state) == OK &&
941 updateStateWithLoop(&trystate, state) == OK;
942 }
943 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800944 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800945 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800946 ALOGE("%s client pushed an invalid state, shutting down", __func__);
947 mIsShutdown = true;
948 return (ssize_t) NO_INIT;
949 }
Andy Hung9b461582014-12-01 17:56:29 -0800950 mState = trystate;
951 if (mState.mLoopCount == -1) {
952 mFramesReady = INT64_MAX;
953 } else if (mState.mLoopCount == 0) {
954 mFramesReady = mFrameCount - mState.mPosition;
955 } else if (mState.mLoopCount > 0) {
956 // TODO: Later consider fixing overflow, but does not seem needed now
957 // as will not overflow if loopStart and loopEnd are Java "ints".
958 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
959 + mFrameCount - mState.mPosition;
960 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800961 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800962 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800963 StaticAudioTrackPosLoop posLoop;
964
965 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
966 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
967 mPosLoopMutator.push(posLoop);
968 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800969 }
Andy Hung9b461582014-12-01 17:56:29 -0800970 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800971}
972
Andy Hung954ca452015-09-09 14:39:02 -0700973status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800974{
975 if (mIsShutdown) {
976 buffer->mFrameCount = 0;
977 buffer->mRaw = NULL;
978 buffer->mNonContig = 0;
979 mUnreleased = 0;
980 return NO_INIT;
981 }
982 ssize_t positionOrStatus = pollPosition();
983 if (positionOrStatus < 0) {
984 buffer->mFrameCount = 0;
985 buffer->mRaw = NULL;
986 buffer->mNonContig = 0;
987 mUnreleased = 0;
988 return (status_t) positionOrStatus;
989 }
990 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800991 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800992 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800993 if (position < end) {
994 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800995 size_t wanted = buffer->mFrameCount;
996 if (avail < wanted) {
997 buffer->mFrameCount = avail;
998 } else {
999 avail = wanted;
1000 }
1001 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1002 } else {
1003 avail = 0;
1004 buffer->mFrameCount = 0;
1005 buffer->mRaw = NULL;
1006 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001007 // As mFramesReady is the total remaining frames in the static audio track,
1008 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -08001009 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001010 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001011 if (!ackFlush) {
1012 mUnreleased = avail;
1013 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001014 return NO_ERROR;
1015}
1016
1017void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1018{
1019 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -08001020 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -07001021 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001022 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001023 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001024 buffer->mRaw = NULL;
1025 buffer->mNonContig = 0;
1026 return;
1027 }
1028 mUnreleased -= stepCount;
1029 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001030 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001031 size_t newPosition = position + stepCount;
1032 int32_t setFlags = 0;
1033 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001034 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1035 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001036 newPosition = mFrameCount;
1037 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001038 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001039 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001040 setFlags = CBLK_LOOP_CYCLE;
1041 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001042 setFlags = CBLK_LOOP_FINAL;
1043 }
1044 }
1045 if (newPosition == mFrameCount) {
1046 setFlags |= CBLK_BUFFER_END;
1047 }
Andy Hung9b461582014-12-01 17:56:29 -08001048 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001049 if (mFramesReady != INT64_MAX) {
1050 mFramesReady -= stepCount;
1051 }
1052 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001053
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001054 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001055 mReleased += stepCount;
1056
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001057 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001058 StaticAudioTrackPosLoop posLoop;
1059 posLoop.mBufferPosition = mState.mPosition;
1060 posLoop.mLoopCount = mState.mLoopCount;
1061 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001062 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001063 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001064 // this would be a good place to wake a futex
1065 }
1066
1067 buffer->mFrameCount = 0;
1068 buffer->mRaw = NULL;
1069 buffer->mNonContig = 0;
1070}
1071
Phil Burk2812d9e2016-01-04 10:34:30 -08001072void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001073{
1074 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1075 // we don't have a location to count underrun frames. The underrun frame counter
1076 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1077 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1078
1079 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001080 if (frameCount > 0) {
1081 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1082 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001083}
1084
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001085// ---------------------------------------------------------------------------
1086
Glenn Kastena8190fc2012-12-03 17:06:56 -08001087} // namespace android