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