blob: cae5560e7925ab8b4324ee712c17a386353fd435 [file] [log] [blame]
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -08001/*
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
Glenn Kastenc56f3422014-03-21 17:53:17 -070023#include <audio_utils/minifloat.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080024#include <utils/threads.h>
Glenn Kastene3aa6592012-12-04 12:22:46 -080025#include <utils/Log.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080026#include <utils/RefBase.h>
Glenn Kasten53dbe772015-01-06 10:46:38 -080027#include <audio_utils/roundup.h>
Andy Hung8edb8dc2015-03-26 19:13:55 -070028#include <media/AudioResamplerPublic.h>
Andy Hung3f0c9022016-01-15 17:49:46 -080029#include <media/AudioTimestamp.h>
Andy Hung90e8a972015-11-09 16:42:40 -080030#include <media/Modulo.h>
Glenn Kasten9f80dd22012-12-18 15:57:32 -080031#include <media/SingleStateQueue.h>
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080032
33namespace android {
34
35// ----------------------------------------------------------------------------
36
Glenn Kasten96f60d82013-07-12 10:21:18 -070037// for audio_track_cblk_t::mFlags
Glenn Kasten9f80dd22012-12-18 15:57:32 -080038#define CBLK_UNDERRUN 0x01 // set by server immediately on output underrun, cleared by client
Glenn Kasten864585d2012-11-06 16:15:41 -080039#define CBLK_FORCEREADY 0x02 // set: track is considered ready immediately by AudioFlinger,
Glenn Kasten9c5fdd82012-11-05 13:38:15 -080040 // clear: track is ready when buffer full
Glenn Kasten864585d2012-11-06 16:15:41 -080041#define CBLK_INVALID 0x04 // track buffer invalidated by AudioFlinger, need to re-create
Glenn Kasten9f80dd22012-12-18 15:57:32 -080042#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()
Richard Fitzgeraldad3af332013-03-25 16:54:37 +000051#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
Glenn Kastene198c362013-08-13 09:13:36 -070054#define MAX_RUN_OFFLOADED_TIMEOUT_MS 20000 // assuming up to a maximum of 20 seconds of offloaded
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -080055
Glenn Kastene3aa6592012-12-04 12:22:46 -080056struct AudioTrackSharedStreaming {
57 // similar to NBAIO MonoPipe
Glenn Kasten9f80dd22012-12-18 15:57:32 -080058 // in continuously incrementing frame units, take modulo buffer size, which must be a power of 2
Glenn Kastenf59497b2015-01-26 16:35:47 -080059 volatile int32_t mFront; // read by consumer (output: server, input: client)
60 volatile int32_t mRear; // written by producer (output: client, input: server)
Glenn Kasten9f80dd22012-12-18 15:57:32 -080061 volatile int32_t mFlush; // incremented by client to indicate a request to flush;
62 // server notices and discards all data between mFront and mRear
Phil Burk2812d9e2016-01-04 10:34:30 -080063 volatile uint32_t mUnderrunFrames; // server increments for each unavailable but desired frame
64 volatile uint32_t mUnderrunCount; // server increments for each underrun occurrence
Glenn Kastene3aa6592012-12-04 12:22:46 -080065};
66
Andy Hung9b461582014-12-01 17:56:29 -080067// Represents a single state of an AudioTrack that was created in static mode (shared memory buffer
68// supplied by the client). This state needs to be communicated from the client to server. As this
69// state is too large to be updated atomically without a mutex, and mutexes aren't allowed here, the
70// state is wrapped by a SingleStateQueue.
71struct StaticAudioTrackState {
72 // Do not define constructors, destructors, or virtual methods as this is part of a
73 // union in shared memory and they will not get called properly.
74
75 // These fields should both be size_t, but since they are located in shared memory we
76 // force to 32-bit. The client and server may have different typedefs for size_t.
77
78 // The state has a sequence counter to indicate whether changes are made to loop or position.
79 // The sequence counter also currently indicates whether loop or position is first depending
80 // on which is greater; it jumps by max(mLoopSequence, mPositionSequence) + 1.
81
82 uint32_t mLoopStart;
83 uint32_t mLoopEnd;
84 int32_t mLoopCount;
85 uint32_t mLoopSequence; // a sequence counter to indicate changes to loop
86 uint32_t mPosition;
87 uint32_t mPositionSequence; // a sequence counter to indicate changes to position
88};
89
Glenn Kasten9f80dd22012-12-18 15:57:32 -080090typedef SingleStateQueue<StaticAudioTrackState> StaticAudioTrackSingleStateQueue;
91
Andy Hung4ede21d2014-12-12 15:37:34 -080092struct StaticAudioTrackPosLoop {
93 // Do not define constructors, destructors, or virtual methods as this is part of a
94 // union in shared memory and will not get called properly.
95
96 // These fields should both be size_t, but since they are located in shared memory we
97 // force to 32-bit. The client and server may have different typedefs for size_t.
98
99 // This struct information is stored in a single state queue to communicate the
100 // static AudioTrack server state to the client while data is consumed.
101 // It is smaller than StaticAudioTrackState to prevent unnecessary information from
102 // being sent.
103
104 uint32_t mBufferPosition;
105 int32_t mLoopCount;
106};
107
108typedef SingleStateQueue<StaticAudioTrackPosLoop> StaticAudioTrackPosLoopQueue;
109
Glenn Kastene3aa6592012-12-04 12:22:46 -0800110struct AudioTrackSharedStatic {
Andy Hung4ede21d2014-12-12 15:37:34 -0800111 // client requests to the server for loop or position changes.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800112 StaticAudioTrackSingleStateQueue::Shared
113 mSingleStateQueue;
Andy Hung4ede21d2014-12-12 15:37:34 -0800114 // position info updated asynchronously by server and read by client,
115 // "for entertainment purposes only"
116 StaticAudioTrackPosLoopQueue::Shared
117 mPosLoopQueue;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800118};
119
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700120typedef SingleStateQueue<AudioPlaybackRate> PlaybackRateQueue;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700121
Andy Hungb3a486f2015-08-04 15:17:58 -0700122
Andy Hung3f0c9022016-01-15 17:49:46 -0800123typedef SingleStateQueue<ExtendedTimestamp> ExtendedTimestampQueue;
124
Andy Hungb3a486f2015-08-04 15:17:58 -0700125typedef SingleStateQueue<AudioTimestamp> TimestampQueue;
126
Glenn Kastene3aa6592012-12-04 12:22:46 -0800127// ----------------------------------------------------------------------------
128
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -0800129// Important: do not add any virtual methods, including ~
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800130struct audio_track_cblk_t
131{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800132 // Since the control block is always located in shared memory, this constructor
133 // is only used for placement new(). It is never used for regular new() or stack.
134 audio_track_cblk_t();
135 /*virtual*/ ~audio_track_cblk_t() { }
136
Glenn Kastene3aa6592012-12-04 12:22:46 -0800137 friend class Proxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800138 friend class ClientProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800139 friend class AudioTrackClientProxy;
140 friend class AudioRecordClientProxy;
141 friend class ServerProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800142 friend class AudioTrackServerProxy;
143 friend class AudioRecordServerProxy;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800144
145 // The data members are grouped so that members accessed frequently and in the same context
146 // are in the same line of data cache.
Glenn Kasten99e53b82012-01-19 08:59:58 -0800147
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700148 uint32_t mServer; // Number of filled frames consumed by server (mIsOut),
149 // or filled frames provided by server (!mIsOut).
150 // It is updated asynchronously by server without a barrier.
Glenn Kastenb187de12014-12-30 08:18:15 -0800151 // The value should be used
152 // "for entertainment purposes only",
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700153 // which means don't make important decisions based on it.
Glenn Kasten22eb4e22012-11-07 14:03:00 -0800154
Glenn Kasten74935e42013-12-19 08:56:45 -0800155 uint32_t mPad1; // unused
Glenn Kasten99e53b82012-01-19 08:59:58 -0800156
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700157 volatile int32_t mFutex; // event flag: down (P) by client,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800158 // up (V) by server or binderDied() or interrupt()
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700159#define CBLK_FUTEX_WAKE 1 // if event flag bit is set, then a deferred wake is pending
Glenn Kasten99e53b82012-01-19 08:59:58 -0800160
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800161private:
162
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800163 // This field should be a size_t, but since it is located in shared memory we
164 // force to 32-bit. The client and server may have different typedefs for size_t.
165 uint32_t mMinimum; // server wakes up client if available >= mMinimum
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800166
Glenn Kastenc56f3422014-03-21 17:53:17 -0700167 // Stereo gains for AudioTrack only, not used by AudioRecord.
168 gain_minifloat_packed_t mVolumeLR;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800169
Glenn Kastene3aa6592012-12-04 12:22:46 -0800170 uint32_t mSampleRate; // AudioTrack only: client's requested sample rate in Hz
171 // or 0 == default. Write-only client, read-only server.
Glenn Kasten99e53b82012-01-19 08:59:58 -0800172
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700173 PlaybackRateQueue::Shared mPlaybackRateQueue;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700174
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800175 // client write-only, server read-only
176 uint16_t mSendLevel; // Fixed point U4.12 so 0x1000 means 1.0
177
Glenn Kastend054c322013-07-12 12:59:20 -0700178 uint16_t mPad2; // unused
Eric Laurentd1b449a2010-05-14 03:26:45 -0700179
Andy Hung3f0c9022016-01-15 17:49:46 -0800180 // server write-only, client read
Andy Hungb3a486f2015-08-04 15:17:58 -0700181 ExtendedTimestampQueue::Shared mExtendedTimestampQueue; // capture
182 TimestampQueue::Shared mTimestampQueue; // playback
183
Glenn Kastene3aa6592012-12-04 12:22:46 -0800184public:
Glenn Kasten99e53b82012-01-19 08:59:58 -0800185
Glenn Kasten96f60d82013-07-12 10:21:18 -0700186 volatile int32_t mFlags; // combinations of CBLK_*
Eric Laurent38ccae22011-03-28 18:37:07 -0700187
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800188public:
Glenn Kastene3aa6592012-12-04 12:22:46 -0800189 union {
190 AudioTrackSharedStreaming mStreaming;
191 AudioTrackSharedStatic mStatic;
192 int mAlign[8];
193 } u;
194
195 // Cache line boundary (32 bytes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800196};
197
Glenn Kastene3aa6592012-12-04 12:22:46 -0800198// ----------------------------------------------------------------------------
199
200// Proxy for shared memory control block, to isolate callers from needing to know the details.
201// There is exactly one ClientProxy and one ServerProxy per shared memory control block.
202// The proxies are located in normal memory, and are not multi-thread safe within a given side.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800203class Proxy : public RefBase {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800204protected:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800205 Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, bool isOut,
206 bool clientInServer);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800207 virtual ~Proxy() { }
208
209public:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800210 struct Buffer {
211 size_t mFrameCount; // number of frames available in this buffer
212 void* mRaw; // pointer to first frame
213 size_t mNonContig; // number of additional non-contiguous frames available
214 };
Glenn Kastene3aa6592012-12-04 12:22:46 -0800215
Phil Burkc0adecb2016-01-08 12:44:11 -0800216 size_t frameCount() const { return mFrameCount; }
217
Glenn Kastene3aa6592012-12-04 12:22:46 -0800218protected:
219 // These refer to shared memory, and are virtual addresses with respect to the current process.
220 // They may have different virtual addresses within the other process.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800221 audio_track_cblk_t* const mCblk; // the control block
222 void* const mBuffers; // starting address of buffers
Glenn Kastene3aa6592012-12-04 12:22:46 -0800223
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800224 const size_t mFrameCount; // not necessarily a power of 2
225 const size_t mFrameSize; // in bytes
226 const size_t mFrameCountP2; // mFrameCount rounded to power of 2, streaming mode
227 const bool mIsOut; // true for AudioTrack, false for AudioRecord
228 const bool mClientInServer; // true for OutputTrack, false for AudioTrack & AudioRecord
229 bool mIsShutdown; // latch set to true when shared memory corruption detected
Glenn Kasten7db7df02013-06-25 16:13:23 -0700230 size_t mUnreleased; // unreleased frames remaining from most recent obtainBuffer
Glenn Kastene3aa6592012-12-04 12:22:46 -0800231};
232
233// ----------------------------------------------------------------------------
234
235// Proxy seen by AudioTrack client and AudioRecord client
236class ClientProxy : public Proxy {
Eric Laurent83b88082014-06-20 18:31:16 -0700237public:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800238 ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
239 bool isOut, bool clientInServer);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800240 virtual ~ClientProxy() { }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800241
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800242 static const struct timespec kForever;
243 static const struct timespec kNonBlocking;
244
245 // Obtain a buffer with filled frames (reading) or empty frames (writing).
246 // It is permitted to call obtainBuffer() multiple times in succession, without any intervening
247 // calls to releaseBuffer(). In that case, the final obtainBuffer() is the one that effectively
248 // sets or extends the unreleased frame count.
249 // On entry:
250 // buffer->mFrameCount should be initialized to maximum number of desired frames,
251 // which must be > 0.
252 // buffer->mNonContig is unused.
253 // buffer->mRaw is unused.
254 // requested is the requested timeout in local monotonic delta time units:
255 // NULL or &kNonBlocking means non-blocking (zero timeout).
256 // &kForever means block forever (infinite timeout).
257 // Other values mean a specific timeout in local monotonic delta time units.
258 // elapsed is a pointer to a location that will hold the total local monotonic time that
259 // elapsed while blocked, or NULL if not needed.
260 // On exit:
261 // buffer->mFrameCount has the actual number of contiguous available frames,
262 // which is always 0 when the return status != NO_ERROR.
263 // buffer->mNonContig is the number of additional non-contiguous available frames.
264 // buffer->mRaw is a pointer to the first available frame,
265 // or NULL when buffer->mFrameCount == 0.
266 // The return status is one of:
267 // NO_ERROR Success, buffer->mFrameCount > 0.
268 // WOULD_BLOCK Non-blocking mode and no frames are available.
269 // TIMED_OUT Timeout occurred before any frames became available.
270 // This can happen even for infinite timeout, due to a spurious wakeup.
271 // In this case, the caller should investigate and then re-try as appropriate.
272 // DEAD_OBJECT Server has died or invalidated, caller should destroy this proxy and re-create.
273 // -EINTR Call has been interrupted. Look around to see why, and then perhaps try again.
274 // NO_INIT Shared memory is corrupt.
Glenn Kasten7db7df02013-06-25 16:13:23 -0700275 // Assertion failure on entry, if buffer == NULL or buffer->mFrameCount == 0.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800276 status_t obtainBuffer(Buffer* buffer, const struct timespec *requested = NULL,
277 struct timespec *elapsed = NULL);
278
279 // Release (some of) the frames last obtained.
280 // On entry, buffer->mFrameCount should have the number of frames to release,
281 // which must (cumulatively) be <= the number of frames last obtained but not yet released.
282 // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer().
283 // It is permitted to call releaseBuffer() multiple times to release the frames in chunks.
284 // On exit:
285 // buffer->mFrameCount is zero.
286 // buffer->mRaw is NULL.
287 void releaseBuffer(Buffer* buffer);
288
289 // Call after detecting server's death
290 void binderDied();
291
292 // Call to force an obtainBuffer() to return quickly with -EINTR
293 void interrupt();
294
Andy Hung90e8a972015-11-09 16:42:40 -0800295 Modulo<uint32_t> getPosition() {
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700296 return mEpoch + mCblk->mServer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800297 }
298
Phil Burkc0adecb2016-01-08 12:44:11 -0800299 void setEpoch(const Modulo<uint32_t> &epoch) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800300 mEpoch = epoch;
301 }
302
303 void setMinimum(size_t minimum) {
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800304 // This can only happen on a 64-bit client
305 if (minimum > UINT32_MAX) {
306 minimum = UINT32_MAX;
307 }
308 mCblk->mMinimum = (uint32_t) minimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800309 }
310
311 // Return the number of frames that would need to be obtained and released
312 // in order for the client to be aligned at start of buffer
313 virtual size_t getMisalignment();
314
Andy Hung90e8a972015-11-09 16:42:40 -0800315 Modulo<uint32_t> getEpoch() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800316 return mEpoch;
317 }
318
Phil Burkc0adecb2016-01-08 12:44:11 -0800319 size_t getBufferSizeInFrames() const { return mBufferSizeInFrames; }
320 // See documentation for AudioTrack.setBufferSizeInFrames()
321 size_t setBufferSizeInFrames(size_t requestedSize);
322
323protected:
324 // This is set by AudioTrack.setBufferSizeInFrames().
325 // A write will not fill the buffer above this limit.
326 size_t mBufferSizeInFrames; // effective size of the buffer
327
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800328private:
Andy Hung90e8a972015-11-09 16:42:40 -0800329 Modulo<uint32_t> mEpoch;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800330};
331
332// ----------------------------------------------------------------------------
333
334// Proxy used by AudioTrack client, which also includes AudioFlinger::PlaybackThread::OutputTrack
335class AudioTrackClientProxy : public ClientProxy {
336public:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800337 AudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
338 size_t frameSize, bool clientInServer = false)
339 : ClientProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/,
Andy Hung8edb8dc2015-03-26 19:13:55 -0700340 clientInServer),
Andy Hungb3a486f2015-08-04 15:17:58 -0700341 mPlaybackRateMutator(&cblk->mPlaybackRateQueue),
342 mTimestampObserver(&cblk->mTimestampQueue) {
343 }
344
Glenn Kastene3aa6592012-12-04 12:22:46 -0800345 virtual ~AudioTrackClientProxy() { }
346
347 // No barriers on the following operations, so the ordering of loads/stores
348 // with respect to other parameters is UNPREDICTABLE. That's considered safe.
349
350 // caller must limit to 0.0 <= sendLevel <= 1.0
351 void setSendLevel(float sendLevel) {
352 mCblk->mSendLevel = uint16_t(sendLevel * 0x1000);
353 }
354
Glenn Kastenc56f3422014-03-21 17:53:17 -0700355 // set stereo gains
356 void setVolumeLR(gain_minifloat_packed_t volumeLR) {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800357 mCblk->mVolumeLR = volumeLR;
358 }
359
360 void setSampleRate(uint32_t sampleRate) {
361 mCblk->mSampleRate = sampleRate;
362 }
363
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700364 void setPlaybackRate(const AudioPlaybackRate& playbackRate) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700365 mPlaybackRateMutator.push(playbackRate);
366 }
367
Andy Hungb3a486f2015-08-04 15:17:58 -0700368 status_t getTimestamp(AudioTimestamp *timestamp) {
369 if (timestamp == nullptr) {
370 return BAD_VALUE;
371 }
372 (void) mTimestampObserver.poll(mTimestamp);
373 // if no data is pushed by server, mTimestamp should be initialized by its constructor
374 // to all zero elements.
375 if (mTimestamp.mTime.tv_sec == 0 && mTimestamp.mTime.tv_nsec == 0) {
376 return WOULD_BLOCK;
377 }
378 *timestamp = mTimestamp;
379 return OK;
380 }
381
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800382 virtual void flush();
383
384 virtual uint32_t getUnderrunFrames() const {
385 return mCblk->u.mStreaming.mUnderrunFrames;
386 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800387 virtual uint32_t getUnderrunCount() const {
388 return mCblk->u.mStreaming.mUnderrunCount;
389 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800390
391 bool clearStreamEndDone(); // and return previous value
392
393 bool getStreamEndDone() const;
394
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100395 status_t waitStreamEndDone(const struct timespec *requested);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700396
397private:
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700398 PlaybackRateQueue::Mutator mPlaybackRateMutator;
Andy Hungb3a486f2015-08-04 15:17:58 -0700399 TimestampQueue::Observer mTimestampObserver;
400 AudioTimestamp mTimestamp;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800401};
402
403class StaticAudioTrackClientProxy : public AudioTrackClientProxy {
404public:
405 StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
406 size_t frameSize);
407 virtual ~StaticAudioTrackClientProxy() { }
408
409 virtual void flush();
410
411#define MIN_LOOP 16 // minimum length of each loop iteration in frames
Andy Hung9b461582014-12-01 17:56:29 -0800412
413 // setLoop(), setBufferPosition(), and setBufferPositionAndLoop() set the
414 // static buffer position and looping parameters. These commands are not
415 // synchronous (they do not wait or block); instead they take effect at the
416 // next buffer data read from the server side. However, the client side
417 // getters will read a cached version of the position and loop variables
418 // until the setting takes effect.
419 //
420 // setBufferPositionAndLoop() is equivalent to calling, in order, setLoop() and
421 // setBufferPosition().
422 //
423 // The functions should not be relied upon to do parameter or state checking.
424 // That is done at the AudioTrack level.
425
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800426 void setLoop(size_t loopStart, size_t loopEnd, int loopCount);
Andy Hung9b461582014-12-01 17:56:29 -0800427 void setBufferPosition(size_t position);
428 void setBufferPositionAndLoop(size_t position, size_t loopStart, size_t loopEnd,
429 int loopCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800430 size_t getBufferPosition();
Andy Hung4ede21d2014-12-12 15:37:34 -0800431 // getBufferPositionAndLoopCount() provides the proper snapshot of
432 // position and loopCount together.
433 void getBufferPositionAndLoopCount(size_t *position, int *loopCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800434
435 virtual size_t getMisalignment() {
436 return 0;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800437 }
438
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800439 virtual uint32_t getUnderrunFrames() const {
440 return 0;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800441 }
442
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800443private:
444 StaticAudioTrackSingleStateQueue::Mutator mMutator;
Andy Hung4ede21d2014-12-12 15:37:34 -0800445 StaticAudioTrackPosLoopQueue::Observer mPosLoopObserver;
Andy Hung9b461582014-12-01 17:56:29 -0800446 StaticAudioTrackState mState; // last communicated state to server
Andy Hung4ede21d2014-12-12 15:37:34 -0800447 StaticAudioTrackPosLoop mPosLoop; // snapshot of position and loop.
Glenn Kastene3aa6592012-12-04 12:22:46 -0800448};
449
450// ----------------------------------------------------------------------------
451
452// Proxy used by AudioRecord client
453class AudioRecordClientProxy : public ClientProxy {
454public:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800455 AudioRecordClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
456 size_t frameSize)
457 : ClientProxy(cblk, buffers, frameCount, frameSize,
Andy Hung3f0c9022016-01-15 17:49:46 -0800458 false /*isOut*/, false /*clientInServer*/)
459 , mTimestampObserver(&cblk->mExtendedTimestampQueue) { }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800460 ~AudioRecordClientProxy() { }
Andy Hung3f0c9022016-01-15 17:49:46 -0800461
462 status_t getTimestamp(ExtendedTimestamp *timestamp) {
463 if (timestamp == nullptr) {
464 return BAD_VALUE;
465 }
466 (void) mTimestampObserver.poll(mTimestamp);
467 *timestamp = mTimestamp;
468 return OK;
469 }
470
471 void clearTimestamp() {
472 mTimestamp.clear();
473 }
474
475 // Advances the client read pointer to the server write head pointer
476 // effectively flushing the client read buffer. The effect is
477 // instantaneous. Returns the number of frames flushed.
478 uint32_t flush() {
479 int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
480 int32_t front = mCblk->u.mStreaming.mFront;
481 android_atomic_release_store(rear, &mCblk->u.mStreaming.mFront);
482 return (Modulo<int32_t>(rear) - front).unsignedValue();
483 }
484
485private:
486 // The shared buffer contents referred to by the timestamp observer
487 // is initialized when the server proxy created. A local zero timestamp
488 // is initialized by the client constructor.
489 ExtendedTimestampQueue::Observer mTimestampObserver;
490 ExtendedTimestamp mTimestamp; // initialized by constructor
Glenn Kastene3aa6592012-12-04 12:22:46 -0800491};
492
493// ----------------------------------------------------------------------------
494
495// Proxy used by AudioFlinger server
496class ServerProxy : public Proxy {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800497protected:
498 ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
499 bool isOut, bool clientInServer);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800500public:
Glenn Kastene3aa6592012-12-04 12:22:46 -0800501 virtual ~ServerProxy() { }
502
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800503 // Obtain a buffer with filled frames (writing) or empty frames (reading).
504 // It is permitted to call obtainBuffer() multiple times in succession, without any intervening
505 // calls to releaseBuffer(). In that case, the final obtainBuffer() is the one that effectively
506 // sets or extends the unreleased frame count.
507 // Always non-blocking.
508 // On entry:
509 // buffer->mFrameCount should be initialized to maximum number of desired frames,
510 // which must be > 0.
511 // buffer->mNonContig is unused.
512 // buffer->mRaw is unused.
Glenn Kasten2e422c42013-10-18 13:00:29 -0700513 // ackFlush is true iff being called from Track::start to acknowledge a pending flush.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800514 // On exit:
515 // buffer->mFrameCount has the actual number of contiguous available frames,
516 // which is always 0 when the return status != NO_ERROR.
517 // buffer->mNonContig is the number of additional non-contiguous available frames.
518 // buffer->mRaw is a pointer to the first available frame,
519 // or NULL when buffer->mFrameCount == 0.
520 // The return status is one of:
521 // NO_ERROR Success, buffer->mFrameCount > 0.
522 // WOULD_BLOCK No frames are available.
523 // NO_INIT Shared memory is corrupt.
Glenn Kasten2e422c42013-10-18 13:00:29 -0700524 virtual status_t obtainBuffer(Buffer* buffer, bool ackFlush = false);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800525
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800526 // Release (some of) the frames last obtained.
527 // On entry, buffer->mFrameCount should have the number of frames to release,
528 // which must (cumulatively) be <= the number of frames last obtained but not yet released.
529 // It is permitted to call releaseBuffer() multiple times to release the frames in chunks.
530 // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer().
531 // On exit:
532 // buffer->mFrameCount is zero.
533 // buffer->mRaw is NULL.
534 virtual void releaseBuffer(Buffer* buffer);
535
536protected:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800537 size_t mAvailToClient; // estimated frames available to client prior to releaseBuffer()
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800538 int32_t mFlush; // our copy of cblk->u.mStreaming.mFlush, for streaming output only
Andy Hung3f0c9022016-01-15 17:49:46 -0800539 int64_t mReleased; // our copy of cblk->mServer, at 64 bit resolution
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800540};
541
542// Proxy used by AudioFlinger for servicing AudioTrack
543class AudioTrackServerProxy : public ServerProxy {
544public:
545 AudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700546 size_t frameSize, bool clientInServer = false, uint32_t sampleRate = 0)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700547 : ServerProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/, clientInServer),
Phil Burk2812d9e2016-01-04 10:34:30 -0800548 mPlaybackRateObserver(&cblk->mPlaybackRateQueue),
Andy Hungb3a486f2015-08-04 15:17:58 -0700549 mUnderrunCount(0), mUnderrunning(false),
550 mTimestampMutator(&cblk->mTimestampQueue) {
Eric Laurent83b88082014-06-20 18:31:16 -0700551 mCblk->mSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700552 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Eric Laurent83b88082014-06-20 18:31:16 -0700553 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800554protected:
555 virtual ~AudioTrackServerProxy() { }
556
557public:
Glenn Kastene3aa6592012-12-04 12:22:46 -0800558 // return value of these methods must be validated by the caller
559 uint32_t getSampleRate() const { return mCblk->mSampleRate; }
560 uint16_t getSendLevel_U4_12() const { return mCblk->mSendLevel; }
Glenn Kastenc56f3422014-03-21 17:53:17 -0700561 gain_minifloat_packed_t getVolumeLR() const { return mCblk->mVolumeLR; }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800562
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800563 // estimated total number of filled frames available to server to read,
564 // which may include non-contiguous frames
565 virtual size_t framesReady();
Glenn Kastene3aa6592012-12-04 12:22:46 -0800566
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 // Currently AudioFlinger will call framesReady() for a fast track from two threads:
568 // FastMixer thread, and normal mixer thread. This is dangerous, as the proxy is intended
569 // to be called from at most one thread of server, and one thread of client.
570 // As a temporary workaround, this method informs the proxy implementation that it
571 // should avoid doing a state queue poll from within framesReady().
572 // FIXME Change AudioFlinger to not call framesReady() from normal mixer thread.
573 virtual void framesReadyIsCalledByMultipleThreads() { }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800574
575 bool setStreamEndDone(); // and return previous value
Glenn Kasten82aaf942013-07-17 16:05:07 -0700576
577 // Add to the tally of underrun frames, and inform client of underrun
578 virtual void tallyUnderrunFrames(uint32_t frameCount);
579
580 // Return the total number of frames which AudioFlinger desired but were unavailable,
581 // and thus which resulted in an underrun.
582 virtual uint32_t getUnderrunFrames() const { return mCblk->u.mStreaming.mUnderrunFrames; }
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700583
584 // Return the total number of frames that AudioFlinger has obtained and released
Andy Hung3f0c9022016-01-15 17:49:46 -0800585 virtual size_t framesReleased() const { return mReleased; }
Andy Hung8edb8dc2015-03-26 19:13:55 -0700586
587 // Return the playback speed and pitch read atomically. Not multi-thread safe on server side.
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700588 AudioPlaybackRate getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -0700589
Andy Hungb3a486f2015-08-04 15:17:58 -0700590 // Expose timestamp to client proxy. Should only be called by a single thread.
591 void setTimestamp(const AudioTimestamp &timestamp) {
592 mTimestampMutator.push(timestamp);
593 }
594
Andy Hung8edb8dc2015-03-26 19:13:55 -0700595private:
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700596 AudioPlaybackRate mPlaybackRate; // last observed playback rate
597 PlaybackRateQueue::Observer mPlaybackRateObserver;
Phil Burk2812d9e2016-01-04 10:34:30 -0800598
599 // The server keeps a copy here where it is safe from the client.
600 uint32_t mUnderrunCount; // echoed to mCblk
601 bool mUnderrunning; // used to detect edge of underrun
Andy Hungb3a486f2015-08-04 15:17:58 -0700602
603 TimestampQueue::Mutator mTimestampMutator;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800604};
605
606class StaticAudioTrackServerProxy : public AudioTrackServerProxy {
607public:
608 StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
609 size_t frameSize);
610protected:
611 virtual ~StaticAudioTrackServerProxy() { }
612
613public:
614 virtual size_t framesReady();
615 virtual void framesReadyIsCalledByMultipleThreads();
Glenn Kasten2e422c42013-10-18 13:00:29 -0700616 virtual status_t obtainBuffer(Buffer* buffer, bool ackFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800617 virtual void releaseBuffer(Buffer* buffer);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700618 virtual void tallyUnderrunFrames(uint32_t frameCount);
619 virtual uint32_t getUnderrunFrames() const { return 0; }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800620
621private:
Andy Hung9b461582014-12-01 17:56:29 -0800622 status_t updateStateWithLoop(StaticAudioTrackState *localState,
623 const StaticAudioTrackState &update) const;
624 status_t updateStateWithPosition(StaticAudioTrackState *localState,
625 const StaticAudioTrackState &update) const;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800626 ssize_t pollPosition(); // poll for state queue update, and return current position
627 StaticAudioTrackSingleStateQueue::Observer mObserver;
Andy Hung4ede21d2014-12-12 15:37:34 -0800628 StaticAudioTrackPosLoopQueue::Mutator mPosLoopMutator;
Andy Hungcb2129b2014-11-11 12:17:22 -0800629 size_t mFramesReadySafe; // Assuming size_t read/writes are atomic on 32 / 64 bit
630 // processors, this is a thread-safe version of
631 // mFramesReady.
632 int64_t mFramesReady; // The number of frames ready in the static buffer
633 // including loops. This is 64 bits since loop mode
634 // can cause a track to appear to have a large number
635 // of frames. INT64_MAX means an infinite loop.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800636 bool mFramesReadyIsCalledByMultipleThreads;
Andy Hung9b461582014-12-01 17:56:29 -0800637 StaticAudioTrackState mState; // Server side state. Any updates from client must be
638 // passed by the mObserver SingleStateQueue.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800639};
Glenn Kastene3aa6592012-12-04 12:22:46 -0800640
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800641// Proxy used by AudioFlinger for servicing AudioRecord
642class AudioRecordServerProxy : public ServerProxy {
643public:
644 AudioRecordServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700645 size_t frameSize, bool clientInServer)
Andy Hung3f0c9022016-01-15 17:49:46 -0800646 : ServerProxy(cblk, buffers, frameCount, frameSize, false /*isOut*/, clientInServer)
647 , mTimestampMutator(&cblk->mExtendedTimestampQueue) { }
648
649 // Return the total number of frames that AudioFlinger has obtained and released
650 virtual int64_t framesReleased() const { return mReleased; }
651
652 // Expose timestamp to client proxy. Should only be called by a single thread.
653 virtual void setExtendedTimestamp(const ExtendedTimestamp &timestamp) {
654 mTimestampMutator.push(timestamp);
655 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800656protected:
657 virtual ~AudioRecordServerProxy() { }
Andy Hung3f0c9022016-01-15 17:49:46 -0800658
659 ExtendedTimestampQueue::Mutator mTimestampMutator;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800660};
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800661
662// ----------------------------------------------------------------------------
663
664}; // namespace android
665
666#endif // ANDROID_AUDIO_TRACK_SHARED_H