blob: 1b1f1499a564c1a2b8a629d08fff57eb5ec51436 [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>
Mikhail Naganov9f3c02d2019-08-12 11:36:05 -070031#include <media/nbaio/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
Andy Hung1d3556d2018-03-29 16:30:14 -070063 volatile int32_t mStop; // set by client to indicate a stop frame position; server
64 // will not read beyond this position until start is called.
Phil Burk2812d9e2016-01-04 10:34:30 -080065 volatile uint32_t mUnderrunFrames; // server increments for each unavailable but desired frame
66 volatile uint32_t mUnderrunCount; // server increments for each underrun occurrence
Glenn Kastene3aa6592012-12-04 12:22:46 -080067};
68
Andy Hung9b461582014-12-01 17:56:29 -080069// Represents a single state of an AudioTrack that was created in static mode (shared memory buffer
70// supplied by the client). This state needs to be communicated from the client to server. As this
71// state is too large to be updated atomically without a mutex, and mutexes aren't allowed here, the
72// state is wrapped by a SingleStateQueue.
73struct StaticAudioTrackState {
74 // Do not define constructors, destructors, or virtual methods as this is part of a
75 // union in shared memory and they will not get called properly.
76
77 // These fields should both be size_t, but since they are located in shared memory we
78 // force to 32-bit. The client and server may have different typedefs for size_t.
79
80 // The state has a sequence counter to indicate whether changes are made to loop or position.
81 // The sequence counter also currently indicates whether loop or position is first depending
82 // on which is greater; it jumps by max(mLoopSequence, mPositionSequence) + 1.
83
84 uint32_t mLoopStart;
85 uint32_t mLoopEnd;
86 int32_t mLoopCount;
87 uint32_t mLoopSequence; // a sequence counter to indicate changes to loop
88 uint32_t mPosition;
89 uint32_t mPositionSequence; // a sequence counter to indicate changes to position
90};
91
Glenn Kasten9f80dd22012-12-18 15:57:32 -080092typedef SingleStateQueue<StaticAudioTrackState> StaticAudioTrackSingleStateQueue;
93
Andy Hung4ede21d2014-12-12 15:37:34 -080094struct StaticAudioTrackPosLoop {
95 // Do not define constructors, destructors, or virtual methods as this is part of a
96 // union in shared memory and will not get called properly.
97
98 // These fields should both be size_t, but since they are located in shared memory we
99 // force to 32-bit. The client and server may have different typedefs for size_t.
100
101 // This struct information is stored in a single state queue to communicate the
102 // static AudioTrack server state to the client while data is consumed.
103 // It is smaller than StaticAudioTrackState to prevent unnecessary information from
104 // being sent.
105
106 uint32_t mBufferPosition;
107 int32_t mLoopCount;
108};
109
110typedef SingleStateQueue<StaticAudioTrackPosLoop> StaticAudioTrackPosLoopQueue;
111
Glenn Kastene3aa6592012-12-04 12:22:46 -0800112struct AudioTrackSharedStatic {
Andy Hung4ede21d2014-12-12 15:37:34 -0800113 // client requests to the server for loop or position changes.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800114 StaticAudioTrackSingleStateQueue::Shared
115 mSingleStateQueue;
Andy Hung4ede21d2014-12-12 15:37:34 -0800116 // position info updated asynchronously by server and read by client,
117 // "for entertainment purposes only"
118 StaticAudioTrackPosLoopQueue::Shared
119 mPosLoopQueue;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800120};
121
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700122typedef SingleStateQueue<AudioPlaybackRate> PlaybackRateQueue;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700123
Andy Hung3f0c9022016-01-15 17:49:46 -0800124typedef SingleStateQueue<ExtendedTimestamp> ExtendedTimestampQueue;
125
Glenn Kastene3aa6592012-12-04 12:22:46 -0800126// ----------------------------------------------------------------------------
127
Glenn Kasten1a0ae5b2012-02-03 10:24:48 -0800128// Important: do not add any virtual methods, including ~
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800129struct audio_track_cblk_t
130{
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800131 // Since the control block is always located in shared memory, this constructor
132 // is only used for placement new(). It is never used for regular new() or stack.
133 audio_track_cblk_t();
134 /*virtual*/ ~audio_track_cblk_t() { }
135
Glenn Kastene3aa6592012-12-04 12:22:46 -0800136 friend class Proxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800137 friend class ClientProxy;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800138 friend class AudioTrackClientProxy;
139 friend class AudioRecordClientProxy;
140 friend class ServerProxy;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800141 friend class AudioTrackServerProxy;
142 friend class AudioRecordServerProxy;
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800143
144 // The data members are grouped so that members accessed frequently and in the same context
145 // are in the same line of data cache.
Glenn Kasten99e53b82012-01-19 08:59:58 -0800146
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700147 uint32_t mServer; // Number of filled frames consumed by server (mIsOut),
148 // or filled frames provided by server (!mIsOut).
149 // It is updated asynchronously by server without a barrier.
Glenn Kastenb187de12014-12-30 08:18:15 -0800150 // The value should be used
151 // "for entertainment purposes only",
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700152 // which means don't make important decisions based on it.
Glenn Kasten22eb4e22012-11-07 14:03:00 -0800153
Glenn Kasten74935e42013-12-19 08:56:45 -0800154 uint32_t mPad1; // unused
Glenn Kasten99e53b82012-01-19 08:59:58 -0800155
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700156 volatile int32_t mFutex; // event flag: down (P) by client,
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800157 // up (V) by server or binderDied() or interrupt()
Glenn Kasten0d09a9b2013-06-24 12:06:46 -0700158#define CBLK_FUTEX_WAKE 1 // if event flag bit is set, then a deferred wake is pending
Glenn Kasten99e53b82012-01-19 08:59:58 -0800159
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800160private:
161
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800162 // This field should be a size_t, but since it is located in shared memory we
163 // force to 32-bit. The client and server may have different typedefs for size_t.
164 uint32_t mMinimum; // server wakes up client if available >= mMinimum
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800165
Glenn Kastenc56f3422014-03-21 17:53:17 -0700166 // Stereo gains for AudioTrack only, not used by AudioRecord.
167 gain_minifloat_packed_t mVolumeLR;
Glenn Kastenb1cf75c2012-01-17 12:20:54 -0800168
Glenn Kastene3aa6592012-12-04 12:22:46 -0800169 uint32_t mSampleRate; // AudioTrack only: client's requested sample rate in Hz
170 // or 0 == default. Write-only client, read-only server.
Glenn Kasten99e53b82012-01-19 08:59:58 -0800171
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700172 PlaybackRateQueue::Shared mPlaybackRateQueue;
Andy Hung8edb8dc2015-03-26 19:13:55 -0700173
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800174 // client write-only, server read-only
175 uint16_t mSendLevel; // Fixed point U4.12 so 0x1000 means 1.0
176
Colin Crossb8c35f92017-04-27 16:15:51 -0700177 uint16_t mPad2 __attribute__((__unused__)); // unused
Eric Laurentd1b449a2010-05-14 03:26:45 -0700178
Andy Hung3f0c9022016-01-15 17:49:46 -0800179 // server write-only, client read
Eric Laurent8ce8e262016-02-16 11:59:23 -0800180 ExtendedTimestampQueue::Shared mExtendedTimestampQueue;
Andy Hung818e7a32016-02-16 18:08:07 -0800181
Phil Burke8972b02016-03-04 11:29:57 -0800182 // This is set by AudioTrack.setBufferSizeInFrames().
183 // A write will not fill the buffer above this limit.
184 volatile uint32_t mBufferSizeInFrames; // effective size of the buffer
185
Glenn Kastene3aa6592012-12-04 12:22:46 -0800186public:
Glenn Kasten99e53b82012-01-19 08:59:58 -0800187
Glenn Kasten96f60d82013-07-12 10:21:18 -0700188 volatile int32_t mFlags; // combinations of CBLK_*
Eric Laurent38ccae22011-03-28 18:37:07 -0700189
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800190public:
Glenn Kastene3aa6592012-12-04 12:22:46 -0800191 union {
192 AudioTrackSharedStreaming mStreaming;
193 AudioTrackSharedStatic mStatic;
194 int mAlign[8];
195 } u;
196
197 // Cache line boundary (32 bytes)
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800198};
199
Glenn Kastene3aa6592012-12-04 12:22:46 -0800200// ----------------------------------------------------------------------------
201
202// Proxy for shared memory control block, to isolate callers from needing to know the details.
203// There is exactly one ClientProxy and one ServerProxy per shared memory control block.
204// The proxies are located in normal memory, and are not multi-thread safe within a given side.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800205class Proxy : public RefBase {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800206protected:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800207 Proxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize, bool isOut,
208 bool clientInServer);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800209 virtual ~Proxy() { }
210
211public:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800212 struct Buffer {
213 size_t mFrameCount; // number of frames available in this buffer
214 void* mRaw; // pointer to first frame
215 size_t mNonContig; // number of additional non-contiguous frames available
216 };
Glenn Kastene3aa6592012-12-04 12:22:46 -0800217
Phil Burkc0adecb2016-01-08 12:44:11 -0800218 size_t frameCount() const { return mFrameCount; }
219
Glenn Kastene3aa6592012-12-04 12:22:46 -0800220protected:
221 // These refer to shared memory, and are virtual addresses with respect to the current process.
222 // They may have different virtual addresses within the other process.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800223 audio_track_cblk_t* const mCblk; // the control block
224 void* const mBuffers; // starting address of buffers
Glenn Kastene3aa6592012-12-04 12:22:46 -0800225
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800226 const size_t mFrameCount; // not necessarily a power of 2
227 const size_t mFrameSize; // in bytes
228 const size_t mFrameCountP2; // mFrameCount rounded to power of 2, streaming mode
229 const bool mIsOut; // true for AudioTrack, false for AudioRecord
230 const bool mClientInServer; // true for OutputTrack, false for AudioTrack & AudioRecord
231 bool mIsShutdown; // latch set to true when shared memory corruption detected
Glenn Kasten7db7df02013-06-25 16:13:23 -0700232 size_t mUnreleased; // unreleased frames remaining from most recent obtainBuffer
Glenn Kastene3aa6592012-12-04 12:22:46 -0800233};
234
235// ----------------------------------------------------------------------------
236
237// Proxy seen by AudioTrack client and AudioRecord client
238class ClientProxy : public Proxy {
Eric Laurent83b88082014-06-20 18:31:16 -0700239public:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800240 ClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
241 bool isOut, bool clientInServer);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800242 virtual ~ClientProxy() { }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800243
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800244 static const struct timespec kForever;
245 static const struct timespec kNonBlocking;
246
247 // Obtain a buffer with filled frames (reading) or empty frames (writing).
248 // It is permitted to call obtainBuffer() multiple times in succession, without any intervening
249 // calls to releaseBuffer(). In that case, the final obtainBuffer() is the one that effectively
250 // sets or extends the unreleased frame count.
251 // On entry:
252 // buffer->mFrameCount should be initialized to maximum number of desired frames,
253 // which must be > 0.
254 // buffer->mNonContig is unused.
255 // buffer->mRaw is unused.
256 // requested is the requested timeout in local monotonic delta time units:
257 // NULL or &kNonBlocking means non-blocking (zero timeout).
258 // &kForever means block forever (infinite timeout).
259 // Other values mean a specific timeout in local monotonic delta time units.
260 // elapsed is a pointer to a location that will hold the total local monotonic time that
261 // elapsed while blocked, or NULL if not needed.
262 // On exit:
263 // buffer->mFrameCount has the actual number of contiguous available frames,
264 // which is always 0 when the return status != NO_ERROR.
265 // buffer->mNonContig is the number of additional non-contiguous available frames.
266 // buffer->mRaw is a pointer to the first available frame,
267 // or NULL when buffer->mFrameCount == 0.
268 // The return status is one of:
269 // NO_ERROR Success, buffer->mFrameCount > 0.
270 // WOULD_BLOCK Non-blocking mode and no frames are available.
271 // TIMED_OUT Timeout occurred before any frames became available.
272 // This can happen even for infinite timeout, due to a spurious wakeup.
273 // In this case, the caller should investigate and then re-try as appropriate.
274 // DEAD_OBJECT Server has died or invalidated, caller should destroy this proxy and re-create.
275 // -EINTR Call has been interrupted. Look around to see why, and then perhaps try again.
276 // NO_INIT Shared memory is corrupt.
Eric Laurent4d231dc2016-03-11 18:38:23 -0800277 // NOT_ENOUGH_DATA Server has disabled the track because of underrun: restart the track
278 // if still in active state.
Glenn Kasten7db7df02013-06-25 16:13:23 -0700279 // Assertion failure on entry, if buffer == NULL or buffer->mFrameCount == 0.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800280 status_t obtainBuffer(Buffer* buffer, const struct timespec *requested = NULL,
281 struct timespec *elapsed = NULL);
282
283 // Release (some of) the frames last obtained.
284 // On entry, buffer->mFrameCount should have the number of frames to release,
285 // which must (cumulatively) be <= the number of frames last obtained but not yet released.
286 // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer().
287 // It is permitted to call releaseBuffer() multiple times to release the frames in chunks.
288 // On exit:
289 // buffer->mFrameCount is zero.
290 // buffer->mRaw is NULL.
291 void releaseBuffer(Buffer* buffer);
292
293 // Call after detecting server's death
294 void binderDied();
295
296 // Call to force an obtainBuffer() to return quickly with -EINTR
297 void interrupt();
298
Andy Hung90e8a972015-11-09 16:42:40 -0800299 Modulo<uint32_t> getPosition() {
Glenn Kastenf20e1d82013-07-12 09:45:18 -0700300 return mEpoch + mCblk->mServer;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800301 }
302
Phil Burkc0adecb2016-01-08 12:44:11 -0800303 void setEpoch(const Modulo<uint32_t> &epoch) {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800304 mEpoch = epoch;
305 }
306
307 void setMinimum(size_t minimum) {
Glenn Kastenfdac7c02014-01-28 11:03:28 -0800308 // This can only happen on a 64-bit client
309 if (minimum > UINT32_MAX) {
310 minimum = UINT32_MAX;
311 }
312 mCblk->mMinimum = (uint32_t) minimum;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800313 }
314
315 // Return the number of frames that would need to be obtained and released
316 // in order for the client to be aligned at start of buffer
317 virtual size_t getMisalignment();
318
Andy Hung90e8a972015-11-09 16:42:40 -0800319 Modulo<uint32_t> getEpoch() const {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800320 return mEpoch;
321 }
322
Phil Burke8972b02016-03-04 11:29:57 -0800323 uint32_t getBufferSizeInFrames() const { return mBufferSizeInFrames; }
324 // See documentation for AudioTrack::setBufferSizeInFrames()
325 uint32_t setBufferSizeInFrames(uint32_t requestedSize);
Phil Burkc0adecb2016-01-08 12:44:11 -0800326
Andy Hung6ae58432016-02-16 18:32:24 -0800327 status_t getTimestamp(ExtendedTimestamp *timestamp) {
328 if (timestamp == nullptr) {
329 return BAD_VALUE;
330 }
331 (void) mTimestampObserver.poll(mTimestamp);
332 *timestamp = mTimestamp;
333 return OK;
334 }
335
336 void clearTimestamp() {
337 mTimestamp.clear();
338 }
339
Andy Hung1d3556d2018-03-29 16:30:14 -0700340 virtual void stop() { }; // called by client in AudioTrack::stop()
341
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800342private:
Phil Burke8972b02016-03-04 11:29:57 -0800343 // This is a copy of mCblk->mBufferSizeInFrames
344 uint32_t mBufferSizeInFrames; // effective size of the buffer
345
Andy Hung90e8a972015-11-09 16:42:40 -0800346 Modulo<uint32_t> mEpoch;
Andy Hung6ae58432016-02-16 18:32:24 -0800347
348 // The shared buffer contents referred to by the timestamp observer
349 // is initialized when the server proxy created. A local zero timestamp
350 // is initialized by the client constructor.
351 ExtendedTimestampQueue::Observer mTimestampObserver;
352 ExtendedTimestamp mTimestamp; // initialized by constructor
Glenn Kastene3aa6592012-12-04 12:22:46 -0800353};
354
355// ----------------------------------------------------------------------------
356
357// Proxy used by AudioTrack client, which also includes AudioFlinger::PlaybackThread::OutputTrack
358class AudioTrackClientProxy : public ClientProxy {
359public:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800360 AudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
361 size_t frameSize, bool clientInServer = false)
362 : ClientProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/,
Andy Hung8edb8dc2015-03-26 19:13:55 -0700363 clientInServer),
Andy Hung6ae58432016-02-16 18:32:24 -0800364 mPlaybackRateMutator(&cblk->mPlaybackRateQueue) {
365 }
366
Glenn Kastene3aa6592012-12-04 12:22:46 -0800367 virtual ~AudioTrackClientProxy() { }
368
369 // No barriers on the following operations, so the ordering of loads/stores
370 // with respect to other parameters is UNPREDICTABLE. That's considered safe.
371
372 // caller must limit to 0.0 <= sendLevel <= 1.0
373 void setSendLevel(float sendLevel) {
374 mCblk->mSendLevel = uint16_t(sendLevel * 0x1000);
375 }
376
Glenn Kastenc56f3422014-03-21 17:53:17 -0700377 // set stereo gains
378 void setVolumeLR(gain_minifloat_packed_t volumeLR) {
Glenn Kastene3aa6592012-12-04 12:22:46 -0800379 mCblk->mVolumeLR = volumeLR;
380 }
381
382 void setSampleRate(uint32_t sampleRate) {
383 mCblk->mSampleRate = sampleRate;
384 }
385
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700386 void setPlaybackRate(const AudioPlaybackRate& playbackRate) {
Andy Hung8edb8dc2015-03-26 19:13:55 -0700387 mPlaybackRateMutator.push(playbackRate);
388 }
389
Andy Hung1d3556d2018-03-29 16:30:14 -0700390 // Sends flush and stop position information from the client to the server,
391 // used by streaming AudioTrack flush() or stop().
392 void sendStreamingFlushStop(bool flush);
393
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800394 virtual void flush();
395
Andy Hung1d3556d2018-03-29 16:30:14 -0700396 void stop() override;
397
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800398 virtual uint32_t getUnderrunFrames() const {
399 return mCblk->u.mStreaming.mUnderrunFrames;
400 }
Phil Burk2812d9e2016-01-04 10:34:30 -0800401 virtual uint32_t getUnderrunCount() const {
402 return mCblk->u.mStreaming.mUnderrunCount;
403 }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800404
405 bool clearStreamEndDone(); // and return previous value
406
407 bool getStreamEndDone() const;
408
Richard Fitzgeraldb1a270d2013-05-14 12:12:21 +0100409 status_t waitStreamEndDone(const struct timespec *requested);
Andy Hung8edb8dc2015-03-26 19:13:55 -0700410
411private:
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700412 PlaybackRateQueue::Mutator mPlaybackRateMutator;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800413};
414
415class StaticAudioTrackClientProxy : public AudioTrackClientProxy {
416public:
417 StaticAudioTrackClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
418 size_t frameSize);
419 virtual ~StaticAudioTrackClientProxy() { }
420
421 virtual void flush();
422
Andy Hung1d3556d2018-03-29 16:30:14 -0700423 void stop() override;
424
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800425#define MIN_LOOP 16 // minimum length of each loop iteration in frames
Andy Hung9b461582014-12-01 17:56:29 -0800426
427 // setLoop(), setBufferPosition(), and setBufferPositionAndLoop() set the
428 // static buffer position and looping parameters. These commands are not
429 // synchronous (they do not wait or block); instead they take effect at the
430 // next buffer data read from the server side. However, the client side
431 // getters will read a cached version of the position and loop variables
432 // until the setting takes effect.
433 //
434 // setBufferPositionAndLoop() is equivalent to calling, in order, setLoop() and
435 // setBufferPosition().
436 //
437 // The functions should not be relied upon to do parameter or state checking.
438 // That is done at the AudioTrack level.
439
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800440 void setLoop(size_t loopStart, size_t loopEnd, int loopCount);
Andy Hung9b461582014-12-01 17:56:29 -0800441 void setBufferPosition(size_t position);
442 void setBufferPositionAndLoop(size_t position, size_t loopStart, size_t loopEnd,
443 int loopCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800444 size_t getBufferPosition();
Andy Hung4ede21d2014-12-12 15:37:34 -0800445 // getBufferPositionAndLoopCount() provides the proper snapshot of
446 // position and loopCount together.
447 void getBufferPositionAndLoopCount(size_t *position, int *loopCount);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800448
449 virtual size_t getMisalignment() {
450 return 0;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800451 }
452
Andy Hung03e1e2c2018-02-20 12:49:08 -0800453 virtual uint32_t getUnderrunFrames() const override {
454 return 0;
455 }
456
457 virtual uint32_t getUnderrunCount() const override {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800458 return 0;
Glenn Kastene3aa6592012-12-04 12:22:46 -0800459 }
460
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800461private:
462 StaticAudioTrackSingleStateQueue::Mutator mMutator;
Andy Hung4ede21d2014-12-12 15:37:34 -0800463 StaticAudioTrackPosLoopQueue::Observer mPosLoopObserver;
Andy Hung9b461582014-12-01 17:56:29 -0800464 StaticAudioTrackState mState; // last communicated state to server
Andy Hung4ede21d2014-12-12 15:37:34 -0800465 StaticAudioTrackPosLoop mPosLoop; // snapshot of position and loop.
Glenn Kastene3aa6592012-12-04 12:22:46 -0800466};
467
468// ----------------------------------------------------------------------------
469
470// Proxy used by AudioRecord client
471class AudioRecordClientProxy : public ClientProxy {
472public:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800473 AudioRecordClientProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
474 size_t frameSize)
475 : ClientProxy(cblk, buffers, frameCount, frameSize,
Andy Hung6ae58432016-02-16 18:32:24 -0800476 false /*isOut*/, false /*clientInServer*/) { }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800477 ~AudioRecordClientProxy() { }
Andy Hung3f0c9022016-01-15 17:49:46 -0800478
Andy Hung3f0c9022016-01-15 17:49:46 -0800479 // Advances the client read pointer to the server write head pointer
480 // effectively flushing the client read buffer. The effect is
481 // instantaneous. Returns the number of frames flushed.
482 uint32_t flush() {
483 int32_t rear = android_atomic_acquire_load(&mCblk->u.mStreaming.mRear);
484 int32_t front = mCblk->u.mStreaming.mFront;
485 android_atomic_release_store(rear, &mCblk->u.mStreaming.mFront);
486 return (Modulo<int32_t>(rear) - front).unsignedValue();
487 }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800488};
489
490// ----------------------------------------------------------------------------
491
492// Proxy used by AudioFlinger server
493class ServerProxy : public Proxy {
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800494protected:
495 ServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount, size_t frameSize,
496 bool isOut, bool clientInServer);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800497public:
Glenn Kastene3aa6592012-12-04 12:22:46 -0800498 virtual ~ServerProxy() { }
499
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800500 // Obtain a buffer with filled frames (writing) or empty frames (reading).
501 // It is permitted to call obtainBuffer() multiple times in succession, without any intervening
502 // calls to releaseBuffer(). In that case, the final obtainBuffer() is the one that effectively
503 // sets or extends the unreleased frame count.
504 // Always non-blocking.
505 // On entry:
506 // buffer->mFrameCount should be initialized to maximum number of desired frames,
507 // which must be > 0.
508 // buffer->mNonContig is unused.
509 // buffer->mRaw is unused.
Glenn Kasten2e422c42013-10-18 13:00:29 -0700510 // ackFlush is true iff being called from Track::start to acknowledge a pending flush.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800511 // On exit:
512 // buffer->mFrameCount has the actual number of contiguous available frames,
513 // which is always 0 when the return status != NO_ERROR.
514 // buffer->mNonContig is the number of additional non-contiguous available frames.
515 // buffer->mRaw is a pointer to the first available frame,
516 // or NULL when buffer->mFrameCount == 0.
517 // The return status is one of:
518 // NO_ERROR Success, buffer->mFrameCount > 0.
519 // WOULD_BLOCK No frames are available.
520 // NO_INIT Shared memory is corrupt.
Glenn Kasten2e422c42013-10-18 13:00:29 -0700521 virtual status_t obtainBuffer(Buffer* buffer, bool ackFlush = false);
Glenn Kastene3aa6592012-12-04 12:22:46 -0800522
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800523 // Release (some of) the frames last obtained.
524 // On entry, buffer->mFrameCount should have the number of frames to release,
525 // which must (cumulatively) be <= the number of frames last obtained but not yet released.
526 // It is permitted to call releaseBuffer() multiple times to release the frames in chunks.
527 // buffer->mRaw is ignored, but is normally same pointer returned by last obtainBuffer().
528 // On exit:
529 // buffer->mFrameCount is zero.
530 // buffer->mRaw is NULL.
531 virtual void releaseBuffer(Buffer* buffer);
532
Andy Hung6ae58432016-02-16 18:32:24 -0800533 // Return the total number of frames that AudioFlinger has obtained and released
534 virtual int64_t framesReleased() const { return mReleased; }
535
536 // Expose timestamp to client proxy. Should only be called by a single thread.
537 virtual void setTimestamp(const ExtendedTimestamp &timestamp) {
538 mTimestampMutator.push(timestamp);
539 }
540
Andy Hungf6ab58d2018-05-25 12:50:39 -0700541 virtual ExtendedTimestamp getTimestamp() const {
542 return mTimestampMutator.last();
543 }
544
Phil Burk4bb650b2016-09-09 12:11:17 -0700545 // Flushes the shared ring buffer if the client had requested it using mStreaming.mFlush.
546 // If flush occurs then:
547 // cblk->u.mStreaming.mFront, ServerProxy::mFlush and ServerProxy::mFlushed will be modified
548 // client will be notified via Futex
549 virtual void flushBufferIfNeeded();
550
Andy Hung1d3556d2018-03-29 16:30:14 -0700551 // Returns the rear position of the AudioTrack shared ring buffer, limited by
552 // the stop frame position level.
553 virtual int32_t getRear() const = 0;
554
Andy Hungea2b9c02016-02-12 17:06:53 -0800555 // Total count of the number of flushed frames since creation (never reset).
556 virtual int64_t framesFlushed() const { return mFlushed; }
557
Andy Hung2a4e1612018-06-01 15:06:09 -0700558 // Safe frames ready query with no side effects.
559 virtual size_t framesReadySafe() const = 0;
560
Phil Burke8972b02016-03-04 11:29:57 -0800561 // Get dynamic buffer size from the shared control block.
562 uint32_t getBufferSizeInFrames() const {
563 return android_atomic_acquire_load((int32_t *)&mCblk->mBufferSizeInFrames);
564 }
565
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800566protected:
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800567 size_t mAvailToClient; // estimated frames available to client prior to releaseBuffer()
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800568 int32_t mFlush; // our copy of cblk->u.mStreaming.mFlush, for streaming output only
Andy Hung3f0c9022016-01-15 17:49:46 -0800569 int64_t mReleased; // our copy of cblk->mServer, at 64 bit resolution
Andy Hungea2b9c02016-02-12 17:06:53 -0800570 int64_t mFlushed; // flushed frames to account for client-server discrepancy
Andy Hung6ae58432016-02-16 18:32:24 -0800571 ExtendedTimestampQueue::Mutator mTimestampMutator;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800572};
573
574// Proxy used by AudioFlinger for servicing AudioTrack
575class AudioTrackServerProxy : public ServerProxy {
576public:
577 AudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700578 size_t frameSize, bool clientInServer = false, uint32_t sampleRate = 0)
Andy Hung8edb8dc2015-03-26 19:13:55 -0700579 : ServerProxy(cblk, buffers, frameCount, frameSize, true /*isOut*/, clientInServer),
Phil Burk2812d9e2016-01-04 10:34:30 -0800580 mPlaybackRateObserver(&cblk->mPlaybackRateQueue),
Andy Hung818e7a32016-02-16 18:08:07 -0800581 mUnderrunCount(0), mUnderrunning(false), mDrained(true) {
Eric Laurent83b88082014-06-20 18:31:16 -0700582 mCblk->mSampleRate = sampleRate;
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700583 mPlaybackRate = AUDIO_PLAYBACK_RATE_DEFAULT;
Eric Laurent83b88082014-06-20 18:31:16 -0700584 }
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800585protected:
586 virtual ~AudioTrackServerProxy() { }
587
588public:
Glenn Kastene3aa6592012-12-04 12:22:46 -0800589 // return value of these methods must be validated by the caller
590 uint32_t getSampleRate() const { return mCblk->mSampleRate; }
591 uint16_t getSendLevel_U4_12() const { return mCblk->mSendLevel; }
Glenn Kastenc56f3422014-03-21 17:53:17 -0700592 gain_minifloat_packed_t getVolumeLR() const { return mCblk->mVolumeLR; }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800593
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800594 // estimated total number of filled frames available to server to read,
595 // which may include non-contiguous frames
596 virtual size_t framesReady();
Glenn Kastene3aa6592012-12-04 12:22:46 -0800597
Andy Hung2a4e1612018-06-01 15:06:09 -0700598 size_t framesReadySafe() const override; // frames available to read by server.
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700599
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800600 // Currently AudioFlinger will call framesReady() for a fast track from two threads:
601 // FastMixer thread, and normal mixer thread. This is dangerous, as the proxy is intended
602 // to be called from at most one thread of server, and one thread of client.
603 // As a temporary workaround, this method informs the proxy implementation that it
604 // should avoid doing a state queue poll from within framesReady().
605 // FIXME Change AudioFlinger to not call framesReady() from normal mixer thread.
606 virtual void framesReadyIsCalledByMultipleThreads() { }
Eric Laurentbfb1b832013-01-07 09:53:42 -0800607
608 bool setStreamEndDone(); // and return previous value
Glenn Kasten82aaf942013-07-17 16:05:07 -0700609
610 // Add to the tally of underrun frames, and inform client of underrun
611 virtual void tallyUnderrunFrames(uint32_t frameCount);
612
613 // Return the total number of frames which AudioFlinger desired but were unavailable,
614 // and thus which resulted in an underrun.
615 virtual uint32_t getUnderrunFrames() const { return mCblk->u.mStreaming.mUnderrunFrames; }
Glenn Kastenbd096fd2013-08-23 13:53:56 -0700616
Andy Hung8edb8dc2015-03-26 19:13:55 -0700617 // Return the playback speed and pitch read atomically. Not multi-thread safe on server side.
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700618 AudioPlaybackRate getPlaybackRate();
Andy Hung8edb8dc2015-03-26 19:13:55 -0700619
Andy Hung818e7a32016-02-16 18:08:07 -0800620 // Set the internal drain state of the track buffer from the timestamp received.
621 virtual void setDrained(bool drained) {
622 mDrained.store(drained);
623 }
624
625 // Check if the internal drain state of the track buffer.
626 // This is not a guarantee, but advisory for determining whether the track is
627 // fully played out.
628 virtual bool isDrained() const {
629 return mDrained.load();
630 }
631
Andy Hung1d3556d2018-03-29 16:30:14 -0700632 int32_t getRear() const override;
633
634 // Called on server side track start().
635 virtual void start();
636
Andy Hung8edb8dc2015-03-26 19:13:55 -0700637private:
Ricardo Garcia5a8a95d2015-04-18 14:47:04 -0700638 AudioPlaybackRate mPlaybackRate; // last observed playback rate
639 PlaybackRateQueue::Observer mPlaybackRateObserver;
Phil Burk2812d9e2016-01-04 10:34:30 -0800640
Andy Hung1d3556d2018-03-29 16:30:14 -0700641 // Last client stop-at position when start() was called. Used for streaming AudioTracks.
642 std::atomic<int32_t> mStopLast{0};
643
Phil Burk2812d9e2016-01-04 10:34:30 -0800644 // The server keeps a copy here where it is safe from the client.
645 uint32_t mUnderrunCount; // echoed to mCblk
646 bool mUnderrunning; // used to detect edge of underrun
Andy Hung818e7a32016-02-16 18:08:07 -0800647
648 std::atomic<bool> mDrained; // is the track buffer drained
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800649};
650
651class StaticAudioTrackServerProxy : public AudioTrackServerProxy {
652public:
653 StaticAudioTrackServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
654 size_t frameSize);
655protected:
656 virtual ~StaticAudioTrackServerProxy() { }
657
658public:
659 virtual size_t framesReady();
Andy Hung2c6c3bb2017-06-16 14:01:45 -0700660 virtual size_t framesReadySafe() const override;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800661 virtual void framesReadyIsCalledByMultipleThreads();
Glenn Kasten2e422c42013-10-18 13:00:29 -0700662 virtual status_t obtainBuffer(Buffer* buffer, bool ackFlush);
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800663 virtual void releaseBuffer(Buffer* buffer);
Glenn Kasten82aaf942013-07-17 16:05:07 -0700664 virtual void tallyUnderrunFrames(uint32_t frameCount);
665 virtual uint32_t getUnderrunFrames() const { return 0; }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800666
Andy Hung1d3556d2018-03-29 16:30:14 -0700667 int32_t getRear() const override;
668
669 void start() override { } // ignore for static tracks
670
Glenn Kastene3aa6592012-12-04 12:22:46 -0800671private:
Andy Hung9b461582014-12-01 17:56:29 -0800672 status_t updateStateWithLoop(StaticAudioTrackState *localState,
673 const StaticAudioTrackState &update) const;
674 status_t updateStateWithPosition(StaticAudioTrackState *localState,
675 const StaticAudioTrackState &update) const;
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800676 ssize_t pollPosition(); // poll for state queue update, and return current position
677 StaticAudioTrackSingleStateQueue::Observer mObserver;
Andy Hung4ede21d2014-12-12 15:37:34 -0800678 StaticAudioTrackPosLoopQueue::Mutator mPosLoopMutator;
Andy Hungcb2129b2014-11-11 12:17:22 -0800679 size_t mFramesReadySafe; // Assuming size_t read/writes are atomic on 32 / 64 bit
680 // processors, this is a thread-safe version of
681 // mFramesReady.
682 int64_t mFramesReady; // The number of frames ready in the static buffer
683 // including loops. This is 64 bits since loop mode
684 // can cause a track to appear to have a large number
685 // of frames. INT64_MAX means an infinite loop.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800686 bool mFramesReadyIsCalledByMultipleThreads;
Andy Hung9b461582014-12-01 17:56:29 -0800687 StaticAudioTrackState mState; // Server side state. Any updates from client must be
688 // passed by the mObserver SingleStateQueue.
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800689};
Glenn Kastene3aa6592012-12-04 12:22:46 -0800690
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800691// Proxy used by AudioFlinger for servicing AudioRecord
692class AudioRecordServerProxy : public ServerProxy {
693public:
694 AudioRecordServerProxy(audio_track_cblk_t* cblk, void *buffers, size_t frameCount,
Eric Laurent83b88082014-06-20 18:31:16 -0700695 size_t frameSize, bool clientInServer)
Andy Hung6ae58432016-02-16 18:32:24 -0800696 : ServerProxy(cblk, buffers, frameCount, frameSize, false /*isOut*/, clientInServer) { }
Andy Hung3f0c9022016-01-15 17:49:46 -0800697
Andy Hung1d3556d2018-03-29 16:30:14 -0700698 int32_t getRear() const override {
699 return mCblk->u.mStreaming.mRear; // For completeness only; mRear written by server.
700 }
701
Andy Hung2a4e1612018-06-01 15:06:09 -0700702 size_t framesReadySafe() const override; // frames available to read by client.
703
Glenn Kasten9f80dd22012-12-18 15:57:32 -0800704protected:
705 virtual ~AudioRecordServerProxy() { }
Glenn Kastene3aa6592012-12-04 12:22:46 -0800706};
The Android Open Source Project89fa4ad2009-03-03 19:31:44 -0800707
708// ----------------------------------------------------------------------------
709
710}; // namespace android
711
712#endif // ANDROID_AUDIO_TRACK_SHARED_H