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