blob: 2396d876b9881ecdd06368f6c826ea3fa537b711 [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
ilewis926b82f2016-03-29 14:50:36 -0700110__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800111status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
112 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800113{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700114 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800115 struct timespec total; // total elapsed time spent waiting
116 total.tv_sec = 0;
117 total.tv_nsec = 0;
118 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -0800119
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800120 status_t status;
121 enum {
122 TIMEOUT_ZERO, // requested == NULL || *requested == 0
123 TIMEOUT_INFINITE, // *requested == infinity
124 TIMEOUT_FINITE, // 0 < *requested < infinity
125 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
126 } timeout;
127 if (requested == NULL) {
128 timeout = TIMEOUT_ZERO;
129 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
130 timeout = TIMEOUT_ZERO;
131 } else if (requested->tv_sec == INT_MAX) {
132 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800133 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800134 timeout = TIMEOUT_FINITE;
135 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
136 measure = true;
137 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800138 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800139 struct timespec before;
140 bool beforeIsValid = false;
141 audio_track_cblk_t* cblk = mCblk;
142 bool ignoreInitialPendingInterrupt = true;
143 // check for shared memory corruption
144 if (mIsShutdown) {
145 status = NO_INIT;
146 goto end;
147 }
148 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700149 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800150 // check for track invalidation by server, or server death detection
151 if (flags & CBLK_INVALID) {
152 ALOGV("Track invalidated");
153 status = DEAD_OBJECT;
154 goto end;
155 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800156 if (flags & CBLK_DISABLED) {
157 ALOGV("Track disabled");
158 status = NOT_ENOUGH_DATA;
159 goto end;
160 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800161 // check for obtainBuffer interrupted by client
162 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
163 ALOGV("obtainBuffer() interrupted by client");
164 status = -EINTR;
165 goto end;
166 }
167 ignoreInitialPendingInterrupt = false;
168 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
169 int32_t front;
170 int32_t rear;
171 if (mIsOut) {
172 // The barrier following the read of mFront is probably redundant.
173 // We're about to perform a conditional branch based on 'filled',
174 // which will force the processor to observe the read of mFront
175 // prior to allowing data writes starting at mRaw.
176 // However, the processor may support speculative execution,
177 // and be unable to undo speculative writes into shared memory.
178 // The barrier will prevent such speculative execution.
179 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
180 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800181 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800182 // On the other hand, this barrier is required.
183 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
184 front = cblk->u.mStreaming.mFront;
185 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800186 // write to rear, read from front
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800187 ssize_t filled = rear - front;
188 // pipe should not be overfull
189 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700190 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700191 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700192 "shutting down", filled, mFrameCount);
193 mIsShutdown = true;
194 status = NO_INIT;
195 goto end;
196 }
197 // for input, sync up on overrun
198 filled = 0;
199 cblk->u.mStreaming.mFront = rear;
200 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800201 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800202 // Don't allow filling pipe beyond the user settable size.
203 // The calculation for avail can go negative if the buffer size
204 // is suddenly dropped below the amount already in the buffer.
205 // So use a signed calculation to prevent a numeric overflow abort.
Phil Burke8972b02016-03-04 11:29:57 -0800206 ssize_t adjustableSize = (ssize_t) getBufferSizeInFrames();
Phil Burkc0adecb2016-01-08 12:44:11 -0800207 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
208 if (avail < 0) {
209 avail = 0;
210 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800211 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800212 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800213 if (mIsOut) {
214 rear &= mFrameCountP2 - 1;
215 part1 = mFrameCountP2 - rear;
216 } else {
217 front &= mFrameCountP2 - 1;
218 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800219 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800220 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800221 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800222 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800223 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224 part1 = buffer->mFrameCount;
225 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800226 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800227 buffer->mRaw = part1 > 0 ?
228 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
229 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700230 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800231 status = NO_ERROR;
232 break;
233 }
234 struct timespec remaining;
235 const struct timespec *ts;
236 switch (timeout) {
237 case TIMEOUT_ZERO:
238 status = WOULD_BLOCK;
239 goto end;
240 case TIMEOUT_INFINITE:
241 ts = NULL;
242 break;
243 case TIMEOUT_FINITE:
244 timeout = TIMEOUT_CONTINUE;
245 if (MAX_SEC == 0) {
246 ts = requested;
247 break;
248 }
249 // fall through
250 case TIMEOUT_CONTINUE:
251 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
252 if (!measure || requested->tv_sec < total.tv_sec ||
253 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
254 status = TIMED_OUT;
255 goto end;
256 }
257 remaining.tv_sec = requested->tv_sec - total.tv_sec;
258 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
259 remaining.tv_nsec += 1000000000;
260 remaining.tv_sec++;
261 }
262 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
263 remaining.tv_sec = MAX_SEC;
264 remaining.tv_nsec = 0;
265 }
266 ts = &remaining;
267 break;
268 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800269 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800270 ts = NULL;
271 break;
272 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700273 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
274 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800275 if (measure && !beforeIsValid) {
276 clock_gettime(CLOCK_MONOTONIC, &before);
277 beforeIsValid = true;
278 }
Elliott Hughesee499292014-05-21 17:55:51 -0700279 errno = 0;
280 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700281 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800282 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800283 // update total elapsed time spent waiting
284 if (measure) {
285 struct timespec after;
286 clock_gettime(CLOCK_MONOTONIC, &after);
287 total.tv_sec += after.tv_sec - before.tv_sec;
288 long deltaNs = after.tv_nsec - before.tv_nsec;
289 if (deltaNs < 0) {
290 deltaNs += 1000000000;
291 total.tv_sec--;
292 }
293 if ((total.tv_nsec += deltaNs) >= 1000000000) {
294 total.tv_nsec -= 1000000000;
295 total.tv_sec++;
296 }
297 before = after;
298 beforeIsValid = true;
299 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800300 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700301 case 0: // normal wakeup by server, or by binderDied()
302 case EWOULDBLOCK: // benign race condition with server
303 case EINTR: // wait was interrupted by signal or other spurious wakeup
304 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700305 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800306 break;
307 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800308 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700309 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800310 goto end;
311 }
312 }
313 }
314
315end:
316 if (status != NO_ERROR) {
317 buffer->mFrameCount = 0;
318 buffer->mRaw = NULL;
319 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700320 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800321 }
322 if (elapsed != NULL) {
323 *elapsed = total;
324 }
325 if (requested == NULL) {
326 requested = &kNonBlocking;
327 }
328 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100329 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
330 requested->tv_sec, requested->tv_nsec / 1000000,
331 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800332 }
333 return status;
334}
335
ilewis926b82f2016-03-29 14:50:36 -0700336__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800337void ClientProxy::releaseBuffer(Buffer* buffer)
338{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700339 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800340 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700341 if (stepCount == 0 || mIsShutdown) {
342 // prevent accidental re-use of buffer
343 buffer->mFrameCount = 0;
344 buffer->mRaw = NULL;
345 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800346 return;
347 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700348 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
349 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800350 audio_track_cblk_t* cblk = mCblk;
351 // Both of these barriers are required
352 if (mIsOut) {
353 int32_t rear = cblk->u.mStreaming.mRear;
354 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
355 } else {
356 int32_t front = cblk->u.mStreaming.mFront;
357 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
358 }
359}
360
361void ClientProxy::binderDied()
362{
363 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700364 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900365 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800366 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700367 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
368 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800369 }
370}
371
372void ClientProxy::interrupt()
373{
374 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700375 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900376 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700377 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
378 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800379 }
380}
381
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700382__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800383size_t ClientProxy::getMisalignment()
384{
385 audio_track_cblk_t* cblk = mCblk;
386 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
387 (mFrameCountP2 - 1);
388}
389
390// ---------------------------------------------------------------------------
391
392void AudioTrackClientProxy::flush()
393{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700394 // This works for mFrameCountP2 <= 2^30
395 size_t increment = mFrameCountP2 << 1;
396 size_t mask = increment - 1;
397 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700398 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
399 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
400 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700401 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
402 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
403 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800404}
405
Eric Laurentbfb1b832013-01-07 09:53:42 -0800406bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700407 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800408}
409
410bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700411 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800412}
413
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100414status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
415{
416 struct timespec total; // total elapsed time spent waiting
417 total.tv_sec = 0;
418 total.tv_nsec = 0;
419 audio_track_cblk_t* cblk = mCblk;
420 status_t status;
421 enum {
422 TIMEOUT_ZERO, // requested == NULL || *requested == 0
423 TIMEOUT_INFINITE, // *requested == infinity
424 TIMEOUT_FINITE, // 0 < *requested < infinity
425 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
426 } timeout;
427 if (requested == NULL) {
428 timeout = TIMEOUT_ZERO;
429 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
430 timeout = TIMEOUT_ZERO;
431 } else if (requested->tv_sec == INT_MAX) {
432 timeout = TIMEOUT_INFINITE;
433 } else {
434 timeout = TIMEOUT_FINITE;
435 }
436 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700437 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100438 // check for track invalidation by server, or server death detection
439 if (flags & CBLK_INVALID) {
440 ALOGV("Track invalidated");
441 status = DEAD_OBJECT;
442 goto end;
443 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800444 // a track is not supposed to underrun at this stage but consider it done
445 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100446 ALOGV("stream end received");
447 status = NO_ERROR;
448 goto end;
449 }
450 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100451 if (flags & CBLK_INTERRUPT) {
452 ALOGV("waitStreamEndDone() interrupted by client");
453 status = -EINTR;
454 goto end;
455 }
456 struct timespec remaining;
457 const struct timespec *ts;
458 switch (timeout) {
459 case TIMEOUT_ZERO:
460 status = WOULD_BLOCK;
461 goto end;
462 case TIMEOUT_INFINITE:
463 ts = NULL;
464 break;
465 case TIMEOUT_FINITE:
466 timeout = TIMEOUT_CONTINUE;
467 if (MAX_SEC == 0) {
468 ts = requested;
469 break;
470 }
471 // fall through
472 case TIMEOUT_CONTINUE:
473 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
474 if (requested->tv_sec < total.tv_sec ||
475 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
476 status = TIMED_OUT;
477 goto end;
478 }
479 remaining.tv_sec = requested->tv_sec - total.tv_sec;
480 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
481 remaining.tv_nsec += 1000000000;
482 remaining.tv_sec++;
483 }
484 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
485 remaining.tv_sec = MAX_SEC;
486 remaining.tv_nsec = 0;
487 }
488 ts = &remaining;
489 break;
490 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800491 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100492 ts = NULL;
493 break;
494 }
495 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
496 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700497 errno = 0;
498 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100499 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700500 switch (errno) {
501 case 0: // normal wakeup by server, or by binderDied()
502 case EWOULDBLOCK: // benign race condition with server
503 case EINTR: // wait was interrupted by signal or other spurious wakeup
504 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100505 break;
506 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700507 status = errno;
508 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100509 goto end;
510 }
511 }
512 }
513
514end:
515 if (requested == NULL) {
516 requested = &kNonBlocking;
517 }
518 return status;
519}
520
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800521// ---------------------------------------------------------------------------
522
523StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
524 size_t frameCount, size_t frameSize)
525 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800526 mMutator(&cblk->u.mStatic.mSingleStateQueue),
527 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800528{
Andy Hung9b461582014-12-01 17:56:29 -0800529 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800530 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800531}
532
533void StaticAudioTrackClientProxy::flush()
534{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800535 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800536}
537
538void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
539{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800540 // This can only happen on a 64-bit client
541 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
542 // FIXME Should return an error status
543 return;
544 }
Andy Hung9b461582014-12-01 17:56:29 -0800545 mState.mLoopStart = (uint32_t) loopStart;
546 mState.mLoopEnd = (uint32_t) loopEnd;
547 mState.mLoopCount = loopCount;
548 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
549 // set patch-up variables until the mState is acknowledged by the ServerProxy.
550 // observed buffer position and loop count will freeze until then to give the
551 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800552 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800553 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800554 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
555 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800556 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800557 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800558 (void) mMutator.push(mState);
559}
560
561void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
562{
563 // This can only happen on a 64-bit client
564 if (position > UINT32_MAX) {
565 // FIXME Should return an error status
566 return;
567 }
568 mState.mPosition = (uint32_t) position;
569 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800570 // set patch-up variables until the mState is acknowledged by the ServerProxy.
571 // observed buffer position and loop count will freeze until then to give the
572 // illusion of a synchronous change.
573 if (mState.mLoopCount > 0) { // only check if loop count is changing
574 getBufferPositionAndLoopCount(NULL, NULL); // get last position
575 }
576 mPosLoop.mBufferPosition = position;
577 if (position >= mState.mLoopEnd) {
578 // no ongoing loop is possible if position is greater than loopEnd.
579 mPosLoop.mLoopCount = 0;
580 }
Andy Hung9b461582014-12-01 17:56:29 -0800581 (void) mMutator.push(mState);
582}
583
584void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
585 size_t loopEnd, int loopCount)
586{
587 setLoop(loopStart, loopEnd, loopCount);
588 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800589}
590
591size_t StaticAudioTrackClientProxy::getBufferPosition()
592{
Andy Hung4ede21d2014-12-12 15:37:34 -0800593 getBufferPositionAndLoopCount(NULL, NULL);
594 return mPosLoop.mBufferPosition;
595}
596
597void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
598 size_t *position, int *loopCount)
599{
600 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
601 if (mPosLoopObserver.poll(mPosLoop)) {
602 ; // a valid mPosLoop should be available if ackDone is true.
603 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800604 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800605 if (position != NULL) {
606 *position = mPosLoop.mBufferPosition;
607 }
608 if (loopCount != NULL) {
609 *loopCount = mPosLoop.mLoopCount;
610 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800611}
612
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800613// ---------------------------------------------------------------------------
614
615ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
616 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700617 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hung3f0c9022016-01-15 17:49:46 -0800618 mAvailToClient(0), mFlush(0), mReleased(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800619 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800620{
Phil Burke8972b02016-03-04 11:29:57 -0800621 cblk->mBufferSizeInFrames = frameCount;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800622}
623
ilewis926b82f2016-03-29 14:50:36 -0700624__attribute__((no_sanitize("integer")))
Glenn Kasten2e422c42013-10-18 13:00:29 -0700625status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800626{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700627 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800628 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700629 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800630 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700631 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800632 audio_track_cblk_t* cblk = mCblk;
633 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
634 // or use previous cached value from framesReady(), with added barrier if it omits.
635 int32_t front;
636 int32_t rear;
637 // See notes on barriers at ClientProxy::obtainBuffer()
638 if (mIsOut) {
639 int32_t flush = cblk->u.mStreaming.mFlush;
640 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100641 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800642 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700643 // effectively obtain then release whatever is in the buffer
Andy Hunga2d75cd2015-07-15 17:04:20 -0700644 const size_t overflowBit = mFrameCountP2 << 1;
645 const size_t mask = overflowBit - 1;
Glenn Kasten20f51b12014-10-30 10:43:19 -0700646 int32_t newFront = (front & ~mask) | (flush & mask);
647 ssize_t filled = rear - newFront;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700648 if (filled >= (ssize_t)overflowBit) {
649 // front and rear offsets span the overflow bit of the p2 mask
650 // so rebasing newFront on the front offset is off by the overflow bit.
651 // adjust newFront to match rear offset.
Glenn Kastendbd0f3c2015-07-17 11:04:04 -0700652 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hunga2d75cd2015-07-15 17:04:20 -0700653 newFront += overflowBit;
654 filled -= overflowBit;
655 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700656 // Rather than shutting down on a corrupt flush, just treat it as a full flush
657 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800658 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
Lajos Molnarf1063e22015-04-17 15:19:42 -0700659 "filled %zd=%#x",
660 mFlush, flush, front, rear,
661 (unsigned)mask, newFront, filled, (unsigned)filled);
Glenn Kasten20f51b12014-10-30 10:43:19 -0700662 newFront = rear;
663 }
664 mFlush = flush;
665 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
666 // There is no danger from a false positive, so err on the side of caution
667 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100668 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
669 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700670 (void) syscall(__NR_futex, &cblk->mFutex,
671 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100672 }
673 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700674 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800675 }
676 } else {
677 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
678 rear = cblk->u.mStreaming.mRear;
679 }
680 ssize_t filled = rear - front;
681 // pipe should not already be overfull
682 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700683 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800684 mIsShutdown = true;
685 }
686 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700687 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800688 }
689 // don't allow filling pipe beyond the nominal size
690 size_t availToServer;
691 if (mIsOut) {
692 availToServer = filled;
693 mAvailToClient = mFrameCount - filled;
694 } else {
695 availToServer = mFrameCount - filled;
696 mAvailToClient = filled;
697 }
698 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
699 size_t part1;
700 if (mIsOut) {
701 front &= mFrameCountP2 - 1;
702 part1 = mFrameCountP2 - front;
703 } else {
704 rear &= mFrameCountP2 - 1;
705 part1 = mFrameCountP2 - rear;
706 }
707 if (part1 > availToServer) {
708 part1 = availToServer;
709 }
710 size_t ask = buffer->mFrameCount;
711 if (part1 > ask) {
712 part1 = ask;
713 }
714 // is assignment redundant in some cases?
715 buffer->mFrameCount = part1;
716 buffer->mRaw = part1 > 0 ?
717 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
718 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700719 // After flush(), allow releaseBuffer() on a previously obtained buffer;
720 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
721 if (!ackFlush) {
722 mUnreleased = part1;
723 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800724 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700725 }
726no_init:
727 buffer->mFrameCount = 0;
728 buffer->mRaw = NULL;
729 buffer->mNonContig = 0;
730 mUnreleased = 0;
731 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800732}
733
ilewis926b82f2016-03-29 14:50:36 -0700734__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800735void ServerProxy::releaseBuffer(Buffer* buffer)
736{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700737 LOG_ALWAYS_FATAL_IF(buffer == NULL);
738 size_t stepCount = buffer->mFrameCount;
739 if (stepCount == 0 || mIsShutdown) {
740 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800741 buffer->mFrameCount = 0;
742 buffer->mRaw = NULL;
743 buffer->mNonContig = 0;
744 return;
745 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700746 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800747 mUnreleased -= stepCount;
748 audio_track_cblk_t* cblk = mCblk;
749 if (mIsOut) {
750 int32_t front = cblk->u.mStreaming.mFront;
751 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
752 } else {
753 int32_t rear = cblk->u.mStreaming.mRear;
754 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
755 }
756
Glenn Kasten844f88c2014-05-09 13:38:09 -0700757 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800758 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800759
760 size_t half = mFrameCount / 2;
761 if (half == 0) {
762 half = 1;
763 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800764 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800765 if (minimum == 0) {
766 minimum = mIsOut ? half : 1;
767 } else if (minimum > half) {
768 minimum = half;
769 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700770 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700771 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700772 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700773 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
774 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700775 (void) syscall(__NR_futex, &cblk->mFutex,
776 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800777 }
778 }
779
780 buffer->mFrameCount = 0;
781 buffer->mRaw = NULL;
782 buffer->mNonContig = 0;
783}
784
785// ---------------------------------------------------------------------------
786
ilewis926b82f2016-03-29 14:50:36 -0700787__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800788size_t AudioTrackServerProxy::framesReady()
789{
790 LOG_ALWAYS_FATAL_IF(!mIsOut);
791
792 if (mIsShutdown) {
793 return 0;
794 }
795 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100796
797 int32_t flush = cblk->u.mStreaming.mFlush;
798 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700799 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100800 return mFrameCount;
801 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800802 // the acquire might not be necessary since not doing a subsequent read
803 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
804 ssize_t filled = rear - cblk->u.mStreaming.mFront;
805 // pipe should not already be overfull
806 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700807 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800808 mIsShutdown = true;
809 return 0;
810 }
811 // cache this value for later use by obtainBuffer(), with added barrier
812 // and racy if called by normal mixer thread
813 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
814 return filled;
815}
816
Eric Laurentbfb1b832013-01-07 09:53:42 -0800817bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700818 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800819 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700820 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800821 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700822 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700823 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800824 }
825 return old;
826}
827
Glenn Kasten82aaf942013-07-17 16:05:07 -0700828void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
829{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700830 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800831 if (frameCount > 0) {
832 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700833
Phil Burk2812d9e2016-01-04 10:34:30 -0800834 if (!mUnderrunning) { // start of underrun?
835 mUnderrunCount++;
836 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
837 mUnderrunning = true;
838 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
839 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
840 }
841
842 // FIXME also wake futex so that underrun is noticed more quickly
843 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
844 } else {
845 ALOGV_IF(mUnderrunning,
846 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
847 frameCount, cblk->u.mStreaming.mUnderrunFrames);
848 mUnderrunning = false; // so we can detect the next edge
849 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700850}
851
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700852AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700853{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700854 mPlaybackRateObserver.poll(mPlaybackRate);
855 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700856}
857
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800858// ---------------------------------------------------------------------------
859
860StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
861 size_t frameCount, size_t frameSize)
862 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800863 mObserver(&cblk->u.mStatic.mSingleStateQueue),
864 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800865 mFramesReadySafe(frameCount), mFramesReady(frameCount),
866 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800867{
Andy Hung9b461582014-12-01 17:56:29 -0800868 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800869}
870
871void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
872{
873 mFramesReadyIsCalledByMultipleThreads = true;
874}
875
876size_t StaticAudioTrackServerProxy::framesReady()
877{
Andy Hungcb2129b2014-11-11 12:17:22 -0800878 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800879 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800880 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800881 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800882 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800883}
884
Andy Hung9b461582014-12-01 17:56:29 -0800885status_t StaticAudioTrackServerProxy::updateStateWithLoop(
886 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800887{
Andy Hung9b461582014-12-01 17:56:29 -0800888 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800889 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800890 const size_t loopStart = update.mLoopStart;
891 const size_t loopEnd = update.mLoopEnd;
892 size_t position = localState->mPosition;
893 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800894 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800895 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800896 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
897 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800898 // If the current position is greater than the end of the loop
899 // we "wrap" to the loop start. This might cause an audible pop.
900 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800901 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800902 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800903 valid = true;
904 }
905 }
Andy Hung9b461582014-12-01 17:56:29 -0800906 if (!valid || position > mFrameCount) {
907 return NO_INIT;
908 }
909 localState->mPosition = position;
910 localState->mLoopCount = update.mLoopCount;
911 localState->mLoopEnd = loopEnd;
912 localState->mLoopStart = loopStart;
913 localState->mLoopSequence = update.mLoopSequence;
914 }
915 return OK;
916}
917
918status_t StaticAudioTrackServerProxy::updateStateWithPosition(
919 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
920{
921 if (localState->mPositionSequence != update.mPositionSequence) {
922 if (update.mPosition > mFrameCount) {
923 return NO_INIT;
924 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
925 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
926 }
927 localState->mPosition = update.mPosition;
928 localState->mPositionSequence = update.mPositionSequence;
929 }
930 return OK;
931}
932
933ssize_t StaticAudioTrackServerProxy::pollPosition()
934{
935 StaticAudioTrackState state;
936 if (mObserver.poll(state)) {
937 StaticAudioTrackState trystate = mState;
938 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700939 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800940
941 if (diffSeq < 0) {
942 result = updateStateWithLoop(&trystate, state) == OK &&
943 updateStateWithPosition(&trystate, state) == OK;
944 } else {
945 result = updateStateWithPosition(&trystate, state) == OK &&
946 updateStateWithLoop(&trystate, state) == OK;
947 }
948 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800949 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800950 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800951 ALOGE("%s client pushed an invalid state, shutting down", __func__);
952 mIsShutdown = true;
953 return (ssize_t) NO_INIT;
954 }
Andy Hung9b461582014-12-01 17:56:29 -0800955 mState = trystate;
956 if (mState.mLoopCount == -1) {
957 mFramesReady = INT64_MAX;
958 } else if (mState.mLoopCount == 0) {
959 mFramesReady = mFrameCount - mState.mPosition;
960 } else if (mState.mLoopCount > 0) {
961 // TODO: Later consider fixing overflow, but does not seem needed now
962 // as will not overflow if loopStart and loopEnd are Java "ints".
963 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
964 + mFrameCount - mState.mPosition;
965 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800966 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800967 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800968 StaticAudioTrackPosLoop posLoop;
969
970 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
971 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
972 mPosLoopMutator.push(posLoop);
973 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800974 }
Andy Hung9b461582014-12-01 17:56:29 -0800975 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800976}
977
Andy Hung954ca452015-09-09 14:39:02 -0700978status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800979{
980 if (mIsShutdown) {
981 buffer->mFrameCount = 0;
982 buffer->mRaw = NULL;
983 buffer->mNonContig = 0;
984 mUnreleased = 0;
985 return NO_INIT;
986 }
987 ssize_t positionOrStatus = pollPosition();
988 if (positionOrStatus < 0) {
989 buffer->mFrameCount = 0;
990 buffer->mRaw = NULL;
991 buffer->mNonContig = 0;
992 mUnreleased = 0;
993 return (status_t) positionOrStatus;
994 }
995 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800996 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800997 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800998 if (position < end) {
999 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001000 size_t wanted = buffer->mFrameCount;
1001 if (avail < wanted) {
1002 buffer->mFrameCount = avail;
1003 } else {
1004 avail = wanted;
1005 }
1006 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
1007 } else {
1008 avail = 0;
1009 buffer->mFrameCount = 0;
1010 buffer->mRaw = NULL;
1011 }
Andy Hungcb2129b2014-11-11 12:17:22 -08001012 // As mFramesReady is the total remaining frames in the static audio track,
1013 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -08001014 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001015 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001016 if (!ackFlush) {
1017 mUnreleased = avail;
1018 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001019 return NO_ERROR;
1020}
1021
1022void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1023{
1024 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -08001025 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -07001026 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001027 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001028 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001029 buffer->mRaw = NULL;
1030 buffer->mNonContig = 0;
1031 return;
1032 }
1033 mUnreleased -= stepCount;
1034 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001035 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001036 size_t newPosition = position + stepCount;
1037 int32_t setFlags = 0;
1038 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001039 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1040 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001041 newPosition = mFrameCount;
1042 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001043 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001044 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001045 setFlags = CBLK_LOOP_CYCLE;
1046 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001047 setFlags = CBLK_LOOP_FINAL;
1048 }
1049 }
1050 if (newPosition == mFrameCount) {
1051 setFlags |= CBLK_BUFFER_END;
1052 }
Andy Hung9b461582014-12-01 17:56:29 -08001053 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001054 if (mFramesReady != INT64_MAX) {
1055 mFramesReady -= stepCount;
1056 }
1057 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001058
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001059 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001060 mReleased += stepCount;
1061
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001062 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001063 StaticAudioTrackPosLoop posLoop;
1064 posLoop.mBufferPosition = mState.mPosition;
1065 posLoop.mLoopCount = mState.mLoopCount;
1066 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001067 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001068 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001069 // this would be a good place to wake a futex
1070 }
1071
1072 buffer->mFrameCount = 0;
1073 buffer->mRaw = NULL;
1074 buffer->mNonContig = 0;
1075}
1076
Phil Burk2812d9e2016-01-04 10:34:30 -08001077void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001078{
1079 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1080 // we don't have a location to count underrun frames. The underrun frame counter
1081 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1082 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1083
1084 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001085 if (frameCount > 0) {
1086 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1087 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001088}
1089
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001090// ---------------------------------------------------------------------------
1091
Glenn Kastena8190fc2012-12-03 17:06:56 -08001092} // namespace android