Home | History | Annotate | Download | only in media
      1 /*
      2  * Copyright (C) 2007 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_AUDIOTRACK_H
     18 #define ANDROID_AUDIOTRACK_H
     19 
     20 #include <cutils/sched_policy.h>
     21 #include <media/AudioSystem.h>
     22 #include <media/AudioTimestamp.h>
     23 #include <media/IAudioTrack.h>
     24 #include <media/AudioResamplerPublic.h>
     25 #include <utils/threads.h>
     26 
     27 namespace android {
     28 
     29 // ----------------------------------------------------------------------------
     30 
     31 struct audio_track_cblk_t;
     32 class AudioTrackClientProxy;
     33 class StaticAudioTrackClientProxy;
     34 
     35 // ----------------------------------------------------------------------------
     36 
     37 class AudioTrack : public RefBase
     38 {
     39 public:
     40 
     41     /* Events used by AudioTrack callback function (callback_t).
     42      * Keep in sync with frameworks/base/media/java/android/media/AudioTrack.java NATIVE_EVENT_*.
     43      */
     44     enum event_type {
     45         EVENT_MORE_DATA = 0,        // Request to write more data to buffer.
     46                                     // This event only occurs for TRANSFER_CALLBACK.
     47                                     // If this event is delivered but the callback handler
     48                                     // does not want to write more data, the handler must
     49                                     // ignore the event by setting frameCount to zero.
     50                                     // This might occur, for example, if the application is
     51                                     // waiting for source data or is at the end of stream.
     52                                     //
     53                                     // For data filling, it is preferred that the callback
     54                                     // does not block and instead returns a short count on
     55                                     // the amount of data actually delivered
     56                                     // (or 0, if no data is currently available).
     57         EVENT_UNDERRUN = 1,         // Buffer underrun occurred. This will not occur for
     58                                     // static tracks.
     59         EVENT_LOOP_END = 2,         // Sample loop end was reached; playback restarted from
     60                                     // loop start if loop count was not 0 for a static track.
     61         EVENT_MARKER = 3,           // Playback head is at the specified marker position
     62                                     // (See setMarkerPosition()).
     63         EVENT_NEW_POS = 4,          // Playback head is at a new position
     64                                     // (See setPositionUpdatePeriod()).
     65         EVENT_BUFFER_END = 5,       // Playback has completed for a static track.
     66         EVENT_NEW_IAUDIOTRACK = 6,  // IAudioTrack was re-created, either due to re-routing and
     67                                     // voluntary invalidation by mediaserver, or mediaserver crash.
     68         EVENT_STREAM_END = 7,       // Sent after all the buffers queued in AF and HW are played
     69                                     // back (after stop is called) for an offloaded track.
     70 #if 0   // FIXME not yet implemented
     71         EVENT_NEW_TIMESTAMP = 8,    // Delivered periodically and when there's a significant change
     72                                     // in the mapping from frame position to presentation time.
     73                                     // See AudioTimestamp for the information included with event.
     74 #endif
     75     };
     76 
     77     /* Client should declare a Buffer and pass the address to obtainBuffer()
     78      * and releaseBuffer().  See also callback_t for EVENT_MORE_DATA.
     79      */
     80 
     81     class Buffer
     82     {
     83     public:
     84         // FIXME use m prefix
     85         size_t      frameCount;   // number of sample frames corresponding to size;
     86                                   // on input to obtainBuffer() it is the number of frames desired,
     87                                   // on output from obtainBuffer() it is the number of available
     88                                   //    [empty slots for] frames to be filled
     89                                   // on input to releaseBuffer() it is currently ignored
     90 
     91         size_t      size;         // input/output in bytes == frameCount * frameSize
     92                                   // on input to obtainBuffer() it is ignored
     93                                   // on output from obtainBuffer() it is the number of available
     94                                   //    [empty slots for] bytes to be filled,
     95                                   //    which is frameCount * frameSize
     96                                   // on input to releaseBuffer() it is the number of bytes to
     97                                   //    release
     98                                   // FIXME This is redundant with respect to frameCount.  Consider
     99                                   //    removing size and making frameCount the primary field.
    100 
    101         union {
    102             void*       raw;
    103             short*      i16;      // signed 16-bit
    104             int8_t*     i8;       // unsigned 8-bit, offset by 0x80
    105         };                        // input to obtainBuffer(): unused, output: pointer to buffer
    106     };
    107 
    108     /* As a convenience, if a callback is supplied, a handler thread
    109      * is automatically created with the appropriate priority. This thread
    110      * invokes the callback when a new buffer becomes available or various conditions occur.
    111      * Parameters:
    112      *
    113      * event:   type of event notified (see enum AudioTrack::event_type).
    114      * user:    Pointer to context for use by the callback receiver.
    115      * info:    Pointer to optional parameter according to event type:
    116      *          - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
    117      *            more bytes than indicated by 'size' field and update 'size' if fewer bytes are
    118      *            written.
    119      *          - EVENT_UNDERRUN: unused.
    120      *          - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
    121      *          - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames.
    122      *          - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames.
    123      *          - EVENT_BUFFER_END: unused.
    124      *          - EVENT_NEW_IAUDIOTRACK: unused.
    125      *          - EVENT_STREAM_END: unused.
    126      *          - EVENT_NEW_TIMESTAMP: pointer to const AudioTimestamp.
    127      */
    128 
    129     typedef void (*callback_t)(int event, void* user, void *info);
    130 
    131     /* Returns the minimum frame count required for the successful creation of
    132      * an AudioTrack object.
    133      * Returned status (from utils/Errors.h) can be:
    134      *  - NO_ERROR: successful operation
    135      *  - NO_INIT: audio server or audio hardware not initialized
    136      *  - BAD_VALUE: unsupported configuration
    137      * frameCount is guaranteed to be non-zero if status is NO_ERROR,
    138      * and is undefined otherwise.
    139      * FIXME This API assumes a route, and so should be deprecated.
    140      */
    141 
    142     static status_t getMinFrameCount(size_t* frameCount,
    143                                      audio_stream_type_t streamType,
    144                                      uint32_t sampleRate);
    145 
    146     /* How data is transferred to AudioTrack
    147      */
    148     enum transfer_type {
    149         TRANSFER_DEFAULT,   // not specified explicitly; determine from the other parameters
    150         TRANSFER_CALLBACK,  // callback EVENT_MORE_DATA
    151         TRANSFER_OBTAIN,    // call obtainBuffer() and releaseBuffer()
    152         TRANSFER_SYNC,      // synchronous write()
    153         TRANSFER_SHARED,    // shared memory
    154     };
    155 
    156     /* Constructs an uninitialized AudioTrack. No connection with
    157      * AudioFlinger takes place.  Use set() after this.
    158      */
    159                         AudioTrack();
    160 
    161     /* Creates an AudioTrack object and registers it with AudioFlinger.
    162      * Once created, the track needs to be started before it can be used.
    163      * Unspecified values are set to appropriate default values.
    164      *
    165      * Parameters:
    166      *
    167      * streamType:         Select the type of audio stream this track is attached to
    168      *                     (e.g. AUDIO_STREAM_MUSIC).
    169      * sampleRate:         Data source sampling rate in Hz.
    170      * format:             Audio format. For mixed tracks, any PCM format supported by server is OK.
    171      *                     For direct and offloaded tracks, the possible format(s) depends on the
    172      *                     output sink.
    173      * channelMask:        Channel mask, such that audio_is_output_channel(channelMask) is true.
    174      * frameCount:         Minimum size of track PCM buffer in frames. This defines the
    175      *                     application's contribution to the
    176      *                     latency of the track. The actual size selected by the AudioTrack could be
    177      *                     larger if the requested size is not compatible with current audio HAL
    178      *                     configuration.  Zero means to use a default value.
    179      * flags:              See comments on audio_output_flags_t in <system/audio.h>.
    180      * cbf:                Callback function. If not null, this function is called periodically
    181      *                     to provide new data in TRANSFER_CALLBACK mode
    182      *                     and inform of marker, position updates, etc.
    183      * user:               Context for use by the callback receiver.
    184      * notificationFrames: The callback function is called each time notificationFrames PCM
    185      *                     frames have been consumed from track input buffer.
    186      *                     This is expressed in units of frames at the initial source sample rate.
    187      * sessionId:          Specific session ID, or zero to use default.
    188      * transferType:       How data is transferred to AudioTrack.
    189      * offloadInfo:        If not NULL, provides offload parameters for
    190      *                     AudioSystem::getOutputForAttr().
    191      * uid:                User ID of the app which initially requested this AudioTrack
    192      *                     for power management tracking, or -1 for current user ID.
    193      * pid:                Process ID of the app which initially requested this AudioTrack
    194      *                     for power management tracking, or -1 for current process ID.
    195      * pAttributes:        If not NULL, supersedes streamType for use case selection.
    196      * doNotReconnect:     If set to true, AudioTrack won't automatically recreate the IAudioTrack
    197                            binder to AudioFlinger.
    198                            It will return an error instead.  The application will recreate
    199                            the track based on offloading or different channel configuration, etc.
    200      * threadCanCallJava:  Not present in parameter list, and so is fixed at false.
    201      */
    202 
    203                         AudioTrack( audio_stream_type_t streamType,
    204                                     uint32_t sampleRate,
    205                                     audio_format_t format,
    206                                     audio_channel_mask_t channelMask,
    207                                     size_t frameCount    = 0,
    208                                     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
    209                                     callback_t cbf       = NULL,
    210                                     void* user           = NULL,
    211                                     uint32_t notificationFrames = 0,
    212                                     int sessionId        = AUDIO_SESSION_ALLOCATE,
    213                                     transfer_type transferType = TRANSFER_DEFAULT,
    214                                     const audio_offload_info_t *offloadInfo = NULL,
    215                                     int uid = -1,
    216                                     pid_t pid = -1,
    217                                     const audio_attributes_t* pAttributes = NULL,
    218                                     bool doNotReconnect = false);
    219 
    220     /* Creates an audio track and registers it with AudioFlinger.
    221      * With this constructor, the track is configured for static buffer mode.
    222      * Data to be rendered is passed in a shared memory buffer
    223      * identified by the argument sharedBuffer, which should be non-0.
    224      * If sharedBuffer is zero, this constructor is equivalent to the previous constructor
    225      * but without the ability to specify a non-zero value for the frameCount parameter.
    226      * The memory should be initialized to the desired data before calling start().
    227      * The write() method is not supported in this case.
    228      * It is recommended to pass a callback function to be notified of playback end by an
    229      * EVENT_UNDERRUN event.
    230      */
    231 
    232                         AudioTrack( audio_stream_type_t streamType,
    233                                     uint32_t sampleRate,
    234                                     audio_format_t format,
    235                                     audio_channel_mask_t channelMask,
    236                                     const sp<IMemory>& sharedBuffer,
    237                                     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
    238                                     callback_t cbf      = NULL,
    239                                     void* user          = NULL,
    240                                     uint32_t notificationFrames = 0,
    241                                     int sessionId       = AUDIO_SESSION_ALLOCATE,
    242                                     transfer_type transferType = TRANSFER_DEFAULT,
    243                                     const audio_offload_info_t *offloadInfo = NULL,
    244                                     int uid = -1,
    245                                     pid_t pid = -1,
    246                                     const audio_attributes_t* pAttributes = NULL,
    247                                     bool doNotReconnect = false);
    248 
    249     /* Terminates the AudioTrack and unregisters it from AudioFlinger.
    250      * Also destroys all resources associated with the AudioTrack.
    251      */
    252 protected:
    253                         virtual ~AudioTrack();
    254 public:
    255 
    256     /* Initialize an AudioTrack that was created using the AudioTrack() constructor.
    257      * Don't call set() more than once, or after the AudioTrack() constructors that take parameters.
    258      * set() is not multi-thread safe.
    259      * Returned status (from utils/Errors.h) can be:
    260      *  - NO_ERROR: successful initialization
    261      *  - INVALID_OPERATION: AudioTrack is already initialized
    262      *  - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...)
    263      *  - NO_INIT: audio server or audio hardware not initialized
    264      * If status is not equal to NO_ERROR, don't call any other APIs on this AudioTrack.
    265      * If sharedBuffer is non-0, the frameCount parameter is ignored and
    266      * replaced by the shared buffer's total allocated size in frame units.
    267      *
    268      * Parameters not listed in the AudioTrack constructors above:
    269      *
    270      * threadCanCallJava:  Whether callbacks are made from an attached thread and thus can call JNI.
    271      *
    272      * Internal state post condition:
    273      *      (mStreamType == AUDIO_STREAM_DEFAULT) implies this AudioTrack has valid attributes
    274      */
    275             status_t    set(audio_stream_type_t streamType,
    276                             uint32_t sampleRate,
    277                             audio_format_t format,
    278                             audio_channel_mask_t channelMask,
    279                             size_t frameCount   = 0,
    280                             audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
    281                             callback_t cbf      = NULL,
    282                             void* user          = NULL,
    283                             uint32_t notificationFrames = 0,
    284                             const sp<IMemory>& sharedBuffer = 0,
    285                             bool threadCanCallJava = false,
    286                             int sessionId       = AUDIO_SESSION_ALLOCATE,
    287                             transfer_type transferType = TRANSFER_DEFAULT,
    288                             const audio_offload_info_t *offloadInfo = NULL,
    289                             int uid = -1,
    290                             pid_t pid = -1,
    291                             const audio_attributes_t* pAttributes = NULL,
    292                             bool doNotReconnect = false);
    293 
    294     /* Result of constructing the AudioTrack. This must be checked for successful initialization
    295      * before using any AudioTrack API (except for set()), because using
    296      * an uninitialized AudioTrack produces undefined results.
    297      * See set() method above for possible return codes.
    298      */
    299             status_t    initCheck() const   { return mStatus; }
    300 
    301     /* Returns this track's estimated latency in milliseconds.
    302      * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
    303      * and audio hardware driver.
    304      */
    305             uint32_t    latency() const     { return mLatency; }
    306 
    307     /* getters, see constructors and set() */
    308 
    309             audio_stream_type_t streamType() const;
    310             audio_format_t format() const   { return mFormat; }
    311 
    312     /* Return frame size in bytes, which for linear PCM is
    313      * channelCount * (bit depth per channel / 8).
    314      * channelCount is determined from channelMask, and bit depth comes from format.
    315      * For non-linear formats, the frame size is typically 1 byte.
    316      */
    317             size_t      frameSize() const   { return mFrameSize; }
    318 
    319             uint32_t    channelCount() const { return mChannelCount; }
    320             size_t      frameCount() const  { return mFrameCount; }
    321 
    322     /* Return the static buffer specified in constructor or set(), or 0 for streaming mode */
    323             sp<IMemory> sharedBuffer() const { return mSharedBuffer; }
    324 
    325     /* After it's created the track is not active. Call start() to
    326      * make it active. If set, the callback will start being called.
    327      * If the track was previously paused, volume is ramped up over the first mix buffer.
    328      */
    329             status_t        start();
    330 
    331     /* Stop a track.
    332      * In static buffer mode, the track is stopped immediately.
    333      * In streaming mode, the callback will cease being called.  Note that obtainBuffer() still
    334      * works and will fill up buffers until the pool is exhausted, and then will return WOULD_BLOCK.
    335      * In streaming mode the stop does not occur immediately: any data remaining in the buffer
    336      * is first drained, mixed, and output, and only then is the track marked as stopped.
    337      */
    338             void        stop();
    339             bool        stopped() const;
    340 
    341     /* Flush a stopped or paused track. All previously buffered data is discarded immediately.
    342      * This has the effect of draining the buffers without mixing or output.
    343      * Flush is intended for streaming mode, for example before switching to non-contiguous content.
    344      * This function is a no-op if the track is not stopped or paused, or uses a static buffer.
    345      */
    346             void        flush();
    347 
    348     /* Pause a track. After pause, the callback will cease being called and
    349      * obtainBuffer returns WOULD_BLOCK. Note that obtainBuffer() still works
    350      * and will fill up buffers until the pool is exhausted.
    351      * Volume is ramped down over the next mix buffer following the pause request,
    352      * and then the track is marked as paused.  It can be resumed with ramp up by start().
    353      */
    354             void        pause();
    355 
    356     /* Set volume for this track, mostly used for games' sound effects
    357      * left and right volumes. Levels must be >= 0.0 and <= 1.0.
    358      * This is the older API.  New applications should use setVolume(float) when possible.
    359      */
    360             status_t    setVolume(float left, float right);
    361 
    362     /* Set volume for all channels.  This is the preferred API for new applications,
    363      * especially for multi-channel content.
    364      */
    365             status_t    setVolume(float volume);
    366 
    367     /* Set the send level for this track. An auxiliary effect should be attached
    368      * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0.
    369      */
    370             status_t    setAuxEffectSendLevel(float level);
    371             void        getAuxEffectSendLevel(float* level) const;
    372 
    373     /* Set source sample rate for this track in Hz, mostly used for games' sound effects
    374      */
    375             status_t    setSampleRate(uint32_t sampleRate);
    376 
    377     /* Return current source sample rate in Hz */
    378             uint32_t    getSampleRate() const;
    379 
    380     /* Return the original source sample rate in Hz. This corresponds to the sample rate
    381      * if playback rate had normal speed and pitch.
    382      */
    383             uint32_t    getOriginalSampleRate() const;
    384 
    385     /* Set source playback rate for timestretch
    386      * 1.0 is normal speed: < 1.0 is slower, > 1.0 is faster
    387      * 1.0 is normal pitch: < 1.0 is lower pitch, > 1.0 is higher pitch
    388      *
    389      * AUDIO_TIMESTRETCH_SPEED_MIN <= speed <= AUDIO_TIMESTRETCH_SPEED_MAX
    390      * AUDIO_TIMESTRETCH_PITCH_MIN <= pitch <= AUDIO_TIMESTRETCH_PITCH_MAX
    391      *
    392      * Speed increases the playback rate of media, but does not alter pitch.
    393      * Pitch increases the "tonal frequency" of media, but does not affect the playback rate.
    394      */
    395             status_t    setPlaybackRate(const AudioPlaybackRate &playbackRate);
    396 
    397     /* Return current playback rate */
    398             const AudioPlaybackRate& getPlaybackRate() const;
    399 
    400     /* Enables looping and sets the start and end points of looping.
    401      * Only supported for static buffer mode.
    402      *
    403      * Parameters:
    404      *
    405      * loopStart:   loop start in frames relative to start of buffer.
    406      * loopEnd:     loop end in frames relative to start of buffer.
    407      * loopCount:   number of loops to execute. Calling setLoop() with loopCount == 0 cancels any
    408      *              pending or active loop. loopCount == -1 means infinite looping.
    409      *
    410      * For proper operation the following condition must be respected:
    411      *      loopCount != 0 implies 0 <= loopStart < loopEnd <= frameCount().
    412      *
    413      * If the loop period (loopEnd - loopStart) is too small for the implementation to support,
    414      * setLoop() will return BAD_VALUE.  loopCount must be >= -1.
    415      *
    416      */
    417             status_t    setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
    418 
    419     /* Sets marker position. When playback reaches the number of frames specified, a callback with
    420      * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker
    421      * notification callback.  To set a marker at a position which would compute as 0,
    422      * a workaround is to set the marker at a nearby position such as ~0 or 1.
    423      * If the AudioTrack has been opened with no callback function associated, the operation will
    424      * fail.
    425      *
    426      * Parameters:
    427      *
    428      * marker:   marker position expressed in wrapping (overflow) frame units,
    429      *           like the return value of getPosition().
    430      *
    431      * Returned status (from utils/Errors.h) can be:
    432      *  - NO_ERROR: successful operation
    433      *  - INVALID_OPERATION: the AudioTrack has no callback installed.
    434      */
    435             status_t    setMarkerPosition(uint32_t marker);
    436             status_t    getMarkerPosition(uint32_t *marker) const;
    437 
    438     /* Sets position update period. Every time the number of frames specified has been played,
    439      * a callback with event type EVENT_NEW_POS is called.
    440      * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
    441      * callback.
    442      * If the AudioTrack has been opened with no callback function associated, the operation will
    443      * fail.
    444      * Extremely small values may be rounded up to a value the implementation can support.
    445      *
    446      * Parameters:
    447      *
    448      * updatePeriod:  position update notification period expressed in frames.
    449      *
    450      * Returned status (from utils/Errors.h) can be:
    451      *  - NO_ERROR: successful operation
    452      *  - INVALID_OPERATION: the AudioTrack has no callback installed.
    453      */
    454             status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
    455             status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
    456 
    457     /* Sets playback head position.
    458      * Only supported for static buffer mode.
    459      *
    460      * Parameters:
    461      *
    462      * position:  New playback head position in frames relative to start of buffer.
    463      *            0 <= position <= frameCount().  Note that end of buffer is permitted,
    464      *            but will result in an immediate underrun if started.
    465      *
    466      * Returned status (from utils/Errors.h) can be:
    467      *  - NO_ERROR: successful operation
    468      *  - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode.
    469      *  - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack
    470      *               buffer
    471      */
    472             status_t    setPosition(uint32_t position);
    473 
    474     /* Return the total number of frames played since playback start.
    475      * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
    476      * It is reset to zero by flush(), reload(), and stop().
    477      *
    478      * Parameters:
    479      *
    480      *  position:  Address where to return play head position.
    481      *
    482      * Returned status (from utils/Errors.h) can be:
    483      *  - NO_ERROR: successful operation
    484      *  - BAD_VALUE:  position is NULL
    485      */
    486             status_t    getPosition(uint32_t *position);
    487 
    488     /* For static buffer mode only, this returns the current playback position in frames
    489      * relative to start of buffer.  It is analogous to the position units used by
    490      * setLoop() and setPosition().  After underrun, the position will be at end of buffer.
    491      */
    492             status_t    getBufferPosition(uint32_t *position);
    493 
    494     /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
    495      * rewriting the buffer before restarting playback after a stop.
    496      * This method must be called with the AudioTrack in paused or stopped state.
    497      * Not allowed in streaming mode.
    498      *
    499      * Returned status (from utils/Errors.h) can be:
    500      *  - NO_ERROR: successful operation
    501      *  - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode.
    502      */
    503             status_t    reload();
    504 
    505     /* Returns a handle on the audio output used by this AudioTrack.
    506      *
    507      * Parameters:
    508      *  none.
    509      *
    510      * Returned value:
    511      *  handle on audio hardware output, or AUDIO_IO_HANDLE_NONE if the
    512      *  track needed to be re-created but that failed
    513      */
    514 private:
    515             audio_io_handle_t    getOutput() const;
    516 public:
    517 
    518     /* Selects the audio device to use for output of this AudioTrack. A value of
    519      * AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing.
    520      *
    521      * Parameters:
    522      *  The device ID of the selected device (as returned by the AudioDevicesManager API).
    523      *
    524      * Returned value:
    525      *  - NO_ERROR: successful operation
    526      *    TODO: what else can happen here?
    527      */
    528             status_t    setOutputDevice(audio_port_handle_t deviceId);
    529 
    530     /* Returns the ID of the audio device selected for this AudioTrack.
    531      * A value of AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing.
    532      *
    533      * Parameters:
    534      *  none.
    535      */
    536      audio_port_handle_t getOutputDevice();
    537 
    538      /* Returns the ID of the audio device actually used by the output to which this AudioTrack is
    539       * attached.
    540       * A value of AUDIO_PORT_HANDLE_NONE indicates the audio track is not attached to any output.
    541       *
    542       * Parameters:
    543       *  none.
    544       */
    545      audio_port_handle_t getRoutedDeviceId();
    546 
    547     /* Returns the unique session ID associated with this track.
    548      *
    549      * Parameters:
    550      *  none.
    551      *
    552      * Returned value:
    553      *  AudioTrack session ID.
    554      */
    555             int    getSessionId() const { return mSessionId; }
    556 
    557     /* Attach track auxiliary output to specified effect. Use effectId = 0
    558      * to detach track from effect.
    559      *
    560      * Parameters:
    561      *
    562      * effectId:  effectId obtained from AudioEffect::id().
    563      *
    564      * Returned status (from utils/Errors.h) can be:
    565      *  - NO_ERROR: successful operation
    566      *  - INVALID_OPERATION: the effect is not an auxiliary effect.
    567      *  - BAD_VALUE: The specified effect ID is invalid
    568      */
    569             status_t    attachAuxEffect(int effectId);
    570 
    571     /* Public API for TRANSFER_OBTAIN mode.
    572      * Obtains a buffer of up to "audioBuffer->frameCount" empty slots for frames.
    573      * After filling these slots with data, the caller should release them with releaseBuffer().
    574      * If the track buffer is not full, obtainBuffer() returns as many contiguous
    575      * [empty slots for] frames as are available immediately.
    576      *
    577      * If nonContig is non-NULL, it is an output parameter that will be set to the number of
    578      * additional non-contiguous frames that are predicted to be available immediately,
    579      * if the client were to release the first frames and then call obtainBuffer() again.
    580      * This value is only a prediction, and needs to be confirmed.
    581      * It will be set to zero for an error return.
    582      *
    583      * If the track buffer is full and track is stopped, obtainBuffer() returns WOULD_BLOCK
    584      * regardless of the value of waitCount.
    585      * If the track buffer is full and track is not stopped, obtainBuffer() blocks with a
    586      * maximum timeout based on waitCount; see chart below.
    587      * Buffers will be returned until the pool
    588      * is exhausted, at which point obtainBuffer() will either block
    589      * or return WOULD_BLOCK depending on the value of the "waitCount"
    590      * parameter.
    591      *
    592      * Interpretation of waitCount:
    593      *  +n  limits wait time to n * WAIT_PERIOD_MS,
    594      *  -1  causes an (almost) infinite wait time,
    595      *   0  non-blocking.
    596      *
    597      * Buffer fields
    598      * On entry:
    599      *  frameCount  number of [empty slots for] frames requested
    600      *  size        ignored
    601      *  raw         ignored
    602      * After error return:
    603      *  frameCount  0
    604      *  size        0
    605      *  raw         undefined
    606      * After successful return:
    607      *  frameCount  actual number of [empty slots for] frames available, <= number requested
    608      *  size        actual number of bytes available
    609      *  raw         pointer to the buffer
    610      */
    611             status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount,
    612                                 size_t *nonContig = NULL);
    613 
    614 private:
    615     /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
    616      * additional non-contiguous frames that are predicted to be available immediately,
    617      * if the client were to release the first frames and then call obtainBuffer() again.
    618      * This value is only a prediction, and needs to be confirmed.
    619      * It will be set to zero for an error return.
    620      * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
    621      * in case the requested amount of frames is in two or more non-contiguous regions.
    622      * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
    623      */
    624             status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
    625                                      struct timespec *elapsed = NULL, size_t *nonContig = NULL);
    626 public:
    627 
    628     /* Public API for TRANSFER_OBTAIN mode.
    629      * Release a filled buffer of frames for AudioFlinger to process.
    630      *
    631      * Buffer fields:
    632      *  frameCount  currently ignored but recommend to set to actual number of frames filled
    633      *  size        actual number of bytes filled, must be multiple of frameSize
    634      *  raw         ignored
    635      */
    636             void        releaseBuffer(const Buffer* audioBuffer);
    637 
    638     /* As a convenience we provide a write() interface to the audio buffer.
    639      * Input parameter 'size' is in byte units.
    640      * This is implemented on top of obtainBuffer/releaseBuffer. For best
    641      * performance use callbacks. Returns actual number of bytes written >= 0,
    642      * or one of the following negative status codes:
    643      *      INVALID_OPERATION   AudioTrack is configured for static buffer or streaming mode
    644      *      BAD_VALUE           size is invalid
    645      *      WOULD_BLOCK         when obtainBuffer() returns same, or
    646      *                          AudioTrack was stopped during the write
    647      *      DEAD_OBJECT         when AudioFlinger dies or the output device changes and
    648      *                          the track cannot be automatically restored.
    649      *                          The application needs to recreate the AudioTrack
    650      *                          because the audio device changed or AudioFlinger died.
    651      *                          This typically occurs for direct or offload tracks
    652      *                          or if mDoNotReconnect is true.
    653      *      or any other error code returned by IAudioTrack::start() or restoreTrack_l().
    654      * Default behavior is to only return when all data has been transferred. Set 'blocking' to
    655      * false for the method to return immediately without waiting to try multiple times to write
    656      * the full content of the buffer.
    657      */
    658             ssize_t     write(const void* buffer, size_t size, bool blocking = true);
    659 
    660     /*
    661      * Dumps the state of an audio track.
    662      * Not a general-purpose API; intended only for use by media player service to dump its tracks.
    663      */
    664             status_t    dump(int fd, const Vector<String16>& args) const;
    665 
    666     /*
    667      * Return the total number of frames which AudioFlinger desired but were unavailable,
    668      * and thus which resulted in an underrun.  Reset to zero by stop().
    669      */
    670             uint32_t    getUnderrunFrames() const;
    671 
    672     /* Get the flags */
    673             audio_output_flags_t getFlags() const { AutoMutex _l(mLock); return mFlags; }
    674 
    675     /* Set parameters - only possible when using direct output */
    676             status_t    setParameters(const String8& keyValuePairs);
    677 
    678     /* Get parameters */
    679             String8     getParameters(const String8& keys);
    680 
    681     /* Poll for a timestamp on demand.
    682      * Use if EVENT_NEW_TIMESTAMP is not delivered often enough for your needs,
    683      * or if you need to get the most recent timestamp outside of the event callback handler.
    684      * Caution: calling this method too often may be inefficient;
    685      * if you need a high resolution mapping between frame position and presentation time,
    686      * consider implementing that at application level, based on the low resolution timestamps.
    687      * Returns NO_ERROR    if timestamp is valid.
    688      *         WOULD_BLOCK if called in STOPPED or FLUSHED state, or if called immediately after
    689      *                     start/ACTIVE, when the number of frames consumed is less than the
    690      *                     overall hardware latency to physical output. In WOULD_BLOCK cases,
    691      *                     one might poll again, or use getPosition(), or use 0 position and
    692      *                     current time for the timestamp.
    693      *         DEAD_OBJECT if AudioFlinger dies or the output device changes and
    694      *                     the track cannot be automatically restored.
    695      *                     The application needs to recreate the AudioTrack
    696      *                     because the audio device changed or AudioFlinger died.
    697      *                     This typically occurs for direct or offload tracks
    698      *                     or if mDoNotReconnect is true.
    699      *         INVALID_OPERATION  if called on a FastTrack, wrong state, or some other error.
    700      *
    701      * The timestamp parameter is undefined on return, if status is not NO_ERROR.
    702      */
    703             status_t    getTimestamp(AudioTimestamp& timestamp);
    704 
    705     /* Add an AudioDeviceCallback. The caller will be notified when the audio device to which this
    706      * AudioTrack is routed is updated.
    707      * Replaces any previously installed callback.
    708      * Parameters:
    709      *  callback:  The callback interface
    710      * Returns NO_ERROR if successful.
    711      *         INVALID_OPERATION if the same callback is already installed.
    712      *         NO_INIT or PREMISSION_DENIED if AudioFlinger service is not reachable
    713      *         BAD_VALUE if the callback is NULL
    714      */
    715             status_t addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback);
    716 
    717     /* remove an AudioDeviceCallback.
    718      * Parameters:
    719      *  callback:  The callback interface
    720      * Returns NO_ERROR if successful.
    721      *         INVALID_OPERATION if the callback is not installed
    722      *         BAD_VALUE if the callback is NULL
    723      */
    724             status_t removeAudioDeviceCallback(
    725                     const sp<AudioSystem::AudioDeviceCallback>& callback);
    726 
    727 protected:
    728     /* copying audio tracks is not allowed */
    729                         AudioTrack(const AudioTrack& other);
    730             AudioTrack& operator = (const AudioTrack& other);
    731 
    732     /* a small internal class to handle the callback */
    733     class AudioTrackThread : public Thread
    734     {
    735     public:
    736         AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
    737 
    738         // Do not call Thread::requestExitAndWait() without first calling requestExit().
    739         // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
    740         virtual void        requestExit();
    741 
    742                 void        pause();    // suspend thread from execution at next loop boundary
    743                 void        resume();   // allow thread to execute, if not requested to exit
    744                 void        wake();     // wake to handle changed notification conditions.
    745 
    746     private:
    747                 void        pauseInternal(nsecs_t ns = 0LL);
    748                                         // like pause(), but only used internally within thread
    749 
    750         friend class AudioTrack;
    751         virtual bool        threadLoop();
    752         AudioTrack&         mReceiver;
    753         virtual ~AudioTrackThread();
    754         Mutex               mMyLock;    // Thread::mLock is private
    755         Condition           mMyCond;    // Thread::mThreadExitedCondition is private
    756         bool                mPaused;    // whether thread is requested to pause at next loop entry
    757         bool                mPausedInt; // whether thread internally requests pause
    758         nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
    759         bool                mIgnoreNextPausedInt;   // skip any internal pause and go immediately
    760                                         // to processAudioBuffer() as state may have changed
    761                                         // since pause time calculated.
    762     };
    763 
    764             // body of AudioTrackThread::threadLoop()
    765             // returns the maximum amount of time before we would like to run again, where:
    766             //      0           immediately
    767             //      > 0         no later than this many nanoseconds from now
    768             //      NS_WHENEVER still active but no particular deadline
    769             //      NS_INACTIVE inactive so don't run again until re-started
    770             //      NS_NEVER    never again
    771             static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
    772             nsecs_t processAudioBuffer();
    773 
    774             // caller must hold lock on mLock for all _l methods
    775 
    776             status_t createTrack_l();
    777 
    778             // can only be called when mState != STATE_ACTIVE
    779             void flush_l();
    780 
    781             void setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
    782 
    783             // FIXME enum is faster than strcmp() for parameter 'from'
    784             status_t restoreTrack_l(const char *from);
    785 
    786             bool     isOffloaded() const;
    787             bool     isDirect() const;
    788             bool     isOffloadedOrDirect() const;
    789 
    790             bool     isOffloaded_l() const
    791                 { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; }
    792 
    793             bool     isOffloadedOrDirect_l() const
    794                 { return (mFlags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD|
    795                                                 AUDIO_OUTPUT_FLAG_DIRECT)) != 0; }
    796 
    797             bool     isDirect_l() const
    798                 { return (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0; }
    799 
    800             // increment mPosition by the delta of mServer, and return new value of mPosition
    801             uint32_t updateAndGetPosition_l();
    802 
    803             // check sample rate and speed is compatible with AudioTrack
    804             bool     isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const;
    805 
    806     // Next 4 fields may be changed if IAudioTrack is re-created, but always != 0
    807     sp<IAudioTrack>         mAudioTrack;
    808     sp<IMemory>             mCblkMemory;
    809     audio_track_cblk_t*     mCblk;                  // re-load after mLock.unlock()
    810     audio_io_handle_t       mOutput;                // returned by AudioSystem::getOutput()
    811 
    812     sp<AudioTrackThread>    mAudioTrackThread;
    813 
    814     float                   mVolume[2];
    815     float                   mSendLevel;
    816     mutable uint32_t        mSampleRate;            // mutable because getSampleRate() can update it
    817     uint32_t                mOriginalSampleRate;
    818     AudioPlaybackRate       mPlaybackRate;
    819     size_t                  mFrameCount;            // corresponds to current IAudioTrack, value is
    820                                                     // reported back by AudioFlinger to the client
    821     size_t                  mReqFrameCount;         // frame count to request the first or next time
    822                                                     // a new IAudioTrack is needed, non-decreasing
    823 
    824     // The following AudioFlinger server-side values are cached in createAudioTrack_l().
    825     // These values can be used for informational purposes until the track is invalidated,
    826     // whereupon restoreTrack_l() calls createTrack_l() to update the values.
    827     uint32_t                mAfLatency;             // AudioFlinger latency in ms
    828     size_t                  mAfFrameCount;          // AudioFlinger frame count
    829     uint32_t                mAfSampleRate;          // AudioFlinger sample rate
    830 
    831     // constant after constructor or set()
    832     audio_format_t          mFormat;                // as requested by client, not forced to 16-bit
    833     audio_stream_type_t     mStreamType;            // mStreamType == AUDIO_STREAM_DEFAULT implies
    834                                                     // this AudioTrack has valid attributes
    835     uint32_t                mChannelCount;
    836     audio_channel_mask_t    mChannelMask;
    837     sp<IMemory>             mSharedBuffer;
    838     transfer_type           mTransfer;
    839     audio_offload_info_t    mOffloadInfoCopy;
    840     const audio_offload_info_t* mOffloadInfo;
    841     audio_attributes_t      mAttributes;
    842 
    843     size_t                  mFrameSize;             // frame size in bytes
    844 
    845     status_t                mStatus;
    846 
    847     // can change dynamically when IAudioTrack invalidated
    848     uint32_t                mLatency;               // in ms
    849 
    850     // Indicates the current track state.  Protected by mLock.
    851     enum State {
    852         STATE_ACTIVE,
    853         STATE_STOPPED,
    854         STATE_PAUSED,
    855         STATE_PAUSED_STOPPING,
    856         STATE_FLUSHED,
    857         STATE_STOPPING,
    858     }                       mState;
    859 
    860     // for client callback handler
    861     callback_t              mCbf;                   // callback handler for events, or NULL
    862     void*                   mUserData;
    863 
    864     // for notification APIs
    865     uint32_t                mNotificationFramesReq; // requested number of frames between each
    866                                                     // notification callback,
    867                                                     // at initial source sample rate
    868     uint32_t                mNotificationFramesAct; // actual number of frames between each
    869                                                     // notification callback,
    870                                                     // at initial source sample rate
    871     bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
    872                                                     // mRemainingFrames and mRetryOnPartialBuffer
    873 
    874                                                     // used for static track cbf and restoration
    875     int32_t                 mLoopCount;             // last setLoop loopCount; zero means disabled
    876     uint32_t                mLoopStart;             // last setLoop loopStart
    877     uint32_t                mLoopEnd;               // last setLoop loopEnd
    878     int32_t                 mLoopCountNotified;     // the last loopCount notified by callback.
    879                                                     // mLoopCountNotified counts down, matching
    880                                                     // the remaining loop count for static track
    881                                                     // playback.
    882 
    883     // These are private to processAudioBuffer(), and are not protected by a lock
    884     uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
    885     bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
    886     uint32_t                mObservedSequence;      // last observed value of mSequence
    887 
    888     uint32_t                mMarkerPosition;        // in wrapping (overflow) frame units
    889     bool                    mMarkerReached;
    890     uint32_t                mNewPosition;           // in frames
    891     uint32_t                mUpdatePeriod;          // in frames, zero means no EVENT_NEW_POS
    892 
    893     uint32_t                mServer;                // in frames, last known mProxy->getPosition()
    894                                                     // which is count of frames consumed by server,
    895                                                     // reset by new IAudioTrack,
    896                                                     // whether it is reset by stop() is TBD
    897     uint32_t                mPosition;              // in frames, like mServer except continues
    898                                                     // monotonically after new IAudioTrack,
    899                                                     // and could be easily widened to uint64_t
    900     uint32_t                mReleased;              // in frames, count of frames released to server
    901                                                     // but not necessarily consumed by server,
    902                                                     // reset by stop() but continues monotonically
    903                                                     // after new IAudioTrack to restore mPosition,
    904                                                     // and could be easily widened to uint64_t
    905     int64_t                 mStartUs;               // the start time after flush or stop.
    906                                                     // only used for offloaded and direct tracks.
    907 
    908     bool                    mPreviousTimestampValid;// true if mPreviousTimestamp is valid
    909     bool                    mTimestampStartupGlitchReported; // reduce log spam
    910     bool                    mRetrogradeMotionReported; // reduce log spam
    911     AudioTimestamp          mPreviousTimestamp;     // used to detect retrograde motion
    912 
    913     audio_output_flags_t    mFlags;
    914         // const after set(), except for bits AUDIO_OUTPUT_FLAG_FAST and AUDIO_OUTPUT_FLAG_OFFLOAD.
    915         // mLock must be held to read or write those bits reliably.
    916 
    917     bool                    mDoNotReconnect;
    918 
    919     int                     mSessionId;
    920     int                     mAuxEffectId;
    921 
    922     mutable Mutex           mLock;
    923 
    924     bool                    mIsTimed;
    925     int                     mPreviousPriority;          // before start()
    926     SchedPolicy             mPreviousSchedulingGroup;
    927     bool                    mAwaitBoost;    // thread should wait for priority boost before running
    928 
    929     // The proxy should only be referenced while a lock is held because the proxy isn't
    930     // multi-thread safe, especially the SingleStateQueue part of the proxy.
    931     // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
    932     // provided that the caller also holds an extra reference to the proxy and shared memory to keep
    933     // them around in case they are replaced during the obtainBuffer().
    934     sp<StaticAudioTrackClientProxy> mStaticProxy;   // for type safety only
    935     sp<AudioTrackClientProxy>       mProxy;         // primary owner of the memory
    936 
    937     bool                    mInUnderrun;            // whether track is currently in underrun state
    938     uint32_t                mPausedPosition;
    939 
    940     // For Device Selection API
    941     //  a value of AUDIO_PORT_HANDLE_NONE indicated default (AudioPolicyManager) routing.
    942     audio_port_handle_t     mSelectedDeviceId;
    943 
    944 private:
    945     class DeathNotifier : public IBinder::DeathRecipient {
    946     public:
    947         DeathNotifier(AudioTrack* audioTrack) : mAudioTrack(audioTrack) { }
    948     protected:
    949         virtual void        binderDied(const wp<IBinder>& who);
    950     private:
    951         const wp<AudioTrack> mAudioTrack;
    952     };
    953 
    954     sp<DeathNotifier>       mDeathNotifier;
    955     uint32_t                mSequence;              // incremented for each new IAudioTrack attempt
    956     int                     mClientUid;
    957     pid_t                   mClientPid;
    958 
    959     sp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
    960 };
    961 
    962 class TimedAudioTrack : public AudioTrack
    963 {
    964 public:
    965     TimedAudioTrack();
    966 
    967     /* allocate a shared memory buffer that can be passed to queueTimedBuffer */
    968     status_t allocateTimedBuffer(size_t size, sp<IMemory>* buffer);
    969 
    970     /* queue a buffer obtained via allocateTimedBuffer for playback at the
    971        given timestamp.  PTS units are microseconds on the media time timeline.
    972        The media time transform (set with setMediaTimeTransform) set by the
    973        audio producer will handle converting from media time to local time
    974        (perhaps going through the common time timeline in the case of
    975        synchronized multiroom audio case) */
    976     status_t queueTimedBuffer(const sp<IMemory>& buffer, int64_t pts);
    977 
    978     /* define a transform between media time and either common time or
    979        local time */
    980     enum TargetTimeline {LOCAL_TIME, COMMON_TIME};
    981     status_t setMediaTimeTransform(const LinearTransform& xform,
    982                                    TargetTimeline target);
    983 };
    984 
    985 }; // namespace android
    986 
    987 #endif // ANDROID_AUDIOTRACK_H
    988