AudioTrackShared.cpp revision 96f60d8f04432a1ed503b3e24d5736d28c63c9a2
1/* 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> 22extern "C" { 23#include "../private/bionic_futex.h" 24} 25 26namespace android { 27 28audio_track_cblk_t::audio_track_cblk_t() 29 : mServer(0), frameCount_(0), mFutex(0), mMinimum(0), 30 mVolumeLR(0x10001000), mSampleRate(0), mSendLevel(0), mName(0), mFlags(0) 31{ 32 memset(&u, 0, sizeof(u)); 33} 34 35// --------------------------------------------------------------------------- 36 37Proxy::Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, 38 bool isOut, bool clientInServer) 39 : mCblk(cblk), mBuffers(buffers), mFrameCount(frameCount), mFrameSize(frameSize), 40 mFrameCountP2(roundup(frameCount)), mIsOut(isOut), mClientInServer(clientInServer), 41 mIsShutdown(false), mUnreleased(0) 42{ 43} 44 45// --------------------------------------------------------------------------- 46 47ClientProxy::ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 48 size_t frameSize, bool isOut, bool clientInServer) 49 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer), mEpoch(0) 50{ 51} 52 53const struct timespec ClientProxy::kForever = {INT_MAX /*tv_sec*/, 0 /*tv_nsec*/}; 54const struct timespec ClientProxy::kNonBlocking = {0 /*tv_sec*/, 0 /*tv_nsec*/}; 55 56#define MEASURE_NS 10000000 // attempt to provide accurate timeouts if requested >= MEASURE_NS 57 58// To facilitate quicker recovery from server failure, this value limits the timeout per each futex 59// wait. However it does not protect infinite timeouts. If defined to be zero, there is no limit. 60// FIXME May not be compatible with audio tunneling requirements where timeout should be in the 61// order of minutes. 62#define MAX_SEC 5 63 64status_t ClientProxy::obtainBuffer(Buffer* buffer, const struct timespec *requested, 65 struct timespec *elapsed) 66{ 67 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0); 68 struct timespec total; // total elapsed time spent waiting 69 total.tv_sec = 0; 70 total.tv_nsec = 0; 71 bool measure = elapsed != NULL; // whether to measure total elapsed time spent waiting 72 73 status_t status; 74 enum { 75 TIMEOUT_ZERO, // requested == NULL || *requested == 0 76 TIMEOUT_INFINITE, // *requested == infinity 77 TIMEOUT_FINITE, // 0 < *requested < infinity 78 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE 79 } timeout; 80 if (requested == NULL) { 81 timeout = TIMEOUT_ZERO; 82 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) { 83 timeout = TIMEOUT_ZERO; 84 } else if (requested->tv_sec == INT_MAX) { 85 timeout = TIMEOUT_INFINITE; 86 } else { 87 timeout = TIMEOUT_FINITE; 88 if (requested->tv_sec > 0 || requested->tv_nsec >= MEASURE_NS) { 89 measure = true; 90 } 91 } 92 struct timespec before; 93 bool beforeIsValid = false; 94 audio_track_cblk_t* cblk = mCblk; 95 bool ignoreInitialPendingInterrupt = true; 96 // check for shared memory corruption 97 if (mIsShutdown) { 98 status = NO_INIT; 99 goto end; 100 } 101 for (;;) { 102 int32_t flags = android_atomic_and(~CBLK_INTERRUPT, &cblk->mFlags); 103 // check for track invalidation by server, or server death detection 104 if (flags & CBLK_INVALID) { 105 ALOGV("Track invalidated"); 106 status = DEAD_OBJECT; 107 goto end; 108 } 109 // check for obtainBuffer interrupted by client 110 if (!ignoreInitialPendingInterrupt && (flags & CBLK_INTERRUPT)) { 111 ALOGV("obtainBuffer() interrupted by client"); 112 status = -EINTR; 113 goto end; 114 } 115 ignoreInitialPendingInterrupt = false; 116 // compute number of frames available to write (AudioTrack) or read (AudioRecord) 117 int32_t front; 118 int32_t rear; 119 if (mIsOut) { 120 // The barrier following the read of mFront is probably redundant. 121 // We're about to perform a conditional branch based on 'filled', 122 // which will force the processor to observe the read of mFront 123 // prior to allowing data writes starting at mRaw. 124 // However, the processor may support speculative execution, 125 // and be unable to undo speculative writes into shared memory. 126 // The barrier will prevent such speculative execution. 127 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront); 128 rear = cblk->u.mStreaming.mRear; 129 } else { 130 // On the other hand, this barrier is required. 131 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear); 132 front = cblk->u.mStreaming.mFront; 133 } 134 ssize_t filled = rear - front; 135 // pipe should not be overfull 136 if (!(0 <= filled && (size_t) filled <= mFrameCount)) { 137 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled); 138 mIsShutdown = true; 139 status = NO_INIT; 140 goto end; 141 } 142 // don't allow filling pipe beyond the nominal size 143 size_t avail = mIsOut ? mFrameCount - filled : filled; 144 if (avail > 0) { 145 // 'avail' may be non-contiguous, so return only the first contiguous chunk 146 size_t part1; 147 if (mIsOut) { 148 rear &= mFrameCountP2 - 1; 149 part1 = mFrameCountP2 - rear; 150 } else { 151 front &= mFrameCountP2 - 1; 152 part1 = mFrameCountP2 - front; 153 } 154 if (part1 > avail) { 155 part1 = avail; 156 } 157 if (part1 > buffer->mFrameCount) { 158 part1 = buffer->mFrameCount; 159 } 160 buffer->mFrameCount = part1; 161 buffer->mRaw = part1 > 0 ? 162 &((char *) mBuffers)[(mIsOut ? rear : front) * mFrameSize] : NULL; 163 buffer->mNonContig = avail - part1; 164 mUnreleased = part1; 165 status = NO_ERROR; 166 break; 167 } 168 struct timespec remaining; 169 const struct timespec *ts; 170 switch (timeout) { 171 case TIMEOUT_ZERO: 172 status = WOULD_BLOCK; 173 goto end; 174 case TIMEOUT_INFINITE: 175 ts = NULL; 176 break; 177 case TIMEOUT_FINITE: 178 timeout = TIMEOUT_CONTINUE; 179 if (MAX_SEC == 0) { 180 ts = requested; 181 break; 182 } 183 // fall through 184 case TIMEOUT_CONTINUE: 185 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine 186 if (!measure || requested->tv_sec < total.tv_sec || 187 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) { 188 status = TIMED_OUT; 189 goto end; 190 } 191 remaining.tv_sec = requested->tv_sec - total.tv_sec; 192 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) { 193 remaining.tv_nsec += 1000000000; 194 remaining.tv_sec++; 195 } 196 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) { 197 remaining.tv_sec = MAX_SEC; 198 remaining.tv_nsec = 0; 199 } 200 ts = &remaining; 201 break; 202 default: 203 LOG_FATAL("obtainBuffer() timeout=%d", timeout); 204 ts = NULL; 205 break; 206 } 207 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex); 208 if (!(old & CBLK_FUTEX_WAKE)) { 209 int rc; 210 if (measure && !beforeIsValid) { 211 clock_gettime(CLOCK_MONOTONIC, &before); 212 beforeIsValid = true; 213 } 214 int ret = __futex_syscall4(&cblk->mFutex, 215 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts); 216 // update total elapsed time spent waiting 217 if (measure) { 218 struct timespec after; 219 clock_gettime(CLOCK_MONOTONIC, &after); 220 total.tv_sec += after.tv_sec - before.tv_sec; 221 long deltaNs = after.tv_nsec - before.tv_nsec; 222 if (deltaNs < 0) { 223 deltaNs += 1000000000; 224 total.tv_sec--; 225 } 226 if ((total.tv_nsec += deltaNs) >= 1000000000) { 227 total.tv_nsec -= 1000000000; 228 total.tv_sec++; 229 } 230 before = after; 231 beforeIsValid = true; 232 } 233 switch (ret) { 234 case 0: // normal wakeup by server, or by binderDied() 235 case -EWOULDBLOCK: // benign race condition with server 236 case -EINTR: // wait was interrupted by signal or other spurious wakeup 237 case -ETIMEDOUT: // time-out expired 238 // FIXME these error/non-0 status are being dropped 239 break; 240 default: 241 ALOGE("%s unexpected error %d", __func__, ret); 242 status = -ret; 243 goto end; 244 } 245 } 246 } 247 248end: 249 if (status != NO_ERROR) { 250 buffer->mFrameCount = 0; 251 buffer->mRaw = NULL; 252 buffer->mNonContig = 0; 253 mUnreleased = 0; 254 } 255 if (elapsed != NULL) { 256 *elapsed = total; 257 } 258 if (requested == NULL) { 259 requested = &kNonBlocking; 260 } 261 if (measure) { 262 ALOGV("requested %ld.%03ld elapsed %ld.%03ld", 263 requested->tv_sec, requested->tv_nsec / 1000000, 264 total.tv_sec, total.tv_nsec / 1000000); 265 } 266 return status; 267} 268 269void ClientProxy::releaseBuffer(Buffer* buffer) 270{ 271 LOG_ALWAYS_FATAL_IF(buffer == NULL); 272 size_t stepCount = buffer->mFrameCount; 273 if (stepCount == 0 || mIsShutdown) { 274 // prevent accidental re-use of buffer 275 buffer->mFrameCount = 0; 276 buffer->mRaw = NULL; 277 buffer->mNonContig = 0; 278 return; 279 } 280 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount)); 281 mUnreleased -= stepCount; 282 audio_track_cblk_t* cblk = mCblk; 283 // Both of these barriers are required 284 if (mIsOut) { 285 int32_t rear = cblk->u.mStreaming.mRear; 286 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear); 287 } else { 288 int32_t front = cblk->u.mStreaming.mFront; 289 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront); 290 } 291} 292 293void ClientProxy::binderDied() 294{ 295 audio_track_cblk_t* cblk = mCblk; 296 if (!(android_atomic_or(CBLK_INVALID, &cblk->mFlags) & CBLK_INVALID)) { 297 // it seems that a FUTEX_WAKE_PRIVATE will not wake a FUTEX_WAIT, even within same process 298 (void) __futex_syscall3(&cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 299 1); 300 } 301} 302 303void ClientProxy::interrupt() 304{ 305 audio_track_cblk_t* cblk = mCblk; 306 if (!(android_atomic_or(CBLK_INTERRUPT, &cblk->mFlags) & CBLK_INTERRUPT)) { 307 (void) __futex_syscall3(&cblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 308 1); 309 } 310} 311 312size_t ClientProxy::getMisalignment() 313{ 314 audio_track_cblk_t* cblk = mCblk; 315 return (mFrameCountP2 - (mIsOut ? cblk->u.mStreaming.mRear : cblk->u.mStreaming.mFront)) & 316 (mFrameCountP2 - 1); 317} 318 319// --------------------------------------------------------------------------- 320 321void AudioTrackClientProxy::flush() 322{ 323 mCblk->u.mStreaming.mFlush++; 324} 325 326bool AudioTrackClientProxy::clearStreamEndDone() { 327 return (android_atomic_and(~CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0; 328} 329 330bool AudioTrackClientProxy::getStreamEndDone() const { 331 return (mCblk->mFlags & CBLK_STREAM_END_DONE) != 0; 332} 333 334status_t AudioTrackClientProxy::waitStreamEndDone(const struct timespec *requested) 335{ 336 struct timespec total; // total elapsed time spent waiting 337 total.tv_sec = 0; 338 total.tv_nsec = 0; 339 audio_track_cblk_t* cblk = mCblk; 340 status_t status; 341 enum { 342 TIMEOUT_ZERO, // requested == NULL || *requested == 0 343 TIMEOUT_INFINITE, // *requested == infinity 344 TIMEOUT_FINITE, // 0 < *requested < infinity 345 TIMEOUT_CONTINUE, // additional chances after TIMEOUT_FINITE 346 } timeout; 347 if (requested == NULL) { 348 timeout = TIMEOUT_ZERO; 349 } else if (requested->tv_sec == 0 && requested->tv_nsec == 0) { 350 timeout = TIMEOUT_ZERO; 351 } else if (requested->tv_sec == INT_MAX) { 352 timeout = TIMEOUT_INFINITE; 353 } else { 354 timeout = TIMEOUT_FINITE; 355 } 356 for (;;) { 357 int32_t flags = android_atomic_and(~(CBLK_INTERRUPT|CBLK_STREAM_END_DONE), &cblk->mFlags); 358 // check for track invalidation by server, or server death detection 359 if (flags & CBLK_INVALID) { 360 ALOGV("Track invalidated"); 361 status = DEAD_OBJECT; 362 goto end; 363 } 364 if (flags & CBLK_STREAM_END_DONE) { 365 ALOGV("stream end received"); 366 status = NO_ERROR; 367 goto end; 368 } 369 // check for obtainBuffer interrupted by client 370 // check for obtainBuffer interrupted by client 371 if (flags & CBLK_INTERRUPT) { 372 ALOGV("waitStreamEndDone() interrupted by client"); 373 status = -EINTR; 374 goto end; 375 } 376 struct timespec remaining; 377 const struct timespec *ts; 378 switch (timeout) { 379 case TIMEOUT_ZERO: 380 status = WOULD_BLOCK; 381 goto end; 382 case TIMEOUT_INFINITE: 383 ts = NULL; 384 break; 385 case TIMEOUT_FINITE: 386 timeout = TIMEOUT_CONTINUE; 387 if (MAX_SEC == 0) { 388 ts = requested; 389 break; 390 } 391 // fall through 392 case TIMEOUT_CONTINUE: 393 // FIXME we do not retry if requested < 10ms? needs documentation on this state machine 394 if (requested->tv_sec < total.tv_sec || 395 (requested->tv_sec == total.tv_sec && requested->tv_nsec <= total.tv_nsec)) { 396 status = TIMED_OUT; 397 goto end; 398 } 399 remaining.tv_sec = requested->tv_sec - total.tv_sec; 400 if ((remaining.tv_nsec = requested->tv_nsec - total.tv_nsec) < 0) { 401 remaining.tv_nsec += 1000000000; 402 remaining.tv_sec++; 403 } 404 if (0 < MAX_SEC && MAX_SEC < remaining.tv_sec) { 405 remaining.tv_sec = MAX_SEC; 406 remaining.tv_nsec = 0; 407 } 408 ts = &remaining; 409 break; 410 default: 411 LOG_FATAL("waitStreamEndDone() timeout=%d", timeout); 412 ts = NULL; 413 break; 414 } 415 int32_t old = android_atomic_and(~CBLK_FUTEX_WAKE, &cblk->mFutex); 416 if (!(old & CBLK_FUTEX_WAKE)) { 417 int rc; 418 int ret = __futex_syscall4(&cblk->mFutex, 419 mClientInServer ? FUTEX_WAIT_PRIVATE : FUTEX_WAIT, old & ~CBLK_FUTEX_WAKE, ts); 420 switch (ret) { 421 case 0: // normal wakeup by server, or by binderDied() 422 case -EWOULDBLOCK: // benign race condition with server 423 case -EINTR: // wait was interrupted by signal or other spurious wakeup 424 case -ETIMEDOUT: // time-out expired 425 break; 426 default: 427 ALOGE("%s unexpected error %d", __func__, ret); 428 status = -ret; 429 goto end; 430 } 431 } 432 } 433 434end: 435 if (requested == NULL) { 436 requested = &kNonBlocking; 437 } 438 return status; 439} 440 441// --------------------------------------------------------------------------- 442 443StaticAudioTrackClientProxy::StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, 444 size_t frameCount, size_t frameSize) 445 : AudioTrackClientProxy(cblk, buffers, frameCount, frameSize), 446 mMutator(&cblk->u.mStatic.mSingleStateQueue), mBufferPosition(0) 447{ 448} 449 450void StaticAudioTrackClientProxy::flush() 451{ 452 LOG_FATAL("static flush"); 453} 454 455void StaticAudioTrackClientProxy::setLoop(size_t loopStart, size_t loopEnd, int loopCount) 456{ 457 StaticAudioTrackState newState; 458 newState.mLoopStart = loopStart; 459 newState.mLoopEnd = loopEnd; 460 newState.mLoopCount = loopCount; 461 mBufferPosition = loopStart; 462 (void) mMutator.push(newState); 463} 464 465size_t StaticAudioTrackClientProxy::getBufferPosition() 466{ 467 size_t bufferPosition; 468 if (mMutator.ack()) { 469 bufferPosition = mCblk->u.mStatic.mBufferPosition; 470 if (bufferPosition > mFrameCount) { 471 bufferPosition = mFrameCount; 472 } 473 } else { 474 bufferPosition = mBufferPosition; 475 } 476 return bufferPosition; 477} 478 479// --------------------------------------------------------------------------- 480 481ServerProxy::ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 482 size_t frameSize, bool isOut, bool clientInServer) 483 : Proxy(cblk, buffers, frameCount, frameSize, isOut, clientInServer), 484 mAvailToClient(0), mFlush(0), mDeferWake(false) 485{ 486} 487 488status_t ServerProxy::obtainBuffer(Buffer* buffer) 489{ 490 LOG_ALWAYS_FATAL_IF(buffer == NULL || buffer->mFrameCount == 0); 491 if (mIsShutdown) { 492 goto no_init; 493 } 494 { 495 audio_track_cblk_t* cblk = mCblk; 496 // compute number of frames available to write (AudioTrack) or read (AudioRecord), 497 // or use previous cached value from framesReady(), with added barrier if it omits. 498 int32_t front; 499 int32_t rear; 500 // See notes on barriers at ClientProxy::obtainBuffer() 501 if (mIsOut) { 502 int32_t flush = cblk->u.mStreaming.mFlush; 503 rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear); 504 front = cblk->u.mStreaming.mFront; 505 if (flush != mFlush) { 506 mFlush = flush; 507 // effectively obtain then release whatever is in the buffer 508 android_atomic_release_store(rear, &cblk->u.mStreaming.mFront); 509 if (front != rear) { 510 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex); 511 if (!(old & CBLK_FUTEX_WAKE)) { 512 (void) __futex_syscall3(&cblk->mFutex, 513 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1); 514 } 515 } 516 front = rear; 517 } 518 } else { 519 front = android_atomic_acquire_load(&cblk->u.mStreaming.mFront); 520 rear = cblk->u.mStreaming.mRear; 521 } 522 ssize_t filled = rear - front; 523 // pipe should not already be overfull 524 if (!(0 <= filled && (size_t) filled <= mFrameCount)) { 525 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled); 526 mIsShutdown = true; 527 } 528 if (mIsShutdown) { 529 goto no_init; 530 } 531 // don't allow filling pipe beyond the nominal size 532 size_t availToServer; 533 if (mIsOut) { 534 availToServer = filled; 535 mAvailToClient = mFrameCount - filled; 536 } else { 537 availToServer = mFrameCount - filled; 538 mAvailToClient = filled; 539 } 540 // 'availToServer' may be non-contiguous, so return only the first contiguous chunk 541 size_t part1; 542 if (mIsOut) { 543 front &= mFrameCountP2 - 1; 544 part1 = mFrameCountP2 - front; 545 } else { 546 rear &= mFrameCountP2 - 1; 547 part1 = mFrameCountP2 - rear; 548 } 549 if (part1 > availToServer) { 550 part1 = availToServer; 551 } 552 size_t ask = buffer->mFrameCount; 553 if (part1 > ask) { 554 part1 = ask; 555 } 556 // is assignment redundant in some cases? 557 buffer->mFrameCount = part1; 558 buffer->mRaw = part1 > 0 ? 559 &((char *) mBuffers)[(mIsOut ? front : rear) * mFrameSize] : NULL; 560 buffer->mNonContig = availToServer - part1; 561 mUnreleased = part1; 562 // optimization to avoid waking up the client too early 563 // FIXME need to test for recording 564 mDeferWake = part1 < ask && availToServer >= ask; 565 return part1 > 0 ? NO_ERROR : WOULD_BLOCK; 566 } 567no_init: 568 buffer->mFrameCount = 0; 569 buffer->mRaw = NULL; 570 buffer->mNonContig = 0; 571 mUnreleased = 0; 572 return NO_INIT; 573} 574 575void ServerProxy::releaseBuffer(Buffer* buffer) 576{ 577 LOG_ALWAYS_FATAL_IF(buffer == NULL); 578 size_t stepCount = buffer->mFrameCount; 579 if (stepCount == 0 || mIsShutdown) { 580 // prevent accidental re-use of buffer 581 buffer->mFrameCount = 0; 582 buffer->mRaw = NULL; 583 buffer->mNonContig = 0; 584 return; 585 } 586 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased && mUnreleased <= mFrameCount)); 587 mUnreleased -= stepCount; 588 audio_track_cblk_t* cblk = mCblk; 589 if (mIsOut) { 590 int32_t front = cblk->u.mStreaming.mFront; 591 android_atomic_release_store(stepCount + front, &cblk->u.mStreaming.mFront); 592 } else { 593 int32_t rear = cblk->u.mStreaming.mRear; 594 android_atomic_release_store(stepCount + rear, &cblk->u.mStreaming.mRear); 595 } 596 597 mCblk->mServer += stepCount; 598 599 size_t half = mFrameCount / 2; 600 if (half == 0) { 601 half = 1; 602 } 603 size_t minimum = cblk->mMinimum; 604 if (minimum == 0) { 605 minimum = mIsOut ? half : 1; 606 } else if (minimum > half) { 607 minimum = half; 608 } 609 // FIXME AudioRecord wakeup needs to be optimized; it currently wakes up client every time 610 if (!mIsOut || (!mDeferWake && mAvailToClient + stepCount >= minimum)) { 611 ALOGV("mAvailToClient=%u stepCount=%u minimum=%u", mAvailToClient, stepCount, minimum); 612 int32_t old = android_atomic_or(CBLK_FUTEX_WAKE, &cblk->mFutex); 613 if (!(old & CBLK_FUTEX_WAKE)) { 614 (void) __futex_syscall3(&cblk->mFutex, 615 mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 1); 616 } 617 } 618 619 buffer->mFrameCount = 0; 620 buffer->mRaw = NULL; 621 buffer->mNonContig = 0; 622} 623 624// --------------------------------------------------------------------------- 625 626size_t AudioTrackServerProxy::framesReady() 627{ 628 LOG_ALWAYS_FATAL_IF(!mIsOut); 629 630 if (mIsShutdown) { 631 return 0; 632 } 633 audio_track_cblk_t* cblk = mCblk; 634 635 int32_t flush = cblk->u.mStreaming.mFlush; 636 if (flush != mFlush) { 637 return mFrameCount; 638 } 639 // the acquire might not be necessary since not doing a subsequent read 640 int32_t rear = android_atomic_acquire_load(&cblk->u.mStreaming.mRear); 641 ssize_t filled = rear - cblk->u.mStreaming.mFront; 642 // pipe should not already be overfull 643 if (!(0 <= filled && (size_t) filled <= mFrameCount)) { 644 ALOGE("Shared memory control block is corrupt (filled=%d); shutting down", filled); 645 mIsShutdown = true; 646 return 0; 647 } 648 // cache this value for later use by obtainBuffer(), with added barrier 649 // and racy if called by normal mixer thread 650 // ignores flush(), so framesReady() may report a larger mFrameCount than obtainBuffer() 651 return filled; 652} 653 654bool AudioTrackServerProxy::setStreamEndDone() { 655 bool old = 656 (android_atomic_or(CBLK_STREAM_END_DONE, &mCblk->mFlags) & CBLK_STREAM_END_DONE) != 0; 657 if (!old) { 658 (void) __futex_syscall3(&mCblk->mFutex, mClientInServer ? FUTEX_WAKE_PRIVATE : FUTEX_WAKE, 659 1); 660 } 661 return old; 662} 663 664// --------------------------------------------------------------------------- 665 666StaticAudioTrackServerProxy::StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, 667 size_t frameCount, size_t frameSize) 668 : AudioTrackServerProxy(cblk, buffers, frameCount, frameSize), 669 mObserver(&cblk->u.mStatic.mSingleStateQueue), mPosition(0), 670 mEnd(frameCount), mFramesReadyIsCalledByMultipleThreads(false) 671{ 672 mState.mLoopStart = 0; 673 mState.mLoopEnd = 0; 674 mState.mLoopCount = 0; 675} 676 677void StaticAudioTrackServerProxy::framesReadyIsCalledByMultipleThreads() 678{ 679 mFramesReadyIsCalledByMultipleThreads = true; 680} 681 682size_t StaticAudioTrackServerProxy::framesReady() 683{ 684 // FIXME 685 // This is racy if called by normal mixer thread, 686 // as we're reading 2 independent variables without a lock. 687 // Can't call mObserver.poll(), as we might be called from wrong thread. 688 // If looping is enabled, should return a higher number (since includes non-contiguous). 689 size_t position = mPosition; 690 if (!mFramesReadyIsCalledByMultipleThreads) { 691 ssize_t positionOrStatus = pollPosition(); 692 if (positionOrStatus >= 0) { 693 position = (size_t) positionOrStatus; 694 } 695 } 696 size_t end = mEnd; 697 return position < end ? end - position : 0; 698} 699 700ssize_t StaticAudioTrackServerProxy::pollPosition() 701{ 702 size_t position = mPosition; 703 StaticAudioTrackState state; 704 if (mObserver.poll(state)) { 705 bool valid = false; 706 size_t loopStart = state.mLoopStart; 707 size_t loopEnd = state.mLoopEnd; 708 if (state.mLoopCount == 0) { 709 if (loopStart > mFrameCount) { 710 loopStart = mFrameCount; 711 } 712 // ignore loopEnd 713 mPosition = position = loopStart; 714 mEnd = mFrameCount; 715 mState.mLoopCount = 0; 716 valid = true; 717 } else { 718 if (loopStart < loopEnd && loopEnd <= mFrameCount && 719 loopEnd - loopStart >= MIN_LOOP) { 720 if (!(loopStart <= position && position < loopEnd)) { 721 mPosition = position = loopStart; 722 } 723 mEnd = loopEnd; 724 mState = state; 725 valid = true; 726 } 727 } 728 if (!valid) { 729 ALOGE("%s client pushed an invalid state, shutting down", __func__); 730 mIsShutdown = true; 731 return (ssize_t) NO_INIT; 732 } 733 mCblk->u.mStatic.mBufferPosition = position; 734 } 735 return (ssize_t) position; 736} 737 738status_t StaticAudioTrackServerProxy::obtainBuffer(Buffer* buffer) 739{ 740 if (mIsShutdown) { 741 buffer->mFrameCount = 0; 742 buffer->mRaw = NULL; 743 buffer->mNonContig = 0; 744 mUnreleased = 0; 745 return NO_INIT; 746 } 747 ssize_t positionOrStatus = pollPosition(); 748 if (positionOrStatus < 0) { 749 buffer->mFrameCount = 0; 750 buffer->mRaw = NULL; 751 buffer->mNonContig = 0; 752 mUnreleased = 0; 753 return (status_t) positionOrStatus; 754 } 755 size_t position = (size_t) positionOrStatus; 756 size_t avail; 757 if (position < mEnd) { 758 avail = mEnd - position; 759 size_t wanted = buffer->mFrameCount; 760 if (avail < wanted) { 761 buffer->mFrameCount = avail; 762 } else { 763 avail = wanted; 764 } 765 buffer->mRaw = &((char *) mBuffers)[position * mFrameSize]; 766 } else { 767 avail = 0; 768 buffer->mFrameCount = 0; 769 buffer->mRaw = NULL; 770 } 771 buffer->mNonContig = 0; // FIXME should be > 0 for looping 772 mUnreleased = avail; 773 return NO_ERROR; 774} 775 776void StaticAudioTrackServerProxy::releaseBuffer(Buffer* buffer) 777{ 778 size_t stepCount = buffer->mFrameCount; 779 LOG_ALWAYS_FATAL_IF(!(stepCount <= mUnreleased)); 780 if (stepCount == 0) { 781 // prevent accidental re-use of buffer 782 buffer->mRaw = NULL; 783 buffer->mNonContig = 0; 784 return; 785 } 786 mUnreleased -= stepCount; 787 audio_track_cblk_t* cblk = mCblk; 788 size_t position = mPosition; 789 size_t newPosition = position + stepCount; 790 int32_t setFlags = 0; 791 if (!(position <= newPosition && newPosition <= mFrameCount)) { 792 ALOGW("%s newPosition %u outside [%u, %u]", __func__, newPosition, position, mFrameCount); 793 newPosition = mFrameCount; 794 } else if (mState.mLoopCount != 0 && newPosition == mState.mLoopEnd) { 795 if (mState.mLoopCount == -1 || --mState.mLoopCount != 0) { 796 newPosition = mState.mLoopStart; 797 setFlags = CBLK_LOOP_CYCLE; 798 } else { 799 mEnd = mFrameCount; // this is what allows playback to continue after the loop 800 setFlags = CBLK_LOOP_FINAL; 801 } 802 } 803 if (newPosition == mFrameCount) { 804 setFlags |= CBLK_BUFFER_END; 805 } 806 mPosition = newPosition; 807 808 cblk->mServer += stepCount; 809 cblk->u.mStatic.mBufferPosition = newPosition; 810 if (setFlags != 0) { 811 (void) android_atomic_or(setFlags, &cblk->mFlags); 812 // this would be a good place to wake a futex 813 } 814 815 buffer->mFrameCount = 0; 816 buffer->mRaw = NULL; 817 buffer->mNonContig = 0; 818} 819 820// --------------------------------------------------------------------------- 821 822} // namespace android 823