blob: 6b6865bacb258b2fe5e55669e37abceafb296ff0 [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()
Glenn Kasten74935e42013-12-19 08:56:45 -080049 : mServer(0), mFutex(0), mMinimum(0),
Glenn Kastenc56f3422014-03-21 17:53:17 -070050 mVolumeLR(GAIN_MINIFLOAT_PACKED_UNITY), mSampleRate(0), mSendLevel(0), mFlags(0)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080051{
52 memset(&u, 0, sizeof(u));
53}
54
55// ---------------------------------------------------------------------------
56
57Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
58 bool isOut, bool clientInServer)
59 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize),
60 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer),
Glenn Kasten7db7df02013-06-25 16:13:23 -070061 mIsShutdown(false), mUnreleased(0)
Glenn Kastena8190fc2012-12-03 17:06:56 -080062{
63}
64
Glenn Kasten9f80dd22012-12-18 15:57:32 -080065// ---------------------------------------------------------------------------
66
67ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
68 size_t frameSize, bool isOut, bool clientInServer)
Phil Burkc0adecb2016-01-08 12:44:11 -080069 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer)
70 , mBufferSizeInFrames(frameCount)
71 , mEpoch(0)
Andy Hung6ae58432016-02-16 18:32:24 -080072 , mTimestampObserver(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -080073{
Glenn Kastena8190fc2012-12-03 17:06:56 -080074}
75
Glenn Kasten9f80dd22012-12-18 15:57:32 -080076const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/};
77const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/};
78
79#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS
80
81// To facilitate quicker recovery from server failure, this value limits the timeout per each futex
82// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit.
83// FIXME May not be compatible with audio tunneling requirements where timeout should be in the
84// order of minutes.
85#define MAX_SEC 5
86
87status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested,
88 struct timespec *elapsed)
Glenn Kastena8190fc2012-12-03 17:06:56 -080089{
Glenn Kasten7db7df02013-06-25 16:13:23 -070090 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -080091 struct timespec total; // total elapsed time spent waiting
92 total.tv_sec = 0;
93 total.tv_nsec = 0;
94 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting
Glenn Kastena8190fc2012-12-03 17:06:56 -080095
Glenn Kasten9f80dd22012-12-18 15:57:32 -080096 status_t status;
97 enum {
98 TIMEOUT_ZERO, // requested == NULL || *requested == 0
99 TIMEOUT_INFINITE, // *requested == infinity
100 TIMEOUT_FINITE, // 0 < *requested < infinity
101 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
102 } timeout;
103 if (requested == NULL) {
104 timeout = TIMEOUT_ZERO;
105 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
106 timeout = TIMEOUT_ZERO;
107 } else if (requested->tv_sec == INT_MAX) {
108 timeout = TIMEOUT_INFINITE;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800109 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800110 timeout = TIMEOUT_FINITE;
111 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) {
112 measure = true;
113 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800114 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800115 struct timespec before;
116 bool beforeIsValid = false;
117 audio_track_cblk_t* cblk = mCblk;
118 bool ignoreInitialPendingInterrupt = true;
119 // check for shared memory corruption
120 if (mIsShutdown) {
121 status = NO_INIT;
122 goto end;
123 }
124 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700125 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800126 // check for track invalidation by server, or server death detection
127 if (flags & CBLK_INVALID) {
128 ALOGV("Track invalidated");
129 status = DEAD_OBJECT;
130 goto end;
131 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800132 if (flags & CBLK_DISABLED) {
133 ALOGV("Track disabled");
134 status = NOT_ENOUGH_DATA;
135 goto end;
136 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800137 // check for obtainBuffer interrupted by client
138 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) {
139 ALOGV("obtainBuffer() interrupted by client");
140 status = -EINTR;
141 goto end;
142 }
143 ignoreInitialPendingInterrupt = false;
144 // compute number of frames available to write (AudioTrack) or read (AudioRecord)
145 int32_t front;
146 int32_t rear;
147 if (mIsOut) {
148 // The barrier following the read of mFront is probably redundant.
149 // We're about to perform a conditional branch based on 'filled',
150 // which will force the processor to observe the read of mFront
151 // prior to allowing data writes starting at mRaw.
152 // However, the processor may support speculative execution,
153 // and be unable to undo speculative writes into shared memory.
154 // The barrier will prevent such speculative execution.
155 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
156 rear = cblk->u.mStreaming.mRear;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800157 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800158 // On the other hand, this barrier is required.
159 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
160 front = cblk->u.mStreaming.mFront;
161 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800162 // write to rear, read from front
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800163 ssize_t filled = rear - front;
164 // pipe should not be overfull
165 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700166 if (mIsOut) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700167 ALOGE("Shared memory control block is corrupt (filled=%zd, mFrameCount=%zu); "
Glenn Kasten6dbb5e32014-05-13 10:38:42 -0700168 "shutting down", filled, mFrameCount);
169 mIsShutdown = true;
170 status = NO_INIT;
171 goto end;
172 }
173 // for input, sync up on overrun
174 filled = 0;
175 cblk->u.mStreaming.mFront = rear;
176 (void) android_atomic_or(CBLK_OVERRUN, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800177 }
Phil Burkc0adecb2016-01-08 12:44:11 -0800178 // Don't allow filling pipe beyond the user settable size.
179 // The calculation for avail can go negative if the buffer size
180 // is suddenly dropped below the amount already in the buffer.
181 // So use a signed calculation to prevent a numeric overflow abort.
182 ssize_t adjustableSize = (ssize_t) mBufferSizeInFrames;
183 ssize_t avail = (mIsOut) ? adjustableSize - filled : filled;
184 if (avail < 0) {
185 avail = 0;
186 } else if (avail > 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800187 // 'avail' may be non-contiguous, so return only the first contiguous chunk
Eric Laurentbdd81012016-01-29 15:25:06 -0800188 size_t part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800189 if (mIsOut) {
190 rear &= mFrameCountP2 - 1;
191 part1 = mFrameCountP2 - rear;
192 } else {
193 front &= mFrameCountP2 - 1;
194 part1 = mFrameCountP2 - front;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800195 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800196 if (part1 > (size_t)avail) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800197 part1 = avail;
Glenn Kastena8190fc2012-12-03 17:06:56 -0800198 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800199 if (part1 > buffer->mFrameCount) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800200 part1 = buffer->mFrameCount;
201 }
Eric Laurentbdd81012016-01-29 15:25:06 -0800202 buffer->mFrameCount = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800203 buffer->mRaw = part1 > 0 ?
204 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL;
205 buffer->mNonContig = avail - part1;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700206 mUnreleased = part1;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800207 status = NO_ERROR;
208 break;
209 }
210 struct timespec remaining;
211 const struct timespec *ts;
212 switch (timeout) {
213 case TIMEOUT_ZERO:
214 status = WOULD_BLOCK;
215 goto end;
216 case TIMEOUT_INFINITE:
217 ts = NULL;
218 break;
219 case TIMEOUT_FINITE:
220 timeout = TIMEOUT_CONTINUE;
221 if (MAX_SEC == 0) {
222 ts = requested;
223 break;
224 }
225 // fall through
226 case TIMEOUT_CONTINUE:
227 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
228 if (!measure || requested->tv_sec < total.tv_sec ||
229 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
230 status = TIMED_OUT;
231 goto end;
232 }
233 remaining.tv_sec = requested->tv_sec - total.tv_sec;
234 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
235 remaining.tv_nsec += 1000000000;
236 remaining.tv_sec++;
237 }
238 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
239 remaining.tv_sec = MAX_SEC;
240 remaining.tv_nsec = 0;
241 }
242 ts = &remaining;
243 break;
244 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800245 LOG_ALWAYS_FATAL("obtainBuffer() timeout=%d", timeout);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800246 ts = NULL;
247 break;
248 }
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700249 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
250 if (!(old & CBLK_FUTEX_WAKE)) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800251 if (measure && !beforeIsValid) {
252 clock_gettime(CLOCK_MONOTONIC, &before);
253 beforeIsValid = true;
254 }
Elliott Hughesee499292014-05-21 17:55:51 -0700255 errno = 0;
256 (void) syscall(__NR_futex, &cblk->mFutex,
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700257 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Leena Winterrowdb463da82015-12-14 15:58:16 -0800258 status_t error = errno; // clock_gettime can affect errno
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800259 // update total elapsed time spent waiting
260 if (measure) {
261 struct timespec after;
262 clock_gettime(CLOCK_MONOTONIC, &after);
263 total.tv_sec += after.tv_sec - before.tv_sec;
264 long deltaNs = after.tv_nsec - before.tv_nsec;
265 if (deltaNs < 0) {
266 deltaNs += 1000000000;
267 total.tv_sec--;
268 }
269 if ((total.tv_nsec += deltaNs) >= 1000000000) {
270 total.tv_nsec -= 1000000000;
271 total.tv_sec++;
272 }
273 before = after;
274 beforeIsValid = true;
275 }
Leena Winterrowdb463da82015-12-14 15:58:16 -0800276 switch (error) {
Elliott Hughesee499292014-05-21 17:55:51 -0700277 case 0: // normal wakeup by server, or by binderDied()
278 case EWOULDBLOCK: // benign race condition with server
279 case EINTR: // wait was interrupted by signal or other spurious wakeup
280 case ETIMEDOUT: // time-out expired
Glenn Kasten7db7df02013-06-25 16:13:23 -0700281 // FIXME these error/non-0 status are being dropped
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800282 break;
283 default:
Leena Winterrowdb463da82015-12-14 15:58:16 -0800284 status = error;
Elliott Hughesee499292014-05-21 17:55:51 -0700285 ALOGE("%s unexpected error %s", __func__, strerror(status));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800286 goto end;
287 }
288 }
289 }
290
291end:
292 if (status != NO_ERROR) {
293 buffer->mFrameCount = 0;
294 buffer->mRaw = NULL;
295 buffer->mNonContig = 0;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700296 mUnreleased = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800297 }
298 if (elapsed != NULL) {
299 *elapsed = total;
300 }
301 if (requested == NULL) {
302 requested = &kNonBlocking;
303 }
304 if (measure) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100305 ALOGV("requested %ld.%03ld elapsed %ld.%03ld",
306 requested->tv_sec, requested->tv_nsec / 1000000,
307 total.tv_sec, total.tv_nsec / 1000000);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800308 }
309 return status;
310}
311
312void ClientProxy::releaseBuffer(Buffer* buffer)
313{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700314 LOG_ALWAYS_FATAL_IF(buffer == NULL);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800315 size_t stepCount = buffer->mFrameCount;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700316 if (stepCount == 0 || mIsShutdown) {
317 // prevent accidental re-use of buffer
318 buffer->mFrameCount = 0;
319 buffer->mRaw = NULL;
320 buffer->mNonContig = 0;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800321 return;
322 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700323 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
324 mUnreleased -= stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800325 audio_track_cblk_t* cblk = mCblk;
326 // Both of these barriers are required
327 if (mIsOut) {
328 int32_t rear = cblk->u.mStreaming.mRear;
329 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
330 } else {
331 int32_t front = cblk->u.mStreaming.mFront;
332 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
333 }
334}
335
336void ClientProxy::binderDied()
337{
338 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700339 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900340 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800341 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process
Elliott Hughesee499292014-05-21 17:55:51 -0700342 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
343 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800344 }
345}
346
347void ClientProxy::interrupt()
348{
349 audio_track_cblk_t* cblk = mCblk;
Glenn Kasten96f60d82013-07-12 10:21:18 -0700350 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) {
zunkyu.lee82a69ea2014-11-07 15:47:32 +0900351 android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
Elliott Hughesee499292014-05-21 17:55:51 -0700352 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
353 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800354 }
355}
356
Chad Brubaker65dda4f2015-09-22 16:13:30 -0700357__attribute__((no_sanitize("integer")))
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800358size_t ClientProxy::getMisalignment()
359{
360 audio_track_cblk_t* cblk = mCblk;
361 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) &
362 (mFrameCountP2 - 1);
363}
364
Phil Burkc0adecb2016-01-08 12:44:11 -0800365size_t ClientProxy::setBufferSizeInFrames(size_t size)
366{
367 // TODO set minimum to 2X the fast mixer buffer size.
368 size_t minimum = 128 * 2; // arbitrary
369 size_t maximum = frameCount();
370 if (size < minimum) {
371 size = minimum;
372 } else if (size > maximum) {
373 size = maximum;
374 }
375 mBufferSizeInFrames = size;
376 return size;
377}
378
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800379// ---------------------------------------------------------------------------
380
381void AudioTrackClientProxy::flush()
382{
Glenn Kasten20f51b12014-10-30 10:43:19 -0700383 // This works for mFrameCountP2 <= 2^30
384 size_t increment = mFrameCountP2 << 1;
385 size_t mask = increment - 1;
386 audio_track_cblk_t* cblk = mCblk;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700387 // mFlush is 32 bits concatenated as [ flush_counter ] [ newfront_offset ]
388 // Should newFlush = cblk->u.mStreaming.mRear? Only problem is
389 // if you want to flush twice to the same rear location after a 32 bit wrap.
Glenn Kasten20f51b12014-10-30 10:43:19 -0700390 int32_t newFlush = (cblk->u.mStreaming.mRear & mask) |
391 ((cblk->u.mStreaming.mFlush & ~mask) + increment);
392 android_atomic_release_store(newFlush, &cblk->u.mStreaming.mFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800393}
394
Eric Laurentbfb1b832013-01-07 09:53:42 -0800395bool AudioTrackClientProxy::clearStreamEndDone() {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700396 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800397}
398
399bool AudioTrackClientProxy::getStreamEndDone() const {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700400 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800401}
402
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100403status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested)
404{
405 struct timespec total; // total elapsed time spent waiting
406 total.tv_sec = 0;
407 total.tv_nsec = 0;
408 audio_track_cblk_t* cblk = mCblk;
409 status_t status;
410 enum {
411 TIMEOUT_ZERO, // requested == NULL || *requested == 0
412 TIMEOUT_INFINITE, // *requested == infinity
413 TIMEOUT_FINITE, // 0 < *requested < infinity
414 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE
415 } timeout;
416 if (requested == NULL) {
417 timeout = TIMEOUT_ZERO;
418 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) {
419 timeout = TIMEOUT_ZERO;
420 } else if (requested->tv_sec == INT_MAX) {
421 timeout = TIMEOUT_INFINITE;
422 } else {
423 timeout = TIMEOUT_FINITE;
424 }
425 for (;;) {
Glenn Kasten96f60d82013-07-12 10:21:18 -0700426 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100427 // check for track invalidation by server, or server death detection
428 if (flags & CBLK_INVALID) {
429 ALOGV("Track invalidated");
430 status = DEAD_OBJECT;
431 goto end;
432 }
Eric Laurent4d231dc2016-03-11 18:38:23 -0800433 // a track is not supposed to underrun at this stage but consider it done
434 if (flags & (CBLK_STREAM_END_DONE | CBLK_DISABLED)) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100435 ALOGV("stream end received");
436 status = NO_ERROR;
437 goto end;
438 }
439 // check for obtainBuffer interrupted by client
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100440 if (flags & CBLK_INTERRUPT) {
441 ALOGV("waitStreamEndDone() interrupted by client");
442 status = -EINTR;
443 goto end;
444 }
445 struct timespec remaining;
446 const struct timespec *ts;
447 switch (timeout) {
448 case TIMEOUT_ZERO:
449 status = WOULD_BLOCK;
450 goto end;
451 case TIMEOUT_INFINITE:
452 ts = NULL;
453 break;
454 case TIMEOUT_FINITE:
455 timeout = TIMEOUT_CONTINUE;
456 if (MAX_SEC == 0) {
457 ts = requested;
458 break;
459 }
460 // fall through
461 case TIMEOUT_CONTINUE:
462 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine
463 if (requested->tv_sec < total.tv_sec ||
464 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) {
465 status = TIMED_OUT;
466 goto end;
467 }
468 remaining.tv_sec = requested->tv_sec - total.tv_sec;
469 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) {
470 remaining.tv_nsec += 1000000000;
471 remaining.tv_sec++;
472 }
473 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) {
474 remaining.tv_sec = MAX_SEC;
475 remaining.tv_nsec = 0;
476 }
477 ts = &remaining;
478 break;
479 default:
Glenn Kastenadad3d72014-02-21 14:51:43 -0800480 LOG_ALWAYS_FATAL("waitStreamEndDone() timeout=%d", timeout);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100481 ts = NULL;
482 break;
483 }
484 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex);
485 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700486 errno = 0;
487 (void) syscall(__NR_futex, &cblk->mFutex,
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100488 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts);
Elliott Hughesee499292014-05-21 17:55:51 -0700489 switch (errno) {
490 case 0: // normal wakeup by server, or by binderDied()
491 case EWOULDBLOCK: // benign race condition with server
492 case EINTR: // wait was interrupted by signal or other spurious wakeup
493 case ETIMEDOUT: // time-out expired
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100494 break;
495 default:
Elliott Hughesee499292014-05-21 17:55:51 -0700496 status = errno;
497 ALOGE("%s unexpected error %s", __func__, strerror(status));
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100498 goto end;
499 }
500 }
501 }
502
503end:
504 if (requested == NULL) {
505 requested = &kNonBlocking;
506 }
507 return status;
508}
509
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800510// ---------------------------------------------------------------------------
511
512StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers,
513 size_t frameCount, size_t frameSize)
514 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800515 mMutator(&cblk->u.mStatic.mSingleStateQueue),
516 mPosLoopObserver(&cblk->u.mStatic.mPosLoopQueue)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800517{
Andy Hung9b461582014-12-01 17:56:29 -0800518 memset(&mState, 0, sizeof(mState));
Andy Hung4ede21d2014-12-12 15:37:34 -0800519 memset(&mPosLoop, 0, sizeof(mPosLoop));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800520}
521
522void StaticAudioTrackClientProxy::flush()
523{
Glenn Kastenadad3d72014-02-21 14:51:43 -0800524 LOG_ALWAYS_FATAL("static flush");
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800525}
526
527void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount)
528{
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800529 // This can only happen on a 64-bit client
530 if (loopStart > UINT32_MAX || loopEnd > UINT32_MAX) {
531 // FIXME Should return an error status
532 return;
533 }
Andy Hung9b461582014-12-01 17:56:29 -0800534 mState.mLoopStart = (uint32_t) loopStart;
535 mState.mLoopEnd = (uint32_t) loopEnd;
536 mState.mLoopCount = loopCount;
537 mState.mLoopSequence = incrementSequence(mState.mLoopSequence, mState.mPositionSequence);
538 // set patch-up variables until the mState is acknowledged by the ServerProxy.
539 // observed buffer position and loop count will freeze until then to give the
540 // illusion of a synchronous change.
Andy Hung4ede21d2014-12-12 15:37:34 -0800541 getBufferPositionAndLoopCount(NULL, NULL);
Andy Hung9b461582014-12-01 17:56:29 -0800542 // preserve behavior to restart at mState.mLoopStart if position exceeds mState.mLoopEnd.
Andy Hung4ede21d2014-12-12 15:37:34 -0800543 if (mState.mLoopCount != 0 && mPosLoop.mBufferPosition >= mState.mLoopEnd) {
544 mPosLoop.mBufferPosition = mState.mLoopStart;
Andy Hung680b7952014-11-12 13:18:52 -0800545 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800546 mPosLoop.mLoopCount = mState.mLoopCount;
Andy Hung9b461582014-12-01 17:56:29 -0800547 (void) mMutator.push(mState);
548}
549
550void StaticAudioTrackClientProxy::setBufferPosition(size_t position)
551{
552 // This can only happen on a 64-bit client
553 if (position > UINT32_MAX) {
554 // FIXME Should return an error status
555 return;
556 }
557 mState.mPosition = (uint32_t) position;
558 mState.mPositionSequence = incrementSequence(mState.mPositionSequence, mState.mLoopSequence);
Andy Hung4ede21d2014-12-12 15:37:34 -0800559 // set patch-up variables until the mState is acknowledged by the ServerProxy.
560 // observed buffer position and loop count will freeze until then to give the
561 // illusion of a synchronous change.
562 if (mState.mLoopCount > 0) { // only check if loop count is changing
563 getBufferPositionAndLoopCount(NULL, NULL); // get last position
564 }
565 mPosLoop.mBufferPosition = position;
566 if (position >= mState.mLoopEnd) {
567 // no ongoing loop is possible if position is greater than loopEnd.
568 mPosLoop.mLoopCount = 0;
569 }
Andy Hung9b461582014-12-01 17:56:29 -0800570 (void) mMutator.push(mState);
571}
572
573void StaticAudioTrackClientProxy::setBufferPositionAndLoop(size_t position, size_t loopStart,
574 size_t loopEnd, int loopCount)
575{
576 setLoop(loopStart, loopEnd, loopCount);
577 setBufferPosition(position);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800578}
579
580size_t StaticAudioTrackClientProxy::getBufferPosition()
581{
Andy Hung4ede21d2014-12-12 15:37:34 -0800582 getBufferPositionAndLoopCount(NULL, NULL);
583 return mPosLoop.mBufferPosition;
584}
585
586void StaticAudioTrackClientProxy::getBufferPositionAndLoopCount(
587 size_t *position, int *loopCount)
588{
589 if (mMutator.ack() == StaticAudioTrackSingleStateQueue::SSQ_DONE) {
590 if (mPosLoopObserver.poll(mPosLoop)) {
591 ; // a valid mPosLoop should be available if ackDone is true.
592 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800593 }
Andy Hung4ede21d2014-12-12 15:37:34 -0800594 if (position != NULL) {
595 *position = mPosLoop.mBufferPosition;
596 }
597 if (loopCount != NULL) {
598 *loopCount = mPosLoop.mLoopCount;
599 }
Glenn Kastena8190fc2012-12-03 17:06:56 -0800600}
601
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800602// ---------------------------------------------------------------------------
603
604ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
605 size_t frameSize, bool isOut, bool clientInServer)
Glenn Kasten7db7df02013-06-25 16:13:23 -0700606 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer),
Andy Hung3f0c9022016-01-15 17:49:46 -0800607 mAvailToClient(0), mFlush(0), mReleased(0)
Andy Hung6ae58432016-02-16 18:32:24 -0800608 , mTimestampMutator(&cblk->mExtendedTimestampQueue)
Glenn Kastena8190fc2012-12-03 17:06:56 -0800609{
Glenn Kastena8190fc2012-12-03 17:06:56 -0800610}
611
Glenn Kasten2e422c42013-10-18 13:00:29 -0700612status_t ServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800613{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700614 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800615 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700616 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700618 {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800619 audio_track_cblk_t* cblk = mCblk;
620 // compute number of frames available to write (AudioTrack) or read (AudioRecord),
621 // or use previous cached value from framesReady(), with added barrier if it omits.
622 int32_t front;
623 int32_t rear;
624 // See notes on barriers at ClientProxy::obtainBuffer()
625 if (mIsOut) {
626 int32_t flush = cblk->u.mStreaming.mFlush;
627 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100628 front = cblk->u.mStreaming.mFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800629 if (flush != mFlush) {
Glenn Kasten050501d2013-07-11 10:35:38 -0700630 // effectively obtain then release whatever is in the buffer
Andy Hunga2d75cd2015-07-15 17:04:20 -0700631 const size_t overflowBit = mFrameCountP2 << 1;
632 const size_t mask = overflowBit - 1;
Glenn Kasten20f51b12014-10-30 10:43:19 -0700633 int32_t newFront = (front & ~mask) | (flush & mask);
634 ssize_t filled = rear - newFront;
Andy Hunga2d75cd2015-07-15 17:04:20 -0700635 if (filled >= (ssize_t)overflowBit) {
636 // front and rear offsets span the overflow bit of the p2 mask
637 // so rebasing newFront on the front offset is off by the overflow bit.
638 // adjust newFront to match rear offset.
Glenn Kastendbd0f3c2015-07-17 11:04:04 -0700639 ALOGV("flush wrap: filled %zx >= overflowBit %zx", filled, overflowBit);
Andy Hunga2d75cd2015-07-15 17:04:20 -0700640 newFront += overflowBit;
641 filled -= overflowBit;
642 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700643 // Rather than shutting down on a corrupt flush, just treat it as a full flush
644 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -0800645 ALOGE("mFlush %#x -> %#x, front %#x, rear %#x, mask %#x, newFront %#x, "
Lajos Molnarf1063e22015-04-17 15:19:42 -0700646 "filled %zd=%#x",
647 mFlush, flush, front, rear,
648 (unsigned)mask, newFront, filled, (unsigned)filled);
Glenn Kasten20f51b12014-10-30 10:43:19 -0700649 newFront = rear;
650 }
651 mFlush = flush;
652 android_atomic_release_store(newFront, &cblk->u.mStreaming.mFront);
653 // There is no danger from a false positive, so err on the side of caution
654 if (true /*front != newFront*/) {
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100655 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
656 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700657 (void) syscall(__NR_futex, &cblk->mFutex,
658 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100659 }
660 }
Glenn Kasten20f51b12014-10-30 10:43:19 -0700661 front = newFront;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800662 }
663 } else {
664 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront);
665 rear = cblk->u.mStreaming.mRear;
666 }
667 ssize_t filled = rear - front;
668 // pipe should not already be overfull
669 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700670 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800671 mIsShutdown = true;
672 }
673 if (mIsShutdown) {
Glenn Kasten7db7df02013-06-25 16:13:23 -0700674 goto no_init;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800675 }
676 // don't allow filling pipe beyond the nominal size
677 size_t availToServer;
678 if (mIsOut) {
679 availToServer = filled;
680 mAvailToClient = mFrameCount - filled;
681 } else {
682 availToServer = mFrameCount - filled;
683 mAvailToClient = filled;
684 }
685 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk
686 size_t part1;
687 if (mIsOut) {
688 front &= mFrameCountP2 - 1;
689 part1 = mFrameCountP2 - front;
690 } else {
691 rear &= mFrameCountP2 - 1;
692 part1 = mFrameCountP2 - rear;
693 }
694 if (part1 > availToServer) {
695 part1 = availToServer;
696 }
697 size_t ask = buffer->mFrameCount;
698 if (part1 > ask) {
699 part1 = ask;
700 }
701 // is assignment redundant in some cases?
702 buffer->mFrameCount = part1;
703 buffer->mRaw = part1 > 0 ?
704 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL;
705 buffer->mNonContig = availToServer - part1;
Glenn Kasten2e422c42013-10-18 13:00:29 -0700706 // After flush(), allow releaseBuffer() on a previously obtained buffer;
707 // see "Acknowledge any pending flush()" in audioflinger/Tracks.cpp.
708 if (!ackFlush) {
709 mUnreleased = part1;
710 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800711 return part1 > 0 ? NO_ERROR : WOULD_BLOCK;
Glenn Kasten7db7df02013-06-25 16:13:23 -0700712 }
713no_init:
714 buffer->mFrameCount = 0;
715 buffer->mRaw = NULL;
716 buffer->mNonContig = 0;
717 mUnreleased = 0;
718 return NO_INIT;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800719}
720
721void ServerProxy::releaseBuffer(Buffer* buffer)
722{
Glenn Kasten7db7df02013-06-25 16:13:23 -0700723 LOG_ALWAYS_FATAL_IF(buffer == NULL);
724 size_t stepCount = buffer->mFrameCount;
725 if (stepCount == 0 || mIsShutdown) {
726 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800727 buffer->mFrameCount = 0;
728 buffer->mRaw = NULL;
729 buffer->mNonContig = 0;
730 return;
731 }
Glenn Kasten7db7df02013-06-25 16:13:23 -0700732 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800733 mUnreleased -= stepCount;
734 audio_track_cblk_t* cblk = mCblk;
735 if (mIsOut) {
736 int32_t front = cblk->u.mStreaming.mFront;
737 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront);
738 } else {
739 int32_t rear = cblk->u.mStreaming.mRear;
740 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear);
741 }
742
Glenn Kasten844f88c2014-05-09 13:38:09 -0700743 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -0800744 mReleased += stepCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800745
746 size_t half = mFrameCount / 2;
747 if (half == 0) {
748 half = 1;
749 }
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800750 size_t minimum = (size_t) cblk->mMinimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800751 if (minimum == 0) {
752 minimum = mIsOut ? half : 1;
753 } else if (minimum > half) {
754 minimum = half;
755 }
Glenn Kasten93bb77d2013-06-24 12:10:45 -0700756 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time
Glenn Kastence8828a2013-09-16 18:07:38 -0700757 if (!mIsOut || (mAvailToClient + stepCount >= minimum)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700758 ALOGV("mAvailToClient=%zu stepCount=%zu minimum=%zu", mAvailToClient, stepCount, minimum);
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700759 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex);
760 if (!(old & CBLK_FUTEX_WAKE)) {
Elliott Hughesee499292014-05-21 17:55:51 -0700761 (void) syscall(__NR_futex, &cblk->mFutex,
762 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800763 }
764 }
765
766 buffer->mFrameCount = 0;
767 buffer->mRaw = NULL;
768 buffer->mNonContig = 0;
769}
770
771// ---------------------------------------------------------------------------
772
773size_t AudioTrackServerProxy::framesReady()
774{
775 LOG_ALWAYS_FATAL_IF(!mIsOut);
776
777 if (mIsShutdown) {
778 return 0;
779 }
780 audio_track_cblk_t* cblk = mCblk;
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100781
782 int32_t flush = cblk->u.mStreaming.mFlush;
783 if (flush != mFlush) {
Glenn Kasten20f51b12014-10-30 10:43:19 -0700784 // FIXME should return an accurate value, but over-estimate is better than under-estimate
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100785 return mFrameCount;
786 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800787 // the acquire might not be necessary since not doing a subsequent read
788 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear);
789 ssize_t filled = rear - cblk->u.mStreaming.mFront;
790 // pipe should not already be overfull
791 if (!(0 <= filled && (size_t) filled <= mFrameCount)) {
Mark Salyzyn34fb2962014-06-18 16:30:56 -0700792 ALOGE("Shared memory control block is corrupt (filled=%zd); shutting down", filled);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800793 mIsShutdown = true;
794 return 0;
795 }
796 // cache this value for later use by obtainBuffer(), with added barrier
797 // and racy if called by normal mixer thread
798 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer()
799 return filled;
800}
801
Eric Laurentbfb1b832013-01-07 09:53:42 -0800802bool AudioTrackServerProxy::setStreamEndDone() {
Glenn Kasten844f88c2014-05-09 13:38:09 -0700803 audio_track_cblk_t* cblk = mCblk;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800804 bool old =
Glenn Kasten844f88c2014-05-09 13:38:09 -0700805 (android_atomic_or(CBLK_STREAM_END_DONE, &cblk->mFlags) & CBLK_STREAM_END_DONE) != 0;
Eric Laurentbfb1b832013-01-07 09:53:42 -0800806 if (!old) {
Elliott Hughese348c5b2014-05-21 18:47:50 -0700807 (void) syscall(__NR_futex, &cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE,
Elliott Hughesee499292014-05-21 17:55:51 -0700808 1);
Eric Laurentbfb1b832013-01-07 09:53:42 -0800809 }
810 return old;
811}
812
Glenn Kasten82aaf942013-07-17 16:05:07 -0700813void AudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
814{
Glenn Kasten844f88c2014-05-09 13:38:09 -0700815 audio_track_cblk_t* cblk = mCblk;
Phil Burk2812d9e2016-01-04 10:34:30 -0800816 if (frameCount > 0) {
817 cblk->u.mStreaming.mUnderrunFrames += frameCount;
Glenn Kasten82aaf942013-07-17 16:05:07 -0700818
Phil Burk2812d9e2016-01-04 10:34:30 -0800819 if (!mUnderrunning) { // start of underrun?
820 mUnderrunCount++;
821 cblk->u.mStreaming.mUnderrunCount = mUnderrunCount;
822 mUnderrunning = true;
823 ALOGV("tallyUnderrunFrames(%3u) at uf = %u, bump mUnderrunCount = %u",
824 frameCount, cblk->u.mStreaming.mUnderrunFrames, mUnderrunCount);
825 }
826
827 // FIXME also wake futex so that underrun is noticed more quickly
828 (void) android_atomic_or(CBLK_UNDERRUN, &cblk->mFlags);
829 } else {
830 ALOGV_IF(mUnderrunning,
831 "tallyUnderrunFrames(%3u) at uf = %u, underrun finished",
832 frameCount, cblk->u.mStreaming.mUnderrunFrames);
833 mUnderrunning = false; // so we can detect the next edge
834 }
Glenn Kasten82aaf942013-07-17 16:05:07 -0700835}
836
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700837AudioPlaybackRate AudioTrackServerProxy::getPlaybackRate()
Andy Hung8edb8dc2015-03-26 19:13:55 -0700838{ // do not call from multiple threads without holding lock
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700839 mPlaybackRateObserver.poll(mPlaybackRate);
840 return mPlaybackRate;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700841}
842
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800843// ---------------------------------------------------------------------------
844
845StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers,
846 size_t frameCount, size_t frameSize)
847 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize),
Andy Hung4ede21d2014-12-12 15:37:34 -0800848 mObserver(&cblk->u.mStatic.mSingleStateQueue),
849 mPosLoopMutator(&cblk->u.mStatic.mPosLoopQueue),
Andy Hungcb2129b2014-11-11 12:17:22 -0800850 mFramesReadySafe(frameCount), mFramesReady(frameCount),
851 mFramesReadyIsCalledByMultipleThreads(false)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800852{
Andy Hung9b461582014-12-01 17:56:29 -0800853 memset(&mState, 0, sizeof(mState));
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800854}
855
856void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads()
857{
858 mFramesReadyIsCalledByMultipleThreads = true;
859}
860
861size_t StaticAudioTrackServerProxy::framesReady()
862{
Andy Hungcb2129b2014-11-11 12:17:22 -0800863 // Can't call pollPosition() from multiple threads.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800864 if (!mFramesReadyIsCalledByMultipleThreads) {
Andy Hungcb2129b2014-11-11 12:17:22 -0800865 (void) pollPosition();
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800866 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800867 return mFramesReadySafe;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800868}
869
Andy Hung9b461582014-12-01 17:56:29 -0800870status_t StaticAudioTrackServerProxy::updateStateWithLoop(
871 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800872{
Andy Hung9b461582014-12-01 17:56:29 -0800873 if (localState->mLoopSequence != update.mLoopSequence) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800874 bool valid = false;
Andy Hung9b461582014-12-01 17:56:29 -0800875 const size_t loopStart = update.mLoopStart;
876 const size_t loopEnd = update.mLoopEnd;
877 size_t position = localState->mPosition;
878 if (update.mLoopCount == 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800879 valid = true;
Andy Hung9b461582014-12-01 17:56:29 -0800880 } else if (update.mLoopCount >= -1) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800881 if (loopStart < loopEnd && loopEnd <= mFrameCount &&
882 loopEnd - loopStart >= MIN_LOOP) {
Andy Hung680b7952014-11-12 13:18:52 -0800883 // If the current position is greater than the end of the loop
884 // we "wrap" to the loop start. This might cause an audible pop.
885 if (position >= loopEnd) {
Andy Hung9b461582014-12-01 17:56:29 -0800886 position = loopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800887 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800888 valid = true;
889 }
890 }
Andy Hung9b461582014-12-01 17:56:29 -0800891 if (!valid || position > mFrameCount) {
892 return NO_INIT;
893 }
894 localState->mPosition = position;
895 localState->mLoopCount = update.mLoopCount;
896 localState->mLoopEnd = loopEnd;
897 localState->mLoopStart = loopStart;
898 localState->mLoopSequence = update.mLoopSequence;
899 }
900 return OK;
901}
902
903status_t StaticAudioTrackServerProxy::updateStateWithPosition(
904 StaticAudioTrackState *localState, const StaticAudioTrackState &update) const
905{
906 if (localState->mPositionSequence != update.mPositionSequence) {
907 if (update.mPosition > mFrameCount) {
908 return NO_INIT;
909 } else if (localState->mLoopCount != 0 && update.mPosition >= localState->mLoopEnd) {
910 localState->mLoopCount = 0; // disable loop count if position is beyond loop end.
911 }
912 localState->mPosition = update.mPosition;
913 localState->mPositionSequence = update.mPositionSequence;
914 }
915 return OK;
916}
917
918ssize_t StaticAudioTrackServerProxy::pollPosition()
919{
920 StaticAudioTrackState state;
921 if (mObserver.poll(state)) {
922 StaticAudioTrackState trystate = mState;
923 bool result;
Chad Brubakercb50c542015-10-07 14:20:10 -0700924 const int32_t diffSeq = (int32_t) state.mLoopSequence - (int32_t) state.mPositionSequence;
Andy Hung9b461582014-12-01 17:56:29 -0800925
926 if (diffSeq < 0) {
927 result = updateStateWithLoop(&trystate, state) == OK &&
928 updateStateWithPosition(&trystate, state) == OK;
929 } else {
930 result = updateStateWithPosition(&trystate, state) == OK &&
931 updateStateWithLoop(&trystate, state) == OK;
932 }
933 if (!result) {
Andy Hung4ede21d2014-12-12 15:37:34 -0800934 mObserver.done();
Andy Hung9b461582014-12-01 17:56:29 -0800935 // caution: no update occurs so server state will be inconsistent with client state.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800936 ALOGE("%s client pushed an invalid state, shutting down", __func__);
937 mIsShutdown = true;
938 return (ssize_t) NO_INIT;
939 }
Andy Hung9b461582014-12-01 17:56:29 -0800940 mState = trystate;
941 if (mState.mLoopCount == -1) {
942 mFramesReady = INT64_MAX;
943 } else if (mState.mLoopCount == 0) {
944 mFramesReady = mFrameCount - mState.mPosition;
945 } else if (mState.mLoopCount > 0) {
946 // TODO: Later consider fixing overflow, but does not seem needed now
947 // as will not overflow if loopStart and loopEnd are Java "ints".
948 mFramesReady = int64_t(mState.mLoopCount) * (mState.mLoopEnd - mState.mLoopStart)
949 + mFrameCount - mState.mPosition;
950 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800951 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800952 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -0800953 StaticAudioTrackPosLoop posLoop;
954
955 posLoop.mLoopCount = (int32_t) mState.mLoopCount;
956 posLoop.mBufferPosition = (uint32_t) mState.mPosition;
957 mPosLoopMutator.push(posLoop);
958 mObserver.done(); // safe to read mStatic variables.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800959 }
Andy Hung9b461582014-12-01 17:56:29 -0800960 return (ssize_t) mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800961}
962
Andy Hung954ca452015-09-09 14:39:02 -0700963status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer, bool ackFlush)
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800964{
965 if (mIsShutdown) {
966 buffer->mFrameCount = 0;
967 buffer->mRaw = NULL;
968 buffer->mNonContig = 0;
969 mUnreleased = 0;
970 return NO_INIT;
971 }
972 ssize_t positionOrStatus = pollPosition();
973 if (positionOrStatus < 0) {
974 buffer->mFrameCount = 0;
975 buffer->mRaw = NULL;
976 buffer->mNonContig = 0;
977 mUnreleased = 0;
978 return (status_t) positionOrStatus;
979 }
980 size_t position = (size_t) positionOrStatus;
Andy Hungcb2129b2014-11-11 12:17:22 -0800981 size_t end = mState.mLoopCount != 0 ? mState.mLoopEnd : mFrameCount;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800982 size_t avail;
Andy Hungcb2129b2014-11-11 12:17:22 -0800983 if (position < end) {
984 avail = end - position;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800985 size_t wanted = buffer->mFrameCount;
986 if (avail < wanted) {
987 buffer->mFrameCount = avail;
988 } else {
989 avail = wanted;
990 }
991 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize];
992 } else {
993 avail = 0;
994 buffer->mFrameCount = 0;
995 buffer->mRaw = NULL;
996 }
Andy Hungcb2129b2014-11-11 12:17:22 -0800997 // As mFramesReady is the total remaining frames in the static audio track,
998 // it is always larger or equal to avail.
Andy Hung486a7132014-12-22 16:54:21 -0800999 LOG_ALWAYS_FATAL_IF(mFramesReady < (int64_t) avail);
Andy Hungcb2129b2014-11-11 12:17:22 -08001000 buffer->mNonContig = mFramesReady == INT64_MAX ? SIZE_MAX : clampToSize(mFramesReady - avail);
Andy Hung954ca452015-09-09 14:39:02 -07001001 if (!ackFlush) {
1002 mUnreleased = avail;
1003 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001004 return NO_ERROR;
1005}
1006
1007void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer)
1008{
1009 size_t stepCount = buffer->mFrameCount;
Andy Hung486a7132014-12-22 16:54:21 -08001010 LOG_ALWAYS_FATAL_IF(!((int64_t) stepCount <= mFramesReady));
Glenn Kasten7db7df02013-06-25 16:13:23 -07001011 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased));
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001012 if (stepCount == 0) {
Glenn Kasten7db7df02013-06-25 16:13:23 -07001013 // prevent accidental re-use of buffer
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001014 buffer->mRaw = NULL;
1015 buffer->mNonContig = 0;
1016 return;
1017 }
1018 mUnreleased -= stepCount;
1019 audio_track_cblk_t* cblk = mCblk;
Andy Hung9b461582014-12-01 17:56:29 -08001020 size_t position = mState.mPosition;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001021 size_t newPosition = position + stepCount;
1022 int32_t setFlags = 0;
1023 if (!(position <= newPosition && newPosition <= mFrameCount)) {
Glenn Kastenb187de12014-12-30 08:18:15 -08001024 ALOGW("%s newPosition %zu outside [%zu, %zu]", __func__, newPosition, position,
1025 mFrameCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001026 newPosition = mFrameCount;
1027 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) {
Andy Hungcb2129b2014-11-11 12:17:22 -08001028 newPosition = mState.mLoopStart;
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001029 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001030 setFlags = CBLK_LOOP_CYCLE;
1031 } else {
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001032 setFlags = CBLK_LOOP_FINAL;
1033 }
1034 }
1035 if (newPosition == mFrameCount) {
1036 setFlags |= CBLK_BUFFER_END;
1037 }
Andy Hung9b461582014-12-01 17:56:29 -08001038 mState.mPosition = newPosition;
Andy Hungcb2129b2014-11-11 12:17:22 -08001039 if (mFramesReady != INT64_MAX) {
1040 mFramesReady -= stepCount;
1041 }
1042 mFramesReadySafe = clampToSize(mFramesReady);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001043
Glenn Kastenf20e1d82013-07-12 09:45:18 -07001044 cblk->mServer += stepCount;
Andy Hung3f0c9022016-01-15 17:49:46 -08001045 mReleased += stepCount;
1046
Glenn Kastenfdac7c02014-01-28 11:03:28 -08001047 // This may overflow, but client is not supposed to rely on it
Andy Hung4ede21d2014-12-12 15:37:34 -08001048 StaticAudioTrackPosLoop posLoop;
1049 posLoop.mBufferPosition = mState.mPosition;
1050 posLoop.mLoopCount = mState.mLoopCount;
1051 mPosLoopMutator.push(posLoop);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001052 if (setFlags != 0) {
Glenn Kasten96f60d82013-07-12 10:21:18 -07001053 (void) android_atomic_or(setFlags, &cblk->mFlags);
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001054 // this would be a good place to wake a futex
1055 }
1056
1057 buffer->mFrameCount = 0;
1058 buffer->mRaw = NULL;
1059 buffer->mNonContig = 0;
1060}
1061
Phil Burk2812d9e2016-01-04 10:34:30 -08001062void StaticAudioTrackServerProxy::tallyUnderrunFrames(uint32_t frameCount)
Glenn Kasten82aaf942013-07-17 16:05:07 -07001063{
1064 // Unlike AudioTrackServerProxy::tallyUnderrunFrames() used for streaming tracks,
1065 // we don't have a location to count underrun frames. The underrun frame counter
1066 // only exists in AudioTrackSharedStreaming. Fortunately, underruns are not
1067 // possible for static buffer tracks other than at end of buffer, so this is not a loss.
1068
1069 // FIXME also wake futex so that underrun is noticed more quickly
Phil Burk2812d9e2016-01-04 10:34:30 -08001070 if (frameCount > 0) {
1071 (void) android_atomic_or(CBLK_UNDERRUN, &mCblk->mFlags);
1072 }
Glenn Kasten82aaf942013-07-17 16:05:07 -07001073}
1074
Glenn Kasten9f80dd22012-12-18 15:57:32 -08001075// ---------------------------------------------------------------------------
1076
Glenn Kastena8190fc2012-12-03 17:06:56 -08001077} // namespace android