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