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 #ifndef ANDROID_AUDIO_TRACK_SHARED_H 18 #define ANDROID_AUDIO_TRACK_SHARED_H 19 20 #include <stdint.h> 21 #include <sys/types.h> 22 23 #include <audio_utils/minifloat.h> 24 #include <utils/threads.h> 25 #include <utils/Log.h> 26 #include <utils/RefBase.h> 27 #include <audio_utils/roundup.h> 28 #include <media/AudioResamplerPublic.h> 29 #include <media/AudioTimestamp.h> 30 #include <media/Modulo.h> 31 #include <media/nbaio/SingleStateQueue.h> 32 33 namespace android { 34 35 // ---------------------------------------------------------------------------- 36 37 // for audio_track_cblk_t::mFlags 38 #define CBLK_UNDERRUN 0x01 // set by server immediately on output underrun, cleared by client 39 #define CBLK_FORCEREADY 0x02 // set: track is considered ready immediately by AudioFlinger, 40 // clear: track is ready when buffer full 41 #define CBLK_INVALID 0x04 // track buffer invalidated by AudioFlinger, need to re-create 42 #define CBLK_DISABLED 0x08 // output track disabled by AudioFlinger due to underrun, 43 // need to re-start. Unlike CBLK_UNDERRUN, this is not set 44 // immediately, but only after a long string of underruns. 45 // 0x10 unused 46 #define CBLK_LOOP_CYCLE 0x20 // set by server each time a loop cycle other than final one completes 47 #define CBLK_LOOP_FINAL 0x40 // set by server when the final loop cycle completes 48 #define CBLK_BUFFER_END 0x80 // set by server when the position reaches end of buffer if not looping 49 #define CBLK_OVERRUN 0x100 // set by server immediately on input overrun, cleared by client 50 #define CBLK_INTERRUPT 0x200 // set by client on interrupt(), cleared by client in obtainBuffer() 51 #define CBLK_STREAM_END_DONE 0x400 // set by server on render completion, cleared by client 52 53 //EL_FIXME 20 seconds may not be enough and must be reconciled with new obtainBuffer implementation 54 #define MAX_RUN_OFFLOADED_TIMEOUT_MS 20000 // assuming up to a maximum of 20 seconds of offloaded 55 56 // for audio_track_cblk_t::mState, to match TrackBase.h 57 static inline constexpr int CBLK_STATE_IDLE = 0; 58 static inline constexpr int CBLK_STATE_ACTIVE = 6; 59 static inline constexpr int CBLK_STATE_PAUSING = 7; 60 61 /** 62 * MirroredVariable is a local variable which simultaneously updates 63 * a mirrored storage location. This is useful for server side variables 64 * where a local copy is kept, but a client visible copy is offered through shared memory. 65 * 66 * We use std::atomic as the default container class to access this memory. 67 */ 68 template <typename T, template <typename> class Container = std::atomic> 69 class MirroredVariable { 70 template <typename C> 71 struct Constraints { 72 // If setMirror is used with a different type U != T passed in, 73 // as a general rule, the Container must issue a memcpy to read or write 74 // (or its equivalent) to avoid possible strict aliasing issues. 75 // The memcpy also avoids gaps in structs and alignment issues with different types. 76 static constexpr bool ok_ = false; // Containers must specify constraints. 77 }; 78 template <typename X> 79 struct Constraints<std::atomic<X>> { 80 // Atomics force read and write to memory. 81 static constexpr bool ok = std::is_same_v<X, T> || 82 (std::atomic<X>::is_always_lock_free // no additional locking 83 && sizeof(std::atomic<X>) == sizeof(X) // layout identical to X. 84 && (std::is_arithmetic_v<X> || std::is_enum_v<X>)); // No gaps in the layout. 85 }; 86 87 static_assert(Constraints<Container<T>>::ok); 88 public: 89 explicit MirroredVariable(const T& t) : t_{t} {} 90 91 // implicit conversion operator 92 operator T() const { 93 return t_; 94 } 95 96 MirroredVariable& operator=(const T& t) { 97 t_ = t; 98 if (mirror_ != nullptr) { 99 *mirror_ = t; 100 } 101 return *this; 102 } 103 104 template <typename U> 105 void setMirror(Container<U> *other_mirror) { 106 // Much of the concern is with T != U, however there are additional concerns 107 // when storage uses shared memory between processes. For atomics, it must be 108 // lock free. 109 static_assert(sizeof(U) == sizeof(T)); 110 static_assert(alignof(U) == alignof(T)); 111 static_assert(Constraints<Container<U>>::ok); 112 static_assert(sizeof(Container<U>) == sizeof(Container<T>)); 113 static_assert(alignof(Container<U>) == alignof(Container<T>)); 114 auto mirror = reinterpret_cast<Container<T>*>(other_mirror); 115 if (mirror_ != mirror) { 116 mirror_ = mirror; 117 if (mirror != nullptr) { 118 *mirror = t_; 119 } 120 } 121 } 122 123 void clear() { 124 mirror_ = nullptr; 125 } 126 127 MirroredVariable& operator&() const = delete; 128 129 protected: 130 T t_{}; 131 Container<T>* mirror_ = nullptr; 132 }; 133 134 struct AudioTrackSharedStreaming { 135 // similar to NBAIO MonoPipe 136 // in continuously incrementing frame units, take modulo buffer size, which must be a power of 2 137 volatile int32_t mFront; // read by consumer (output: server, input: client) 138 volatile int32_t mRear; // written by producer (output: client, input: server) 139 volatile int32_t mFlush; // incremented by client to indicate a request to flush; 140 // server notices and discards all data between mFront and mRear 141 volatile int32_t mStop; // set by client to indicate a stop frame position; server 142 // will not read beyond this position until start is called. 143 volatile uint32_t mUnderrunFrames; // server increments for each unavailable but desired frame 144 volatile uint32_t mUnderrunCount; // server increments for each underrun occurrence 145 }; 146 147 // Represents a single state of an AudioTrack that was created in static mode (shared memory buffer 148 // supplied by the client). This state needs to be communicated from the client to server. As this 149 // state is too large to be updated atomically without a mutex, and mutexes aren't allowed here, the 150 // state is wrapped by a SingleStateQueue. 151 struct StaticAudioTrackState { 152 // Do not define constructors, destructors, or virtual methods as this is part of a 153 // union in shared memory and they will not get called properly. 154 155 // These fields should both be size_t, but since they are located in shared memory we 156 // force to 32-bit. The client and server may have different typedefs for size_t. 157 158 // The state has a sequence counter to indicate whether changes are made to loop or position. 159 // The sequence counter also currently indicates whether loop or position is first depending 160 // on which is greater; it jumps by max(mLoopSequence, mPositionSequence) + 1. 161 162 uint32_t mLoopStart; 163 uint32_t mLoopEnd; 164 int32_t mLoopCount; 165 uint32_t mLoopSequence; // a sequence counter to indicate changes to loop 166 uint32_t mPosition; 167 uint32_t mPositionSequence; // a sequence counter to indicate changes to position 168 }; 169 170 typedef SingleStateQueue<StaticAudioTrackState> StaticAudioTrackSingleStateQueue; 171 172 struct StaticAudioTrackPosLoop { 173 // Do not define constructors, destructors, or virtual methods as this is part of a 174 // union in shared memory and will not get called properly. 175 176 // These fields should both be size_t, but since they are located in shared memory we 177 // force to 32-bit. The client and server may have different typedefs for size_t. 178 179 // This struct information is stored in a single state queue to communicate the 180 // static AudioTrack server state to the client while data is consumed. 181 // It is smaller than StaticAudioTrackState to prevent unnecessary information from 182 // being sent. 183 184 uint32_t mBufferPosition; 185 int32_t mLoopCount; 186 }; 187 188 typedef SingleStateQueue<StaticAudioTrackPosLoop> StaticAudioTrackPosLoopQueue; 189 190 struct AudioTrackSharedStatic { 191 // client requests to the server for loop or position changes. 192 StaticAudioTrackSingleStateQueue::Shared 193 mSingleStateQueue; 194 // position info updated asynchronously by server and read by client, 195 // "for entertainment purposes only" 196 StaticAudioTrackPosLoopQueue::Shared 197 mPosLoopQueue; 198 }; 199 200 typedef SingleStateQueue<AudioPlaybackRate> PlaybackRateQueue; 201 202 typedef SingleStateQueue<ExtendedTimestamp> ExtendedTimestampQueue; 203 204 // ---------------------------------------------------------------------------- 205 206 // Important: do not add any virtual methods, including ~ 207 struct audio_track_cblk_t 208 { 209 // Since the control block is always located in shared memory, this constructor 210 // is only used for placement new(). It is never used for regular new() or stack. 211 audio_track_cblk_t(); 212 /*virtual*/ ~audio_track_cblk_t() { } 213 214 friend class Proxy; 215 friend class ClientProxy; 216 friend class AudioTrackClientProxy; 217 friend class AudioRecordClientProxy; 218 friend class ServerProxy; 219 friend class AudioTrackServerProxy; 220 friend class AudioRecordServerProxy; 221 222 // The data members are grouped so that members accessed frequently and in the same context 223 // are in the same line of data cache. 224 225 uint32_t mServer; // Number of filled frames consumed by server (mIsOut), 226 // or filled frames provided by server (!mIsOut). 227 // It is updated asynchronously by server without a barrier. 228 // The value should be used 229 // "for entertainment purposes only", 230 // which means don't make important decisions based on it. 231 232 uint32_t mPad1; // unused 233 234 volatile int32_t mFutex; // event flag: down (P) by client, 235 // up (V) by server or binderDied() or interrupt() 236 #define CBLK_FUTEX_WAKE 1 // if event flag bit is set, then a deferred wake is pending 237 238 private: 239 240 // This field should be a size_t, but since it is located in shared memory we 241 // force to 32-bit. The client and server may have different typedefs for size_t. 242 uint32_t mMinimum; // server wakes up client if available >= mMinimum 243 244 // Stereo gains for AudioTrack only, not used by AudioRecord. 245 gain_minifloat_packed_t mVolumeLR; 246 247 uint32_t mSampleRate; // AudioTrack only: client's requested sample rate in Hz 248 // or 0 == default. Write-only client, read-only server. 249 250 PlaybackRateQueue::Shared mPlaybackRateQueue; 251 252 // client write-only, server read-only 253 uint16_t mSendLevel; // Fixed point U4.12 so 0x1000 means 1.0 254 255 uint16_t mPad2 __attribute__((__unused__)); // unused 256 257 // server write-only, client read 258 ExtendedTimestampQueue::Shared mExtendedTimestampQueue; 259 260 // This is set by AudioTrack.setBufferSizeInFrames(). 261 // A write will not fill the buffer above this limit. 262 volatile uint32_t mBufferSizeInFrames; // effective size of the buffer 263 volatile uint32_t mStartThresholdInFrames; // min frames in buffer to start streaming 264 265 public: 266 267 volatile int32_t mFlags; // combinations of CBLK_* 268 269 std::atomic<int32_t> mState; // current TrackBase state. 270 271 public: 272 union { 273 AudioTrackSharedStreaming mStreaming; 274 AudioTrackSharedStatic mStatic; 275 int mAlign[8]; 276 } u; 277 278 // Cache line boundary (32 bytes) 279 }; 280 281 // TODO: ensure standard layout. 282 // static_assert(std::is_standard_layout_v<audio_track_cblk_t>); 283 284 // ---------------------------------------------------------------------------- 285 286 // Proxy for shared memory control block, to isolate callers from needing to know the details. 287 // There is exactly one ClientProxy and one ServerProxy per shared memory control block. 288 // The proxies are located in normal memory, and are not multi-thread safe within a given side. 289 class Proxy : public RefBase { 290 protected: 291 Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, bool isOut, 292 bool clientInServer); 293 virtual ~Proxy() { } 294 295 public: 296 struct Buffer { 297 size_t mFrameCount; // number of frames available in this buffer 298 void* mRaw; // pointer to first frame 299 size_t mNonContig; // number of additional non-contiguous frames available 300 }; 301 302 size_t frameCount() const { return mFrameCount; } 303 uint32_t getStartThresholdInFrames() const; 304 uint32_t setStartThresholdInFrames(uint32_t startThresholdInFrames); 305 306 protected: 307 // These refer to shared memory, and are virtual addresses with respect to the current process. 308 // They may have different virtual addresses within the other process. 309 audio_track_cblk_t* const mCblk; // the control block 310 void* const mBuffers; // starting address of buffers 311 312 const size_t mFrameCount; // not necessarily a power of 2 313 const size_t mFrameSize; // in bytes 314 const size_t mFrameCountP2; // mFrameCount rounded to power of 2, streaming mode 315 const bool mIsOut; // true for AudioTrack, false for AudioRecord 316 const bool mClientInServer; // true for OutputTrack, false for AudioTrack & AudioRecord 317 bool mIsShutdown; // latch set to true when shared memory corruption detected 318 size_t mUnreleased; // unreleased frames remaining from most recent obtainBuffer 319 }; 320 321 // ---------------------------------------------------------------------------- 322 323 // Proxy seen by AudioTrack client and AudioRecord client 324 class ClientProxy : public Proxy { 325 public: 326 ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, 327 bool isOut, bool clientInServer); 328 virtual ~ClientProxy() { } 329 330 static const struct timespec kForever; 331 static const struct timespec kNonBlocking; 332 333 // Obtain a buffer with filled frames (reading) or empty frames (writing). 334 // It is permitted to call obtainBuffer() multiple times in succession, without any intervening 335 // calls to releaseBuffer(). In that case, the final obtainBuffer() is the one that effectively 336 // sets or extends the unreleased frame count. 337 // On entry: 338 // buffer->mFrameCount should be initialized to maximum number of desired frames, 339 // which must be > 0. 340 // buffer->mNonContig is unused. 341 // buffer->mRaw is unused. 342 // requested is the requested timeout in local monotonic delta time units: 343 // NULL or &kNonBlocking means non-blocking (zero timeout). 344 // &kForever means block forever (infinite timeout). 345 // Other values mean a specific timeout in local monotonic delta time units. 346 // elapsed is a pointer to a location that will hold the total local monotonic time that 347 // elapsed while blocked, or NULL if not needed. 348 // On exit: 349 // buffer->mFrameCount has the actual number of contiguous available frames, 350 // which is always 0 when the return status != NO_ERROR. 351 // buffer->mNonContig is the number of additional non-contiguous available frames. 352 // buffer->mRaw is a pointer to the first available frame, 353 // or NULL when buffer->mFrameCount == 0. 354 // The return status is one of: 355 // NO_ERROR Success, buffer->mFrameCount > 0. 356 // WOULD_BLOCK Non-blocking mode and no frames are available. 357 // TIMED_OUT Timeout occurred before any frames became available. 358 // This can happen even for infinite timeout, due to a spurious wakeup. 359 // In this case, the caller should investigate and then re-try as appropriate. 360 // DEAD_OBJECT Server has died or invalidated, caller should destroy this proxy and re-create. 361 // -EINTR Call has been interrupted. Look around to see why, and then perhaps try again. 362 // NO_INIT Shared memory is corrupt. 363 // NOT_ENOUGH_DATA Server has disabled the track because of underrun: restart the track 364 // if still in active state. 365 // Assertion failure on entry, if buffer == NULL or buffer->mFrameCount == 0. 366 status_t obtainBuffer(Buffer* buffer, const struct timespec *requested = NULL, 367 struct timespec *elapsed = NULL); 368 369 // Release (some of) the frames last obtained. 370 // On entry, buffer->mFrameCount should have the number of frames to release, 371 // which must (cumulatively) be <= the number of frames last obtained but not yet released. 372 // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer(). 373 // It is permitted to call releaseBuffer() multiple times to release the frames in chunks. 374 // On exit: 375 // buffer->mFrameCount is zero. 376 // buffer->mRaw is NULL. 377 void releaseBuffer(Buffer* buffer); 378 379 // Call after detecting server's death 380 void binderDied(); 381 382 // Call to force an obtainBuffer() to return quickly with -EINTR 383 void interrupt(); 384 385 Modulo<uint32_t> getPosition() { 386 return mEpoch + mCblk->mServer; 387 } 388 389 void setEpoch(const Modulo<uint32_t> &epoch) { 390 mEpoch = epoch; 391 } 392 393 void setMinimum(size_t minimum) { 394 // This can only happen on a 64-bit client 395 if (minimum > UINT32_MAX) { 396 minimum = UINT32_MAX; 397 } 398 mCblk->mMinimum = (uint32_t) minimum; 399 } 400 401 // Return the number of frames that would need to be obtained and released 402 // in order for the client to be aligned at start of buffer 403 virtual size_t getMisalignment(); 404 405 Modulo<uint32_t> getEpoch() const { 406 return mEpoch; 407 } 408 409 int32_t getState() const { return mCblk->mState; } 410 uint32_t getBufferSizeInFrames() const { return mBufferSizeInFrames; } 411 // See documentation for AudioTrack::setBufferSizeInFrames() 412 uint32_t setBufferSizeInFrames(uint32_t requestedSize); 413 414 status_t getTimestamp(ExtendedTimestamp *timestamp) { 415 if (timestamp == nullptr) { 416 return BAD_VALUE; 417 } 418 (void) mTimestampObserver.poll(mTimestamp); 419 *timestamp = mTimestamp; 420 return OK; 421 } 422 423 void clearTimestamp() { 424 mTimestamp.clear(); 425 } 426 427 virtual void stop() { }; // called by client in AudioTrack::stop() 428 429 private: 430 // This is a copy of mCblk->mBufferSizeInFrames 431 uint32_t mBufferSizeInFrames; // effective size of the buffer 432 433 Modulo<uint32_t> mEpoch; 434 435 // The shared buffer contents referred to by the timestamp observer 436 // is initialized when the server proxy created. A local zero timestamp 437 // is initialized by the client constructor. 438 ExtendedTimestampQueue::Observer mTimestampObserver; 439 ExtendedTimestamp mTimestamp; // initialized by constructor 440 }; 441 442 // ---------------------------------------------------------------------------- 443 444 // Proxy used by AudioTrack client, which also includes AudioFlinger::PlaybackThread::OutputTrack 445 class AudioTrackClientProxy : public ClientProxy { 446 public: 447 AudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 448 size_t frameSize, bool clientInServer = false) 449 : ClientProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/, 450 clientInServer), 451 mPlaybackRateMutator(&cblk->mPlaybackRateQueue) { 452 } 453 454 virtual ~AudioTrackClientProxy() { } 455 456 // No barriers on the following operations, so the ordering of loads/stores 457 // with respect to other parameters is UNPREDICTABLE. That's considered safe. 458 459 // caller must limit to 0.0 <= sendLevel <= 1.0 460 void setSendLevel(float sendLevel) { 461 mCblk->mSendLevel = uint16_t(sendLevel * 0x1000); 462 } 463 464 // set stereo gains 465 void setVolumeLR(gain_minifloat_packed_t volumeLR) { 466 mCblk->mVolumeLR = volumeLR; 467 } 468 469 void setSampleRate(uint32_t sampleRate) { 470 mCblk->mSampleRate = sampleRate; 471 } 472 473 void setPlaybackRate(const AudioPlaybackRate& playbackRate) { 474 mPlaybackRateMutator.push(playbackRate); 475 } 476 477 // Sends flush and stop position information from the client to the server, 478 // used by streaming AudioTrack flush() or stop(). 479 void sendStreamingFlushStop(bool flush); 480 481 virtual void flush(); 482 483 void stop() override; 484 485 virtual uint32_t getUnderrunFrames() const { 486 return mCblk->u.mStreaming.mUnderrunFrames; 487 } 488 virtual uint32_t getUnderrunCount() const { 489 return mCblk->u.mStreaming.mUnderrunCount; 490 } 491 492 bool clearStreamEndDone(); // and return previous value 493 494 bool getStreamEndDone() const; 495 496 status_t waitStreamEndDone(const struct timespec *requested); 497 498 private: 499 PlaybackRateQueue::Mutator mPlaybackRateMutator; 500 }; 501 502 class StaticAudioTrackClientProxy : public AudioTrackClientProxy { 503 public: 504 StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 505 size_t frameSize); 506 virtual ~StaticAudioTrackClientProxy() { } 507 508 virtual void flush(); 509 510 void stop() override; 511 512 #define MIN_LOOP 16 // minimum length of each loop iteration in frames 513 514 // setLoop(), setBufferPosition(), and setBufferPositionAndLoop() set the 515 // static buffer position and looping parameters. These commands are not 516 // synchronous (they do not wait or block); instead they take effect at the 517 // next buffer data read from the server side. However, the client side 518 // getters will read a cached version of the position and loop variables 519 // until the setting takes effect. 520 // 521 // setBufferPositionAndLoop() is equivalent to calling, in order, setLoop() and 522 // setBufferPosition(). 523 // 524 // The functions should not be relied upon to do parameter or state checking. 525 // That is done at the AudioTrack level. 526 527 void setLoop(size_t loopStart, size_t loopEnd, int loopCount); 528 void setBufferPosition(size_t position); 529 void setBufferPositionAndLoop(size_t position, size_t loopStart, size_t loopEnd, 530 int loopCount); 531 size_t getBufferPosition(); 532 // getBufferPositionAndLoopCount() provides the proper snapshot of 533 // position and loopCount together. 534 void getBufferPositionAndLoopCount(size_t *position, int *loopCount); 535 536 virtual size_t getMisalignment() { 537 return 0; 538 } 539 540 virtual uint32_t getUnderrunFrames() const override { 541 return 0; 542 } 543 544 virtual uint32_t getUnderrunCount() const override { 545 return 0; 546 } 547 548 private: 549 StaticAudioTrackSingleStateQueue::Mutator mMutator; 550 StaticAudioTrackPosLoopQueue::Observer mPosLoopObserver; 551 StaticAudioTrackState mState; // last communicated state to server 552 StaticAudioTrackPosLoop mPosLoop; // snapshot of position and loop. 553 }; 554 555 // ---------------------------------------------------------------------------- 556 557 // Proxy used by AudioRecord client 558 class AudioRecordClientProxy : public ClientProxy { 559 public: 560 AudioRecordClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 561 size_t frameSize) 562 : ClientProxy(cblk, buffers, frameCount, frameSize, 563 false /*isOut*/, false /*clientInServer*/) { } 564 ~AudioRecordClientProxy() { } 565 566 // Advances the client read pointer to the server write head pointer 567 // effectively flushing the client read buffer. The effect is 568 // instantaneous. Returns the number of frames flushed. 569 uint32_t flush() { 570 int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear); 571 int32_t front = mCblk->u.mStreaming.mFront; 572 android_atomic_release_store(rear, &mCblk->u.mStreaming.mFront); 573 return (Modulo<int32_t>(rear) - front).unsignedValue(); 574 } 575 }; 576 577 // ---------------------------------------------------------------------------- 578 579 // Proxy used by AudioFlinger server 580 class ServerProxy : public Proxy { 581 protected: 582 ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, 583 bool isOut, bool clientInServer); 584 public: 585 virtual ~ServerProxy() { } 586 587 // Obtain a buffer with filled frames (writing) or empty frames (reading). 588 // It is permitted to call obtainBuffer() multiple times in succession, without any intervening 589 // calls to releaseBuffer(). In that case, the final obtainBuffer() is the one that effectively 590 // sets or extends the unreleased frame count. 591 // Always non-blocking. 592 // On entry: 593 // buffer->mFrameCount should be initialized to maximum number of desired frames, 594 // which must be > 0. 595 // buffer->mNonContig is unused. 596 // buffer->mRaw is unused. 597 // ackFlush is true iff being called from Track::start to acknowledge a pending flush. 598 // On exit: 599 // buffer->mFrameCount has the actual number of contiguous available frames, 600 // which is always 0 when the return status != NO_ERROR. 601 // buffer->mNonContig is the number of additional non-contiguous available frames. 602 // buffer->mRaw is a pointer to the first available frame, 603 // or NULL when buffer->mFrameCount == 0. 604 // The return status is one of: 605 // NO_ERROR Success, buffer->mFrameCount > 0. 606 // WOULD_BLOCK No frames are available. 607 // NO_INIT Shared memory is corrupt. 608 virtual status_t obtainBuffer(Buffer* buffer, bool ackFlush = false); 609 610 // Release (some of) the frames last obtained. 611 // On entry, buffer->mFrameCount should have the number of frames to release, 612 // which must (cumulatively) be <= the number of frames last obtained but not yet released. 613 // It is permitted to call releaseBuffer() multiple times to release the frames in chunks. 614 // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer(). 615 // On exit: 616 // buffer->mFrameCount is zero. 617 // buffer->mRaw is NULL. 618 virtual void releaseBuffer(Buffer* buffer); 619 620 // Return the total number of frames that AudioFlinger has obtained and released 621 virtual int64_t framesReleased() const { return mReleased; } 622 623 // Expose timestamp to client proxy. Should only be called by a single thread. 624 virtual void setTimestamp(const ExtendedTimestamp ×tamp) { 625 mTimestampMutator.push(timestamp); 626 } 627 628 virtual ExtendedTimestamp getTimestamp() const { 629 return mTimestampMutator.last(); 630 } 631 632 // Flushes the shared ring buffer if the client had requested it using mStreaming.mFlush. 633 // If flush occurs then: 634 // cblk->u.mStreaming.mFront, ServerProxy::mFlush and ServerProxy::mFlushed will be modified 635 // client will be notified via Futex 636 virtual void flushBufferIfNeeded(); 637 638 // Returns the rear position of the AudioTrack shared ring buffer, limited by 639 // the stop frame position level. 640 virtual int32_t getRear() const = 0; 641 642 // Total count of the number of flushed frames since creation (never reset). 643 virtual int64_t framesFlushed() const { return mFlushed; } 644 645 // Safe frames ready query with no side effects. 646 virtual size_t framesReadySafe() const = 0; 647 648 // Get dynamic buffer size from the shared control block. 649 uint32_t getBufferSizeInFrames() const { 650 return android_atomic_acquire_load((int32_t *)&mCblk->mBufferSizeInFrames); 651 } 652 653 protected: 654 size_t mAvailToClient; // estimated frames available to client prior to releaseBuffer() 655 int32_t mFlush; // our copy of cblk->u.mStreaming.mFlush, for streaming output only 656 int64_t mReleased; // our copy of cblk->mServer, at 64 bit resolution 657 int64_t mFlushed; // flushed frames to account for client-server discrepancy 658 ExtendedTimestampQueue::Mutator mTimestampMutator; 659 }; 660 661 // Proxy used by AudioFlinger for servicing AudioTrack 662 class AudioTrackServerProxy : public ServerProxy { 663 public: 664 AudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 665 size_t frameSize, bool clientInServer, uint32_t sampleRate) 666 : ServerProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/, clientInServer), 667 mPlaybackRateObserver(&cblk->mPlaybackRateQueue), 668 mUnderrunCount(0), mUnderrunning(false), mDrained(true) { 669 mCblk->mSampleRate = sampleRate; 670 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT; 671 } 672 protected: 673 virtual ~AudioTrackServerProxy() { } 674 675 public: 676 // return value of these methods must be validated by the caller 677 uint32_t getSampleRate() const { return mCblk->mSampleRate; } 678 uint16_t getSendLevel_U4_12() const { return mCblk->mSendLevel; } 679 gain_minifloat_packed_t getVolumeLR() const { return mCblk->mVolumeLR; } 680 681 // estimated total number of filled frames available to server to read, 682 // which may include non-contiguous frames 683 virtual size_t framesReady(); 684 685 size_t framesReadySafe() const override; // frames available to read by server. 686 687 // Currently AudioFlinger will call framesReady() for a fast track from two threads: 688 // FastMixer thread, and normal mixer thread. This is dangerous, as the proxy is intended 689 // to be called from at most one thread of server, and one thread of client. 690 // As a temporary workaround, this method informs the proxy implementation that it 691 // should avoid doing a state queue poll from within framesReady(). 692 // FIXME Change AudioFlinger to not call framesReady() from normal mixer thread. 693 virtual void framesReadyIsCalledByMultipleThreads() { } 694 695 bool setStreamEndDone(); // and return previous value 696 697 // Add to the tally of underrun frames, and inform client of underrun 698 virtual void tallyUnderrunFrames(uint32_t frameCount); 699 700 // Return the total number of frames which AudioFlinger desired but were unavailable, 701 // and thus which resulted in an underrun. 702 virtual uint32_t getUnderrunFrames() const { return mCblk->u.mStreaming.mUnderrunFrames; } 703 704 virtual uint32_t getUnderrunCount() const { return mCblk->u.mStreaming.mUnderrunCount; } 705 706 // Return the playback speed and pitch read atomically. Not multi-thread safe on server side. 707 AudioPlaybackRate getPlaybackRate(); 708 709 // Set the internal drain state of the track buffer from the timestamp received. 710 virtual void setDrained(bool drained) { 711 mDrained.store(drained); 712 } 713 714 // Check if the internal drain state of the track buffer. 715 // This is not a guarantee, but advisory for determining whether the track is 716 // fully played out. 717 virtual bool isDrained() const { 718 return mDrained.load(); 719 } 720 721 int32_t getRear() const override; 722 723 // Called on server side track start(). 724 virtual void start(); 725 726 private: 727 AudioPlaybackRate mPlaybackRate; // last observed playback rate 728 PlaybackRateQueue::Observer mPlaybackRateObserver; 729 730 // Last client stop-at position when start() was called. Used for streaming AudioTracks. 731 std::atomic<int32_t> mStopLast{0}; 732 733 // The server keeps a copy here where it is safe from the client. 734 uint32_t mUnderrunCount; // echoed to mCblk 735 bool mUnderrunning; // used to detect edge of underrun 736 737 std::atomic<bool> mDrained; // is the track buffer drained 738 }; 739 740 class StaticAudioTrackServerProxy : public AudioTrackServerProxy { 741 public: 742 StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 743 size_t frameSize, uint32_t sampleRate); 744 protected: 745 virtual ~StaticAudioTrackServerProxy() { } 746 747 public: 748 virtual size_t framesReady(); 749 virtual size_t framesReadySafe() const override; 750 virtual void framesReadyIsCalledByMultipleThreads(); 751 virtual status_t obtainBuffer(Buffer* buffer, bool ackFlush); 752 virtual void releaseBuffer(Buffer* buffer); 753 virtual void tallyUnderrunFrames(uint32_t frameCount); 754 virtual uint32_t getUnderrunFrames() const { return 0; } 755 756 int32_t getRear() const override; 757 758 void start() override { } // ignore for static tracks 759 760 private: 761 status_t updateStateWithLoop(StaticAudioTrackState *localState, 762 const StaticAudioTrackState &update) const; 763 status_t updateStateWithPosition(StaticAudioTrackState *localState, 764 const StaticAudioTrackState &update) const; 765 ssize_t pollPosition(); // poll for state queue update, and return current position 766 StaticAudioTrackSingleStateQueue::Observer mObserver; 767 StaticAudioTrackPosLoopQueue::Mutator mPosLoopMutator; 768 size_t mFramesReadySafe; // Assuming size_t read/writes are atomic on 32 / 64 bit 769 // processors, this is a thread-safe version of 770 // mFramesReady. 771 int64_t mFramesReady; // The number of frames ready in the static buffer 772 // including loops. This is 64 bits since loop mode 773 // can cause a track to appear to have a large number 774 // of frames. INT64_MAX means an infinite loop. 775 bool mFramesReadyIsCalledByMultipleThreads; 776 StaticAudioTrackState mState; // Server side state. Any updates from client must be 777 // passed by the mObserver SingleStateQueue. 778 }; 779 780 // Proxy used by AudioFlinger for servicing AudioRecord 781 class AudioRecordServerProxy : public ServerProxy { 782 public: 783 AudioRecordServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 784 size_t frameSize, bool clientInServer) 785 : ServerProxy(cblk, buffers, frameCount, frameSize, false /*isOut*/, clientInServer) { } 786 787 int32_t getRear() const override { 788 return mCblk->u.mStreaming.mRear; // For completeness only; mRear written by server. 789 } 790 791 size_t framesReadySafe() const override; // frames available to read by client. 792 793 protected: 794 virtual ~AudioRecordServerProxy() { } 795 }; 796 797 // ---------------------------------------------------------------------------- 798 799 }; // namespace android 800 801 #endif // ANDROID_AUDIO_TRACK_SHARED_H 802