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