AudioTrackShared.h 32 KB

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