AudioTrackShared.h revision 96f60d8f04432a1ed503b3e24d5736d28c63c9a2
1bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant/* 2bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * Copyright (C) 2007 The Android Open Source Project 3f5256e16dfc425c1d466f6308d4026d529ce9e0bHoward Hinnant * 4bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * Licensed under the Apache License, Version 2.0 (the "License"); 5b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant * you may not use this file except in compliance with the License. 6b64f8b07c104c6cc986570ac8ee0ed16a9f23976Howard Hinnant * You may obtain a copy of the License at 7bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * 8bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * http://www.apache.org/licenses/LICENSE-2.0 9bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * 10bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * Unless required by applicable law or agreed to in writing, software 11bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * distributed under the License is distributed on an "AS IS" BASIS, 12bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * See the License for the specific language governing permissions and 14bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant * limitations under the License. 15bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant */ 16bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant 17bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#ifndef ANDROID_AUDIO_TRACK_SHARED_H 18bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#define ANDROID_AUDIO_TRACK_SHARED_H 19bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant 20bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include <stdint.h> 21bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include <sys/types.h> 22bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant 23bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include <utils/threads.h> 24bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include <utils/Log.h> 25bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include <utils/RefBase.h> 26bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include <media/nbaio/roundup.h> 27bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include <media/SingleStateQueue.h> 28bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#include <private/media/StaticAudioTrackState.h> 29bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant 30bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnantnamespace android { 31bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant 32bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant// ---------------------------------------------------------------------------- 33bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant 34bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant// for audio_track_cblk_t::mFlags 35bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#define CBLK_UNDERRUN 0x01 // set by server immediately on output underrun, cleared by client 36bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#define CBLK_FORCEREADY 0x02 // set: track is considered ready immediately by AudioFlinger, 37bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant // clear: track is ready when buffer full 38bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#define CBLK_INVALID 0x04 // track buffer invalidated by AudioFlinger, need to re-create 39bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant#define CBLK_DISABLED 0x08 // output track disabled by AudioFlinger due to underrun, 40bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant // need to re-start. Unlike CBLK_UNDERRUN, this is not set 41bc8d3f97eb5c958007f2713238472e0c1c8fe02Howard Hinnant // immediately, but only after a long string of underruns. 42// 0x10 unused 43#define CBLK_LOOP_CYCLE 0x20 // set by server each time a loop cycle other than final one completes 44#define CBLK_LOOP_FINAL 0x40 // set by server when the final loop cycle completes 45#define CBLK_BUFFER_END 0x80 // set by server when the position reaches end of buffer if not looping 46#define CBLK_OVERRUN 0x100 // set by server immediately on input overrun, cleared by client 47#define CBLK_INTERRUPT 0x200 // set by client on interrupt(), cleared by client in obtainBuffer() 48#define CBLK_STREAM_END_DONE 0x400 // set by server on render completion, cleared by client 49 50//EL_FIXME 20 seconds may not be enough and must be reconciled with new obtainBuffer implementation 51#define MAX_RUN_OFFLOADED_TIMEOUT_MS 20000 //assuming upto a maximum of 20 seconds of offloaded 52 53struct AudioTrackSharedStreaming { 54 // similar to NBAIO MonoPipe 55 // in continuously incrementing frame units, take modulo buffer size, which must be a power of 2 56 volatile int32_t mFront; // read by server 57 volatile int32_t mRear; // write by client 58 volatile int32_t mFlush; // incremented by client to indicate a request to flush; 59 // server notices and discards all data between mFront and mRear 60 volatile uint32_t mUnderrunFrames; // server increments for each unavailable but desired frame 61}; 62 63typedef SingleStateQueue<StaticAudioTrackState> StaticAudioTrackSingleStateQueue; 64 65struct AudioTrackSharedStatic { 66 StaticAudioTrackSingleStateQueue::Shared 67 mSingleStateQueue; 68 size_t mBufferPosition; // updated asynchronously by server, 69 // "for entertainment purposes only" 70}; 71 72// ---------------------------------------------------------------------------- 73 74// Important: do not add any virtual methods, including ~ 75struct audio_track_cblk_t 76{ 77 // Since the control block is always located in shared memory, this constructor 78 // is only used for placement new(). It is never used for regular new() or stack. 79 audio_track_cblk_t(); 80 /*virtual*/ ~audio_track_cblk_t() { } 81 82 friend class Proxy; 83 friend class ClientProxy; 84 friend class AudioTrackClientProxy; 85 friend class AudioRecordClientProxy; 86 friend class ServerProxy; 87 friend class AudioTrackServerProxy; 88 friend class AudioRecordServerProxy; 89 90 // The data members are grouped so that members accessed frequently and in the same context 91 // are in the same line of data cache. 92 93 uint32_t mServer; // Number of filled frames consumed by server (mIsOut), 94 // or filled frames provided by server (!mIsOut). 95 // It is updated asynchronously by server without a barrier. 96 // The value should be used "for entertainment purposes only", 97 // which means don't make important decisions based on it. 98 99 size_t frameCount_; // used during creation to pass actual track buffer size 100 // from AudioFlinger to client, and not referenced again 101 // FIXME remove here and replace by createTrack() in/out 102 // parameter 103 // renamed to "_" to detect incorrect use 104 105 volatile int32_t mFutex; // event flag: down (P) by client, 106 // up (V) by server or binderDied() or interrupt() 107#define CBLK_FUTEX_WAKE 1 // if event flag bit is set, then a deferred wake is pending 108 109private: 110 111 size_t mMinimum; // server wakes up client if available >= mMinimum 112 113 // Channel volumes are fixed point U4.12, so 0x1000 means 1.0. 114 // Left channel is in [0:15], right channel is in [16:31]. 115 // Always read and write the combined pair atomically. 116 // For AudioTrack only, not used by AudioRecord. 117 uint32_t mVolumeLR; 118 119 uint32_t mSampleRate; // AudioTrack only: client's requested sample rate in Hz 120 // or 0 == default. Write-only client, read-only server. 121 122 // client write-only, server read-only 123 uint16_t mSendLevel; // Fixed point U4.12 so 0x1000 means 1.0 124 125 uint8_t mPad2; // unused 126 127public: 128 // read-only for client, server writes once at initialization and is then read-only 129 uint8_t mName; // normal tracks: track name, fast tracks: track index 130 131 volatile int32_t mFlags; // combinations of CBLK_* 132 133 // Cache line boundary (32 bytes) 134 135public: 136 union { 137 AudioTrackSharedStreaming mStreaming; 138 AudioTrackSharedStatic mStatic; 139 int mAlign[8]; 140 } u; 141 142 // Cache line boundary (32 bytes) 143}; 144 145// ---------------------------------------------------------------------------- 146 147// Proxy for shared memory control block, to isolate callers from needing to know the details. 148// There is exactly one ClientProxy and one ServerProxy per shared memory control block. 149// The proxies are located in normal memory, and are not multi-thread safe within a given side. 150class Proxy : public RefBase { 151protected: 152 Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, bool isOut, 153 bool clientInServer); 154 virtual ~Proxy() { } 155 156public: 157 struct Buffer { 158 size_t mFrameCount; // number of frames available in this buffer 159 void* mRaw; // pointer to first frame 160 size_t mNonContig; // number of additional non-contiguous frames available 161 }; 162 163protected: 164 // These refer to shared memory, and are virtual addresses with respect to the current process. 165 // They may have different virtual addresses within the other process. 166 audio_track_cblk_t* const mCblk; // the control block 167 void* const mBuffers; // starting address of buffers 168 169 const size_t mFrameCount; // not necessarily a power of 2 170 const size_t mFrameSize; // in bytes 171 const size_t mFrameCountP2; // mFrameCount rounded to power of 2, streaming mode 172 const bool mIsOut; // true for AudioTrack, false for AudioRecord 173 const bool mClientInServer; // true for OutputTrack, false for AudioTrack & AudioRecord 174 bool mIsShutdown; // latch set to true when shared memory corruption detected 175 size_t mUnreleased; // unreleased frames remaining from most recent obtainBuffer 176}; 177 178// ---------------------------------------------------------------------------- 179 180// Proxy seen by AudioTrack client and AudioRecord client 181class ClientProxy : public Proxy { 182protected: 183 ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, 184 bool isOut, bool clientInServer); 185 virtual ~ClientProxy() { } 186 187public: 188 static const struct timespec kForever; 189 static const struct timespec kNonBlocking; 190 191 // Obtain a buffer with filled frames (reading) or empty frames (writing). 192 // It is permitted to call obtainBuffer() multiple times in succession, without any intervening 193 // calls to releaseBuffer(). In that case, the final obtainBuffer() is the one that effectively 194 // sets or extends the unreleased frame count. 195 // On entry: 196 // buffer->mFrameCount should be initialized to maximum number of desired frames, 197 // which must be > 0. 198 // buffer->mNonContig is unused. 199 // buffer->mRaw is unused. 200 // requested is the requested timeout in local monotonic delta time units: 201 // NULL or &kNonBlocking means non-blocking (zero timeout). 202 // &kForever means block forever (infinite timeout). 203 // Other values mean a specific timeout in local monotonic delta time units. 204 // elapsed is a pointer to a location that will hold the total local monotonic time that 205 // elapsed while blocked, or NULL if not needed. 206 // On exit: 207 // buffer->mFrameCount has the actual number of contiguous available frames, 208 // which is always 0 when the return status != NO_ERROR. 209 // buffer->mNonContig is the number of additional non-contiguous available frames. 210 // buffer->mRaw is a pointer to the first available frame, 211 // or NULL when buffer->mFrameCount == 0. 212 // The return status is one of: 213 // NO_ERROR Success, buffer->mFrameCount > 0. 214 // WOULD_BLOCK Non-blocking mode and no frames are available. 215 // TIMED_OUT Timeout occurred before any frames became available. 216 // This can happen even for infinite timeout, due to a spurious wakeup. 217 // In this case, the caller should investigate and then re-try as appropriate. 218 // DEAD_OBJECT Server has died or invalidated, caller should destroy this proxy and re-create. 219 // -EINTR Call has been interrupted. Look around to see why, and then perhaps try again. 220 // NO_INIT Shared memory is corrupt. 221 // Assertion failure on entry, if buffer == NULL or buffer->mFrameCount == 0. 222 status_t obtainBuffer(Buffer* buffer, const struct timespec *requested = NULL, 223 struct timespec *elapsed = NULL); 224 225 // Release (some of) the frames last obtained. 226 // On entry, buffer->mFrameCount should have the number of frames to release, 227 // which must (cumulatively) be <= the number of frames last obtained but not yet released. 228 // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer(). 229 // It is permitted to call releaseBuffer() multiple times to release the frames in chunks. 230 // On exit: 231 // buffer->mFrameCount is zero. 232 // buffer->mRaw is NULL. 233 void releaseBuffer(Buffer* buffer); 234 235 // Call after detecting server's death 236 void binderDied(); 237 238 // Call to force an obtainBuffer() to return quickly with -EINTR 239 void interrupt(); 240 241 size_t getPosition() { 242 return mEpoch + mCblk->mServer; 243 } 244 245 void setEpoch(size_t epoch) { 246 mEpoch = epoch; 247 } 248 249 void setMinimum(size_t minimum) { 250 mCblk->mMinimum = minimum; 251 } 252 253 // Return the number of frames that would need to be obtained and released 254 // in order for the client to be aligned at start of buffer 255 virtual size_t getMisalignment(); 256 257 size_t getEpoch() const { 258 return mEpoch; 259 } 260 261private: 262 size_t mEpoch; 263}; 264 265// ---------------------------------------------------------------------------- 266 267// Proxy used by AudioTrack client, which also includes AudioFlinger::PlaybackThread::OutputTrack 268class AudioTrackClientProxy : public ClientProxy { 269public: 270 AudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 271 size_t frameSize, bool clientInServer = false) 272 : ClientProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/, 273 clientInServer) { } 274 virtual ~AudioTrackClientProxy() { } 275 276 // No barriers on the following operations, so the ordering of loads/stores 277 // with respect to other parameters is UNPREDICTABLE. That's considered safe. 278 279 // caller must limit to 0.0 <= sendLevel <= 1.0 280 void setSendLevel(float sendLevel) { 281 mCblk->mSendLevel = uint16_t(sendLevel * 0x1000); 282 } 283 284 // caller must limit to 0 <= volumeLR <= 0x10001000 285 void setVolumeLR(uint32_t volumeLR) { 286 mCblk->mVolumeLR = volumeLR; 287 } 288 289 void setSampleRate(uint32_t sampleRate) { 290 mCblk->mSampleRate = sampleRate; 291 } 292 293 virtual void flush(); 294 295 virtual uint32_t getUnderrunFrames() const { 296 return mCblk->u.mStreaming.mUnderrunFrames; 297 } 298 299 bool clearStreamEndDone(); // and return previous value 300 301 bool getStreamEndDone() const; 302 303 status_t waitStreamEndDone(const struct timespec *requested); 304}; 305 306class StaticAudioTrackClientProxy : public AudioTrackClientProxy { 307public: 308 StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 309 size_t frameSize); 310 virtual ~StaticAudioTrackClientProxy() { } 311 312 virtual void flush(); 313 314#define MIN_LOOP 16 // minimum length of each loop iteration in frames 315 void setLoop(size_t loopStart, size_t loopEnd, int loopCount); 316 size_t getBufferPosition(); 317 318 virtual size_t getMisalignment() { 319 return 0; 320 } 321 322 virtual uint32_t getUnderrunFrames() const { 323 return 0; 324 } 325 326private: 327 StaticAudioTrackSingleStateQueue::Mutator mMutator; 328 size_t mBufferPosition; // so that getBufferPosition() appears to be synchronous 329}; 330 331// ---------------------------------------------------------------------------- 332 333// Proxy used by AudioRecord client 334class AudioRecordClientProxy : public ClientProxy { 335public: 336 AudioRecordClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 337 size_t frameSize) 338 : ClientProxy(cblk, buffers, frameCount, frameSize, 339 false /*isOut*/, false /*clientInServer*/) { } 340 ~AudioRecordClientProxy() { } 341}; 342 343// ---------------------------------------------------------------------------- 344 345// Proxy used by AudioFlinger server 346class ServerProxy : public Proxy { 347protected: 348 ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, 349 bool isOut, bool clientInServer); 350public: 351 virtual ~ServerProxy() { } 352 353 // Obtain a buffer with filled frames (writing) or empty frames (reading). 354 // It is permitted to call obtainBuffer() multiple times in succession, without any intervening 355 // calls to releaseBuffer(). In that case, the final obtainBuffer() is the one that effectively 356 // sets or extends the unreleased frame count. 357 // Always non-blocking. 358 // On entry: 359 // buffer->mFrameCount should be initialized to maximum number of desired frames, 360 // which must be > 0. 361 // buffer->mNonContig is unused. 362 // buffer->mRaw is unused. 363 // On exit: 364 // buffer->mFrameCount has the actual number of contiguous available frames, 365 // which is always 0 when the return status != NO_ERROR. 366 // buffer->mNonContig is the number of additional non-contiguous available frames. 367 // buffer->mRaw is a pointer to the first available frame, 368 // or NULL when buffer->mFrameCount == 0. 369 // The return status is one of: 370 // NO_ERROR Success, buffer->mFrameCount > 0. 371 // WOULD_BLOCK No frames are available. 372 // NO_INIT Shared memory is corrupt. 373 virtual status_t obtainBuffer(Buffer* buffer); 374 375 // Release (some of) the frames last obtained. 376 // On entry, buffer->mFrameCount should have the number of frames to release, 377 // which must (cumulatively) be <= the number of frames last obtained but not yet released. 378 // It is permitted to call releaseBuffer() multiple times to release the frames in chunks. 379 // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer(). 380 // On exit: 381 // buffer->mFrameCount is zero. 382 // buffer->mRaw is NULL. 383 virtual void releaseBuffer(Buffer* buffer); 384 385protected: 386 size_t mAvailToClient; // estimated frames available to client prior to releaseBuffer() 387 int32_t mFlush; // our copy of cblk->u.mStreaming.mFlush, for streaming output only 388private: 389 bool mDeferWake; // whether another releaseBuffer() is expected soon 390}; 391 392// Proxy used by AudioFlinger for servicing AudioTrack 393class AudioTrackServerProxy : public ServerProxy { 394public: 395 AudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 396 size_t frameSize, bool clientInServer = false) 397 : ServerProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/, clientInServer) { } 398protected: 399 virtual ~AudioTrackServerProxy() { } 400 401public: 402 // return value of these methods must be validated by the caller 403 uint32_t getSampleRate() const { return mCblk->mSampleRate; } 404 uint16_t getSendLevel_U4_12() const { return mCblk->mSendLevel; } 405 uint32_t getVolumeLR() const { return mCblk->mVolumeLR; } 406 407 // estimated total number of filled frames available to server to read, 408 // which may include non-contiguous frames 409 virtual size_t framesReady(); 410 411 // Currently AudioFlinger will call framesReady() for a fast track from two threads: 412 // FastMixer thread, and normal mixer thread. This is dangerous, as the proxy is intended 413 // to be called from at most one thread of server, and one thread of client. 414 // As a temporary workaround, this method informs the proxy implementation that it 415 // should avoid doing a state queue poll from within framesReady(). 416 // FIXME Change AudioFlinger to not call framesReady() from normal mixer thread. 417 virtual void framesReadyIsCalledByMultipleThreads() { } 418 419 bool setStreamEndDone(); // and return previous value 420}; 421 422class StaticAudioTrackServerProxy : public AudioTrackServerProxy { 423public: 424 StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 425 size_t frameSize); 426protected: 427 virtual ~StaticAudioTrackServerProxy() { } 428 429public: 430 virtual size_t framesReady(); 431 virtual void framesReadyIsCalledByMultipleThreads(); 432 virtual status_t obtainBuffer(Buffer* buffer); 433 virtual void releaseBuffer(Buffer* buffer); 434 435private: 436 ssize_t pollPosition(); // poll for state queue update, and return current position 437 StaticAudioTrackSingleStateQueue::Observer mObserver; 438 size_t mPosition; // server's current play position in frames, relative to 0 439 size_t mEnd; // cached value computed from mState, safe for asynchronous read 440 bool mFramesReadyIsCalledByMultipleThreads; 441 StaticAudioTrackState mState; 442}; 443 444// Proxy used by AudioFlinger for servicing AudioRecord 445class AudioRecordServerProxy : public ServerProxy { 446public: 447 AudioRecordServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, 448 size_t frameSize) 449 : ServerProxy(cblk, buffers, frameCount, frameSize, false /*isOut*/, 450 false /*clientInServer*/) { } 451protected: 452 virtual ~AudioRecordServerProxy() { } 453}; 454 455// ---------------------------------------------------------------------------- 456 457}; // namespace android 458 459#endif // ANDROID_AUDIO_TRACK_SHARED_H 460