blob: b5ae0f102f5a1225e5829fb45f0ef4212b0488f5 [file] [log] [blame]
Glenn Kasten01066232012-02-27 11:50:44 -08001/*
2 * Copyright (C) 2012 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_NBAIO_H
18#define ANDROID_AUDIO_NBAIO_H
19
20// Non-blocking audio I/O interface
21//
22// This header file has the abstract interfaces only. Concrete implementation classes are declared
23// elsewhere. Implementations _should_ be non-blocking for all methods, especially read() and
24// write(), but this is not enforced. In general, implementations do not need to be multi-thread
25// safe, and any exceptions are noted in the particular implementation.
26
27#include <limits.h>
28#include <stdlib.h>
29#include <utils/RefBase.h>
30
31namespace android {
32
33// In addition to the usual status_t
34enum {
35 NEGOTIATE = 0x80000010, // Must (re-)negotiate format. For negotiate() only, the offeree
36 // doesn't accept offers, and proposes counter-offers
37 OVERRUN = 0x80000011, // availableToRead(), read(), or readVia() detected lost input due
38 // to overrun; an event is counted and the caller should re-try
39 UNDERRUN = 0x80000012, // availableToWrite(), write(), or writeVia() detected a gap in
40 // output due to underrun (not being called often enough, or with
41 // enough data); an event is counted and the caller should re-try
42};
43
44// Negotiation of format is based on the data provider and data sink, or the data consumer and
45// data source, exchanging prioritized arrays of offers and counter-offers until a single offer is
46// mutually agreed upon. Each offer is an NBAIO_Format. For simplicity and performance,
47// NBAIO_Format is an enum that ties together the most important combinations of the various
48// attributes, rather than a struct with separate fields for format, sample rate, channel count,
49// interleave, packing, alignment, etc. The reason is that NBAIO_Format tries to abstract out only
50// the combinations that are actually needed within AudioFligner. If the list of combinations grows
51// too large, then this decision should be re-visited.
52enum NBAIO_Format {
53 Format_Invalid,
54 Format_SR44_1_C2_I16, // 44.1 kHz PCM stereo interleaved 16-bit signed
55 Format_SR48_C2_I16, // 48 kHz PCM stereo interleaved 16-bit signed
56 Format_SR44_1_C1_I16, // 44.1 kHz PCM mono interleaved 16-bit signed
57 Format_SR48_C1_I16, // 48 kHz PCM mono interleaved 16-bit signed
58};
59
60// Return the frame size of an NBAIO_Format in bytes
61size_t Format_frameSize(NBAIO_Format format);
62
63// Return the frame size of an NBAIO_Format as a bit shift
64size_t Format_frameBitShift(NBAIO_Format format);
65
66// Convert a sample rate in Hz and channel count to an NBAIO_Format
67NBAIO_Format Format_from_SR_C(unsigned sampleRate, unsigned channelCount);
68
69// Return the sample rate in Hz of an NBAIO_Format
70unsigned Format_sampleRate(NBAIO_Format format);
71
72// Return the channel count of an NBAIO_Format
73unsigned Format_channelCount(NBAIO_Format format);
74
75// Callbacks used by NBAIO_Sink::writeVia() and NBAIO_Source::readVia() below.
76typedef ssize_t (*writeVia_t)(void *user, void *buffer, size_t count);
77typedef ssize_t (*readVia_t)(void *user, const void *buffer, size_t count);
78
79// Abstract class (interface) representing a data port.
80class NBAIO_Port : public RefBase {
81
82public:
83
84 // negotiate() must called first. The purpose of negotiate() is to check compatibility of
85 // formats, not to automatically adapt if they are incompatible. It's the responsibility of
86 // whoever sets up the graph connections to make sure formats are compatible, and this method
87 // just verifies that. The edges are "dumb" and don't attempt to adapt to bad connections.
88 // How it works: offerer proposes an array of formats, in descending order of preference from
89 // offers[0] to offers[numOffers - 1]. If offeree accepts one of these formats, it returns
90 // the index of that offer. Otherwise, offeree sets numCounterOffers to the number of
91 // counter-offers (up to a maximumum of the entry value of numCounterOffers), fills in the
92 // provided array counterOffers[] with its counter-offers, in descending order of preference
93 // from counterOffers[0] to counterOffers[numCounterOffers - 1], and returns NEGOTIATE.
94 // Note that since the offerer allocates space for counter-offers, but only the offeree knows
95 // how many counter-offers it has, there may be insufficient space for all counter-offers.
96 // In that case, the offeree sets numCounterOffers to the requested number of counter-offers
97 // (which is greater than the entry value of numCounterOffers), fills in as many of the most
98 // important counterOffers as will fit, and returns NEGOTIATE. As this implies a re-allocation,
99 // it should be used as a last resort. It is preferable for the offerer to simply allocate a
100 // larger space to begin with, and/or for the offeree to tolerate a smaller space than desired.
101 // Alternatively, the offerer can pass NULL for offers and counterOffers, and zero for
102 // numOffers. This indicates that it has not allocated space for any counter-offers yet.
103 // In this case, the offerree should set numCounterOffers appropriately and return NEGOTIATE.
104 // Then the offerer will allocate the correct amount of memory and retry.
105 // Format_Invalid is not allowed as either an offer or counter-offer.
106 // Returns:
107 // >= 0 Offer accepted.
108 // NEGOTIATE No offer accepted, and counter-offer(s) optionally made. See above for details.
109 virtual ssize_t negotiate(const NBAIO_Format offers[], size_t numOffers,
110 NBAIO_Format counterOffers[], size_t& numCounterOffers);
111
112 // Return the current negotiated format, or Format_Invalid if negotiation has not been done,
113 // or if re-negotiation is required.
114 virtual NBAIO_Format format() const { return mNegotiated ? mFormat : Format_Invalid; }
115
116protected:
117 NBAIO_Port(NBAIO_Format format) : mNegotiated(false), mFormat(format),
118 mBitShift(Format_frameBitShift(format)) { }
119 virtual ~NBAIO_Port() { }
120
121 // Implementations are free to ignore these if they don't need them
122
123 bool mNegotiated; // mNegotiated implies (mFormat != Format_Invalid)
124 NBAIO_Format mFormat; // (mFormat != Format_Invalid) does not imply mNegotiated
125 size_t mBitShift; // assign in parallel with any assignment to mFormat
126};
127
128// Abstract class (interface) representing a non-blocking data sink, for use by a data provider.
129class NBAIO_Sink : public NBAIO_Port {
130
131public:
132
133 // For the next two APIs:
134 // 32 bits rolls over after 27 hours at 44.1 kHz; if that concerns you then poll periodically.
135
136 // Return the number of frames written successfully since construction.
137 virtual size_t framesWritten() const { return mFramesWritten; }
138
139 // Number of frames lost due to underrun since construction.
140 virtual size_t framesUnderrun() const { return 0; }
141
142 // Number of underruns since construction, where a set of contiguous lost frames is one event.
143 virtual size_t underruns() const { return 0; }
144
145 // Estimate of number of frames that could be written successfully now without blocking.
146 // When a write() is actually attempted, the implementation is permitted to return a smaller or
147 // larger transfer count, however it will make a good faith effort to give an accurate estimate.
148 // Errors:
149 // NEGOTIATE (Re-)negotiation is needed.
150 // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up.
151 // An underrun event is counted, and the caller should re-try this operation.
152 // WOULD_BLOCK Determining how many frames can be written without blocking would itself block.
153 virtual ssize_t availableToWrite() const { return SSIZE_MAX; }
154
155 // Transfer data to sink from single input buffer. Implies a copy.
156 // Inputs:
157 // buffer Non-NULL buffer owned by provider.
158 // count Maximum number of frames to transfer.
159 // Return value:
160 // > 0 Number of frames successfully transferred prior to first error.
161 // = 0 Count was zero.
162 // < 0 status_t error occurred prior to the first frame transfer.
163 // Errors:
164 // NEGOTIATE (Re-)negotiation is needed.
165 // WOULD_BLOCK No frames can be transferred without blocking.
166 // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up.
167 // An underrun event is counted, and the caller should re-try this operation.
168 virtual ssize_t write(const void *buffer, size_t count) = 0;
169
170 // Transfer data to sink using a series of callbacks. More suitable for zero-fill, synthesis,
171 // and non-contiguous transfers (e.g. circular buffer or writev).
172 // Inputs:
173 // via Callback function that the sink will call as many times as needed to consume data.
174 // total Estimate of the number of frames the provider has available. This is an estimate,
175 // and it can provide a different number of frames during the series of callbacks.
176 // user Arbitrary void * reserved for data provider.
177 // block Number of frames per block, that is a suggested value for 'count' in each callback.
178 // Zero means no preference. This parameter is a hint only, and may be ignored.
179 // Return value:
180 // > 0 Total number of frames successfully transferred prior to first error.
181 // = 0 Count was zero.
182 // < 0 status_t error occurred prior to the first frame transfer.
183 // Errors:
184 // NEGOTIATE (Re-)negotiation is needed.
185 // WOULD_BLOCK No frames can be transferred without blocking.
186 // UNDERRUN write() has not been called frequently enough, or with enough frames to keep up.
187 // An underrun event is counted, and the caller should re-try this operation.
188 //
189 // The 'via' callback is called by the data sink as follows:
190 // Inputs:
191 // user Arbitrary void * reserved for data provider.
192 // buffer Non-NULL buffer owned by sink that callback should fill in with data,
193 // up to a maximum of 'count' frames.
194 // count Maximum number of frames to transfer during this callback.
195 // Return value:
196 // > 0 Number of frames successfully transferred during this callback prior to first error.
197 // = 0 Count was zero.
198 // < 0 status_t error occurred prior to the first frame transfer during this callback.
199 virtual ssize_t writeVia(writeVia_t via, size_t total, void *user, size_t block = 0);
200
201protected:
202 NBAIO_Sink(NBAIO_Format format = Format_Invalid) : NBAIO_Port(format), mFramesWritten(0) { }
203 virtual ~NBAIO_Sink() { }
204
205 // Implementations are free to ignore these if they don't need them
206 size_t mFramesWritten;
207};
208
209// Abstract class (interface) representing a non-blocking data source, for use by a data consumer.
210class NBAIO_Source : public NBAIO_Port {
211
212public:
213
214 // For the next two APIs:
215 // 32 bits rolls over after 27 hours at 44.1 kHz; if that concerns you then poll periodically.
216
217 // Number of frames read successfully since construction.
218 virtual size_t framesRead() const { return mFramesRead; }
219
220 // Number of frames lost due to overrun since construction.
221 // Not const because implementations may need to do I/O.
222 virtual size_t framesOverrun() /*const*/ { return 0; }
223
224 // Number of overruns since construction, where a set of contiguous lost frames is one event.
225 // Not const because implementations may need to do I/O.
226 virtual size_t overruns() /*const*/ { return 0; }
227
228 // Estimate of number of frames that could be read successfully now.
229 // When a read() is actually attempted, the implementation is permitted to return a smaller or
230 // larger transfer count, however it will make a good faith effort to give an accurate estimate.
231 // Errors:
232 // NEGOTIATE (Re-)negotiation is needed.
233 // OVERRUN One or more frames were lost due to overrun, try again to read more recent data.
234 // WOULD_BLOCK Determining how many frames can be read without blocking would itself block.
235 virtual ssize_t availableToRead() { return SSIZE_MAX; }
236
237 // Transfer data from source into single destination buffer. Implies a copy.
238 // Inputs:
239 // buffer Non-NULL destination buffer owned by consumer.
240 // count Maximum number of frames to transfer.
241 // Return value:
242 // > 0 Number of frames successfully transferred prior to first error.
243 // = 0 Count was zero.
244 // < 0 status_t error occurred prior to the first frame transfer.
245 // Errors:
246 // NEGOTIATE (Re-)negotiation is needed.
247 // WOULD_BLOCK No frames can be transferred without blocking.
248 // OVERRUN read() has not been called frequently enough, or with enough frames to keep up.
249 // One or more frames were lost due to overrun, try again to read more recent data.
250 virtual ssize_t read(void *buffer, size_t count) = 0;
251
252 // Transfer data from source using a series of callbacks. More suitable for zero-fill,
253 // synthesis, and non-contiguous transfers (e.g. circular buffer or readv).
254 // Inputs:
255 // via Callback function that the source will call as many times as needed to provide data.
256 // total Estimate of the number of frames the consumer desires. This is an estimate,
257 // and it can consume a different number of frames during the series of callbacks.
258 // user Arbitrary void * reserved for data consumer.
259 // block Number of frames per block, that is a suggested value for 'count' in each callback.
260 // Zero means no preference. This parameter is a hint only, and may be ignored.
261 // Return value:
262 // > 0 Total number of frames successfully transferred prior to first error.
263 // = 0 Count was zero.
264 // < 0 status_t error occurred prior to the first frame transfer.
265 // Errors:
266 // NEGOTIATE (Re-)negotiation is needed.
267 // WOULD_BLOCK No frames can be transferred without blocking.
268 // OVERRUN read() has not been called frequently enough, or with enough frames to keep up.
269 // One or more frames were lost due to overrun, try again to read more recent data.
270 //
271 // The 'via' callback is called by the data source as follows:
272 // Inputs:
273 // user Arbitrary void * reserved for data consumer.
274 // dest Non-NULL buffer owned by source that callback should consume data from,
275 // up to a maximum of 'count' frames.
276 // count Maximum number of frames to transfer during this callback.
277 // Return value:
278 // > 0 Number of frames successfully transferred during this callback prior to first error.
279 // = 0 Count was zero.
280 // < 0 status_t error occurred prior to the first frame transfer during this callback.
281 virtual ssize_t readVia(readVia_t via, size_t total, void *user, size_t block = 0);
282
283protected:
284 NBAIO_Source(NBAIO_Format format = Format_Invalid) : NBAIO_Port(format), mFramesRead(0) { }
285 virtual ~NBAIO_Source() { }
286
287 // Implementations are free to ignore these if they don't need them
288 size_t mFramesRead;
289};
290
291} // namespace android
292
293#endif // ANDROID_AUDIO_NBAIO_H