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