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 <media/MediaAnalyticsItem.h>
     26 #include <media/Modulo.h>
     27 #include <utils/threads.h>
     28 
     29 namespace android {
     30 
     31 // ----------------------------------------------------------------------------
     32 
     33 struct audio_track_cblk_t;
     34 class AudioTrackClientProxy;
     35 class StaticAudioTrackClientProxy;
     36 
     37 // ----------------------------------------------------------------------------
     38 
     39 class AudioTrack : public AudioSystem::AudioDeviceCallback
     40 {
     41 public:
     42 
     43     /* Events used by AudioTrack callback function (callback_t).
     44      * Keep in sync with frameworks/base/media/java/android/media/AudioTrack.java NATIVE_EVENT_*.
     45      */
     46     enum event_type {
     47         EVENT_MORE_DATA = 0,        // Request to write more data to buffer.
     48                                     // This event only occurs for TRANSFER_CALLBACK.
     49                                     // If this event is delivered but the callback handler
     50                                     // does not want to write more data, the handler must
     51                                     // ignore the event by setting frameCount to zero.
     52                                     // This might occur, for example, if the application is
     53                                     // waiting for source data or is at the end of stream.
     54                                     //
     55                                     // For data filling, it is preferred that the callback
     56                                     // does not block and instead returns a short count on
     57                                     // the amount of data actually delivered
     58                                     // (or 0, if no data is currently available).
     59         EVENT_UNDERRUN = 1,         // Buffer underrun occurred. This will not occur for
     60                                     // static tracks.
     61         EVENT_LOOP_END = 2,         // Sample loop end was reached; playback restarted from
     62                                     // loop start if loop count was not 0 for a static track.
     63         EVENT_MARKER = 3,           // Playback head is at the specified marker position
     64                                     // (See setMarkerPosition()).
     65         EVENT_NEW_POS = 4,          // Playback head is at a new position
     66                                     // (See setPositionUpdatePeriod()).
     67         EVENT_BUFFER_END = 5,       // Playback has completed for a static track.
     68         EVENT_NEW_IAUDIOTRACK = 6,  // IAudioTrack was re-created, either due to re-routing and
     69                                     // voluntary invalidation by mediaserver, or mediaserver crash.
     70         EVENT_STREAM_END = 7,       // Sent after all the buffers queued in AF and HW are played
     71                                     // back (after stop is called) for an offloaded track.
     72 #if 0   // FIXME not yet implemented
     73         EVENT_NEW_TIMESTAMP = 8,    // Delivered periodically and when there's a significant change
     74                                     // in the mapping from frame position to presentation time.
     75                                     // See AudioTimestamp for the information included with event.
     76 #endif
     77         EVENT_CAN_WRITE_MORE_DATA = 9,// Notification that more data can be given by write()
     78                                     // This event only occurs for TRANSFER_SYNC_NOTIF_CALLBACK.
     79     };
     80 
     81     /* Client should declare a Buffer and pass the address to obtainBuffer()
     82      * and releaseBuffer().  See also callback_t for EVENT_MORE_DATA.
     83      */
     84 
     85     class Buffer
     86     {
     87     public:
     88         // FIXME use m prefix
     89         size_t      frameCount;   // number of sample frames corresponding to size;
     90                                   // on input to obtainBuffer() it is the number of frames desired,
     91                                   // on output from obtainBuffer() it is the number of available
     92                                   //    [empty slots for] frames to be filled
     93                                   // on input to releaseBuffer() it is currently ignored
     94 
     95         size_t      size;         // input/output in bytes == frameCount * frameSize
     96                                   // on input to obtainBuffer() it is ignored
     97                                   // on output from obtainBuffer() it is the number of available
     98                                   //    [empty slots for] bytes to be filled,
     99                                   //    which is frameCount * frameSize
    100                                   // on input to releaseBuffer() it is the number of bytes to
    101                                   //    release
    102                                   // FIXME This is redundant with respect to frameCount.  Consider
    103                                   //    removing size and making frameCount the primary field.
    104 
    105         union {
    106             void*       raw;
    107             int16_t*    i16;      // signed 16-bit
    108             int8_t*     i8;       // unsigned 8-bit, offset by 0x80
    109         };                        // input to obtainBuffer(): unused, output: pointer to buffer
    110     };
    111 
    112     /* As a convenience, if a callback is supplied, a handler thread
    113      * is automatically created with the appropriate priority. This thread
    114      * invokes the callback when a new buffer becomes available or various conditions occur.
    115      * Parameters:
    116      *
    117      * event:   type of event notified (see enum AudioTrack::event_type).
    118      * user:    Pointer to context for use by the callback receiver.
    119      * info:    Pointer to optional parameter according to event type:
    120      *          - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
    121      *            more bytes than indicated by 'size' field and update 'size' if fewer bytes are
    122      *            written.
    123      *          - EVENT_UNDERRUN: unused.
    124      *          - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
    125      *          - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames.
    126      *          - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames.
    127      *          - EVENT_BUFFER_END: unused.
    128      *          - EVENT_NEW_IAUDIOTRACK: unused.
    129      *          - EVENT_STREAM_END: unused.
    130      *          - EVENT_NEW_TIMESTAMP: pointer to const AudioTimestamp.
    131      */
    132 
    133     typedef void (*callback_t)(int event, void* user, void *info);
    134 
    135     /* Returns the minimum frame count required for the successful creation of
    136      * an AudioTrack object.
    137      * Returned status (from utils/Errors.h) can be:
    138      *  - NO_ERROR: successful operation
    139      *  - NO_INIT: audio server or audio hardware not initialized
    140      *  - BAD_VALUE: unsupported configuration
    141      * frameCount is guaranteed to be non-zero if status is NO_ERROR,
    142      * and is undefined otherwise.
    143      * FIXME This API assumes a route, and so should be deprecated.
    144      */
    145 
    146     static status_t getMinFrameCount(size_t* frameCount,
    147                                      audio_stream_type_t streamType,
    148                                      uint32_t sampleRate);
    149 
    150     /* Check if direct playback is possible for the given audio configuration and attributes.
    151      * Return true if output is possible for the given parameters. Otherwise returns false.
    152      */
    153     static bool isDirectOutputSupported(const audio_config_base_t& config,
    154                                         const audio_attributes_t& attributes);
    155 
    156     /* How data is transferred to AudioTrack
    157      */
    158     enum transfer_type {
    159         TRANSFER_DEFAULT,   // not specified explicitly; determine from the other parameters
    160         TRANSFER_CALLBACK,  // callback EVENT_MORE_DATA
    161         TRANSFER_OBTAIN,    // call obtainBuffer() and releaseBuffer()
    162         TRANSFER_SYNC,      // synchronous write()
    163         TRANSFER_SHARED,    // shared memory
    164         TRANSFER_SYNC_NOTIF_CALLBACK, // synchronous write(), notif EVENT_CAN_WRITE_MORE_DATA
    165     };
    166 
    167     /* Constructs an uninitialized AudioTrack. No connection with
    168      * AudioFlinger takes place.  Use set() after this.
    169      */
    170                         AudioTrack();
    171 
    172     /* Creates an AudioTrack object and registers it with AudioFlinger.
    173      * Once created, the track needs to be started before it can be used.
    174      * Unspecified values are set to appropriate default values.
    175      *
    176      * Parameters:
    177      *
    178      * streamType:         Select the type of audio stream this track is attached to
    179      *                     (e.g. AUDIO_STREAM_MUSIC).
    180      * sampleRate:         Data source sampling rate in Hz.  Zero means to use the sink sample rate.
    181      *                     A non-zero value must be specified if AUDIO_OUTPUT_FLAG_DIRECT is set.
    182      *                     0 will not work with current policy implementation for direct output
    183      *                     selection where an exact match is needed for sampling rate.
    184      * format:             Audio format. For mixed tracks, any PCM format supported by server is OK.
    185      *                     For direct and offloaded tracks, the possible format(s) depends on the
    186      *                     output sink.
    187      * channelMask:        Channel mask, such that audio_is_output_channel(channelMask) is true.
    188      * frameCount:         Minimum size of track PCM buffer in frames. This defines the
    189      *                     application's contribution to the
    190      *                     latency of the track. The actual size selected by the AudioTrack could be
    191      *                     larger if the requested size is not compatible with current audio HAL
    192      *                     configuration.  Zero means to use a default value.
    193      * flags:              See comments on audio_output_flags_t in <system/audio.h>.
    194      * cbf:                Callback function. If not null, this function is called periodically
    195      *                     to provide new data in TRANSFER_CALLBACK mode
    196      *                     and inform of marker, position updates, etc.
    197      * user:               Context for use by the callback receiver.
    198      * notificationFrames: The callback function is called each time notificationFrames PCM
    199      *                     frames have been consumed from track input buffer by server.
    200      *                     Zero means to use a default value, which is typically:
    201      *                      - fast tracks: HAL buffer size, even if track frameCount is larger
    202      *                      - normal tracks: 1/2 of track frameCount
    203      *                     A positive value means that many frames at initial source sample rate.
    204      *                     A negative value for this parameter specifies the negative of the
    205      *                     requested number of notifications (sub-buffers) in the entire buffer.
    206      *                     For fast tracks, the FastMixer will process one sub-buffer at a time.
    207      *                     The size of each sub-buffer is determined by the HAL.
    208      *                     To get "double buffering", for example, one should pass -2.
    209      *                     The minimum number of sub-buffers is 1 (expressed as -1),
    210      *                     and the maximum number of sub-buffers is 8 (expressed as -8).
    211      *                     Negative is only permitted for fast tracks, and if frameCount is zero.
    212      *                     TODO It is ugly to overload a parameter in this way depending on
    213      *                     whether it is positive, negative, or zero.  Consider splitting apart.
    214      * sessionId:          Specific session ID, or zero to use default.
    215      * transferType:       How data is transferred to AudioTrack.
    216      * offloadInfo:        If not NULL, provides offload parameters for
    217      *                     AudioSystem::getOutputForAttr().
    218      * uid:                User ID of the app which initially requested this AudioTrack
    219      *                     for power management tracking, or -1 for current user ID.
    220      * pid:                Process ID of the app which initially requested this AudioTrack
    221      *                     for power management tracking, or -1 for current process ID.
    222      * pAttributes:        If not NULL, supersedes streamType for use case selection.
    223      * doNotReconnect:     If set to true, AudioTrack won't automatically recreate the IAudioTrack
    224                            binder to AudioFlinger.
    225                            It will return an error instead.  The application will recreate
    226                            the track based on offloading or different channel configuration, etc.
    227      * maxRequiredSpeed:   For PCM tracks, this creates an appropriate buffer size that will allow
    228      *                     maxRequiredSpeed playback. Values less than 1.0f and greater than
    229      *                     AUDIO_TIMESTRETCH_SPEED_MAX will be clamped.  For non-PCM tracks
    230      *                     and direct or offloaded tracks, this parameter is ignored.
    231      * selectedDeviceId:   Selected device id of the app which initially requested the AudioTrack
    232      *                     to open with a specific device.
    233      * threadCanCallJava:  Not present in parameter list, and so is fixed at false.
    234      */
    235 
    236                         AudioTrack( audio_stream_type_t streamType,
    237                                     uint32_t sampleRate,
    238                                     audio_format_t format,
    239                                     audio_channel_mask_t channelMask,
    240                                     size_t frameCount    = 0,
    241                                     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
    242                                     callback_t cbf       = NULL,
    243                                     void* user           = NULL,
    244                                     int32_t notificationFrames = 0,
    245                                     audio_session_t sessionId  = AUDIO_SESSION_ALLOCATE,
    246                                     transfer_type transferType = TRANSFER_DEFAULT,
    247                                     const audio_offload_info_t *offloadInfo = NULL,
    248                                     uid_t uid = AUDIO_UID_INVALID,
    249                                     pid_t pid = -1,
    250                                     const audio_attributes_t* pAttributes = NULL,
    251                                     bool doNotReconnect = false,
    252                                     float maxRequiredSpeed = 1.0f,
    253                                     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE);
    254 
    255     /* Creates an audio track and registers it with AudioFlinger.
    256      * With this constructor, the track is configured for static buffer mode.
    257      * Data to be rendered is passed in a shared memory buffer
    258      * identified by the argument sharedBuffer, which should be non-0.
    259      * If sharedBuffer is zero, this constructor is equivalent to the previous constructor
    260      * but without the ability to specify a non-zero value for the frameCount parameter.
    261      * The memory should be initialized to the desired data before calling start().
    262      * The write() method is not supported in this case.
    263      * It is recommended to pass a callback function to be notified of playback end by an
    264      * EVENT_UNDERRUN event.
    265      */
    266 
    267                         AudioTrack( audio_stream_type_t streamType,
    268                                     uint32_t sampleRate,
    269                                     audio_format_t format,
    270                                     audio_channel_mask_t channelMask,
    271                                     const sp<IMemory>& sharedBuffer,
    272                                     audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
    273                                     callback_t cbf      = NULL,
    274                                     void* user          = NULL,
    275                                     int32_t notificationFrames = 0,
    276                                     audio_session_t sessionId   = AUDIO_SESSION_ALLOCATE,
    277                                     transfer_type transferType = TRANSFER_DEFAULT,
    278                                     const audio_offload_info_t *offloadInfo = NULL,
    279                                     uid_t uid = AUDIO_UID_INVALID,
    280                                     pid_t pid = -1,
    281                                     const audio_attributes_t* pAttributes = NULL,
    282                                     bool doNotReconnect = false,
    283                                     float maxRequiredSpeed = 1.0f);
    284 
    285     /* Terminates the AudioTrack and unregisters it from AudioFlinger.
    286      * Also destroys all resources associated with the AudioTrack.
    287      */
    288 protected:
    289                         virtual ~AudioTrack();
    290 public:
    291 
    292     /* Initialize an AudioTrack that was created using the AudioTrack() constructor.
    293      * Don't call set() more than once, or after the AudioTrack() constructors that take parameters.
    294      * set() is not multi-thread safe.
    295      * Returned status (from utils/Errors.h) can be:
    296      *  - NO_ERROR: successful initialization
    297      *  - INVALID_OPERATION: AudioTrack is already initialized
    298      *  - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...)
    299      *  - NO_INIT: audio server or audio hardware not initialized
    300      * If status is not equal to NO_ERROR, don't call any other APIs on this AudioTrack.
    301      * If sharedBuffer is non-0, the frameCount parameter is ignored and
    302      * replaced by the shared buffer's total allocated size in frame units.
    303      *
    304      * Parameters not listed in the AudioTrack constructors above:
    305      *
    306      * threadCanCallJava:  Whether callbacks are made from an attached thread and thus can call JNI.
    307      *      Only set to true when AudioTrack object is used for a java android.media.AudioTrack
    308      *      in its JNI code.
    309      *
    310      * Internal state post condition:
    311      *      (mStreamType == AUDIO_STREAM_DEFAULT) implies this AudioTrack has valid attributes
    312      */
    313             status_t    set(audio_stream_type_t streamType,
    314                             uint32_t sampleRate,
    315                             audio_format_t format,
    316                             audio_channel_mask_t channelMask,
    317                             size_t frameCount   = 0,
    318                             audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
    319                             callback_t cbf      = NULL,
    320                             void* user          = NULL,
    321                             int32_t notificationFrames = 0,
    322                             const sp<IMemory>& sharedBuffer = 0,
    323                             bool threadCanCallJava = false,
    324                             audio_session_t sessionId  = AUDIO_SESSION_ALLOCATE,
    325                             transfer_type transferType = TRANSFER_DEFAULT,
    326                             const audio_offload_info_t *offloadInfo = NULL,
    327                             uid_t uid = AUDIO_UID_INVALID,
    328                             pid_t pid = -1,
    329                             const audio_attributes_t* pAttributes = NULL,
    330                             bool doNotReconnect = false,
    331                             float maxRequiredSpeed = 1.0f,
    332                             audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE);
    333 
    334     /* Result of constructing the AudioTrack. This must be checked for successful initialization
    335      * before using any AudioTrack API (except for set()), because using
    336      * an uninitialized AudioTrack produces undefined results.
    337      * See set() method above for possible return codes.
    338      */
    339             status_t    initCheck() const   { return mStatus; }
    340 
    341     /* Returns this track's estimated latency in milliseconds.
    342      * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
    343      * and audio hardware driver.
    344      */
    345             uint32_t    latency();
    346 
    347     /* Returns the number of application-level buffer underruns
    348      * since the AudioTrack was created.
    349      */
    350             uint32_t    getUnderrunCount() const;
    351 
    352     /* getters, see constructors and set() */
    353 
    354             audio_stream_type_t streamType() const;
    355             audio_format_t format() const   { return mFormat; }
    356 
    357     /* Return frame size in bytes, which for linear PCM is
    358      * channelCount * (bit depth per channel / 8).
    359      * channelCount is determined from channelMask, and bit depth comes from format.
    360      * For non-linear formats, the frame size is typically 1 byte.
    361      */
    362             size_t      frameSize() const   { return mFrameSize; }
    363 
    364             uint32_t    channelCount() const { return mChannelCount; }
    365             size_t      frameCount() const  { return mFrameCount; }
    366 
    367     /*
    368      * Return the period of the notification callback in frames.
    369      * This value is set when the AudioTrack is constructed.
    370      * It can be modified if the AudioTrack is rerouted.
    371      */
    372             uint32_t    getNotificationPeriodInFrames() const { return mNotificationFramesAct; }
    373 
    374     /* Return effective size of audio buffer that an application writes to
    375      * or a negative error if the track is uninitialized.
    376      */
    377             ssize_t     getBufferSizeInFrames();
    378 
    379     /* Returns the buffer duration in microseconds at current playback rate.
    380      */
    381             status_t    getBufferDurationInUs(int64_t *duration);
    382 
    383     /* Set the effective size of audio buffer that an application writes to.
    384      * This is used to determine the amount of available room in the buffer,
    385      * which determines when a write will block.
    386      * This allows an application to raise and lower the audio latency.
    387      * The requested size may be adjusted so that it is
    388      * greater or equal to the absolute minimum and
    389      * less than or equal to the getBufferCapacityInFrames().
    390      * It may also be adjusted slightly for internal reasons.
    391      *
    392      * Return the final size or a negative error if the track is unitialized
    393      * or does not support variable sizes.
    394      */
    395             ssize_t     setBufferSizeInFrames(size_t size);
    396 
    397     /* Return the static buffer specified in constructor or set(), or 0 for streaming mode */
    398             sp<IMemory> sharedBuffer() const { return mSharedBuffer; }
    399 
    400     /*
    401      * return metrics information for the current track.
    402      */
    403             status_t getMetrics(MediaAnalyticsItem * &item);
    404 
    405     /* After it's created the track is not active. Call start() to
    406      * make it active. If set, the callback will start being called.
    407      * If the track was previously paused, volume is ramped up over the first mix buffer.
    408      */
    409             status_t        start();
    410 
    411     /* Stop a track.
    412      * In static buffer mode, the track is stopped immediately.
    413      * In streaming mode, the callback will cease being called.  Note that obtainBuffer() still
    414      * works and will fill up buffers until the pool is exhausted, and then will return WOULD_BLOCK.
    415      * In streaming mode the stop does not occur immediately: any data remaining in the buffer
    416      * is first drained, mixed, and output, and only then is the track marked as stopped.
    417      */
    418             void        stop();
    419             bool        stopped() const;
    420 
    421     /* Flush a stopped or paused track. All previously buffered data is discarded immediately.
    422      * This has the effect of draining the buffers without mixing or output.
    423      * Flush is intended for streaming mode, for example before switching to non-contiguous content.
    424      * This function is a no-op if the track is not stopped or paused, or uses a static buffer.
    425      */
    426             void        flush();
    427 
    428     /* Pause a track. After pause, the callback will cease being called and
    429      * obtainBuffer returns WOULD_BLOCK. Note that obtainBuffer() still works
    430      * and will fill up buffers until the pool is exhausted.
    431      * Volume is ramped down over the next mix buffer following the pause request,
    432      * and then the track is marked as paused.  It can be resumed with ramp up by start().
    433      */
    434             void        pause();
    435 
    436     /* Set volume for this track, mostly used for games' sound effects
    437      * left and right volumes. Levels must be >= 0.0 and <= 1.0.
    438      * This is the older API.  New applications should use setVolume(float) when possible.
    439      */
    440             status_t    setVolume(float left, float right);
    441 
    442     /* Set volume for all channels.  This is the preferred API for new applications,
    443      * especially for multi-channel content.
    444      */
    445             status_t    setVolume(float volume);
    446 
    447     /* Set the send level for this track. An auxiliary effect should be attached
    448      * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0.
    449      */
    450             status_t    setAuxEffectSendLevel(float level);
    451             void        getAuxEffectSendLevel(float* level) const;
    452 
    453     /* Set source sample rate for this track in Hz, mostly used for games' sound effects.
    454      * Zero is not permitted.
    455      */
    456             status_t    setSampleRate(uint32_t sampleRate);
    457 
    458     /* Return current source sample rate in Hz.
    459      * If specified as zero in constructor or set(), this will be the sink sample rate.
    460      */
    461             uint32_t    getSampleRate() const;
    462 
    463     /* Return the original source sample rate in Hz. This corresponds to the sample rate
    464      * if playback rate had normal speed and pitch.
    465      */
    466             uint32_t    getOriginalSampleRate() const;
    467 
    468     /* Set source playback rate for timestretch
    469      * 1.0 is normal speed: < 1.0 is slower, > 1.0 is faster
    470      * 1.0 is normal pitch: < 1.0 is lower pitch, > 1.0 is higher pitch
    471      *
    472      * AUDIO_TIMESTRETCH_SPEED_MIN <= speed <= AUDIO_TIMESTRETCH_SPEED_MAX
    473      * AUDIO_TIMESTRETCH_PITCH_MIN <= pitch <= AUDIO_TIMESTRETCH_PITCH_MAX
    474      *
    475      * Speed increases the playback rate of media, but does not alter pitch.
    476      * Pitch increases the "tonal frequency" of media, but does not affect the playback rate.
    477      */
    478             status_t    setPlaybackRate(const AudioPlaybackRate &playbackRate);
    479 
    480     /* Return current playback rate */
    481             const AudioPlaybackRate& getPlaybackRate() const;
    482 
    483     /* Enables looping and sets the start and end points of looping.
    484      * Only supported for static buffer mode.
    485      *
    486      * Parameters:
    487      *
    488      * loopStart:   loop start in frames relative to start of buffer.
    489      * loopEnd:     loop end in frames relative to start of buffer.
    490      * loopCount:   number of loops to execute. Calling setLoop() with loopCount == 0 cancels any
    491      *              pending or active loop. loopCount == -1 means infinite looping.
    492      *
    493      * For proper operation the following condition must be respected:
    494      *      loopCount != 0 implies 0 <= loopStart < loopEnd <= frameCount().
    495      *
    496      * If the loop period (loopEnd - loopStart) is too small for the implementation to support,
    497      * setLoop() will return BAD_VALUE.  loopCount must be >= -1.
    498      *
    499      */
    500             status_t    setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
    501 
    502     /* Sets marker position. When playback reaches the number of frames specified, a callback with
    503      * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker
    504      * notification callback.  To set a marker at a position which would compute as 0,
    505      * a workaround is to set the marker at a nearby position such as ~0 or 1.
    506      * If the AudioTrack has been opened with no callback function associated, the operation will
    507      * fail.
    508      *
    509      * Parameters:
    510      *
    511      * marker:   marker position expressed in wrapping (overflow) frame units,
    512      *           like the return value of getPosition().
    513      *
    514      * Returned status (from utils/Errors.h) can be:
    515      *  - NO_ERROR: successful operation
    516      *  - INVALID_OPERATION: the AudioTrack has no callback installed.
    517      */
    518             status_t    setMarkerPosition(uint32_t marker);
    519             status_t    getMarkerPosition(uint32_t *marker) const;
    520 
    521     /* Sets position update period. Every time the number of frames specified has been played,
    522      * a callback with event type EVENT_NEW_POS is called.
    523      * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
    524      * callback.
    525      * If the AudioTrack has been opened with no callback function associated, the operation will
    526      * fail.
    527      * Extremely small values may be rounded up to a value the implementation can support.
    528      *
    529      * Parameters:
    530      *
    531      * updatePeriod:  position update notification period expressed in frames.
    532      *
    533      * Returned status (from utils/Errors.h) can be:
    534      *  - NO_ERROR: successful operation
    535      *  - INVALID_OPERATION: the AudioTrack has no callback installed.
    536      */
    537             status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
    538             status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
    539 
    540     /* Sets playback head position.
    541      * Only supported for static buffer mode.
    542      *
    543      * Parameters:
    544      *
    545      * position:  New playback head position in frames relative to start of buffer.
    546      *            0 <= position <= frameCount().  Note that end of buffer is permitted,
    547      *            but will result in an immediate underrun if started.
    548      *
    549      * Returned status (from utils/Errors.h) can be:
    550      *  - NO_ERROR: successful operation
    551      *  - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode.
    552      *  - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack
    553      *               buffer
    554      */
    555             status_t    setPosition(uint32_t position);
    556 
    557     /* Return the total number of frames played since playback start.
    558      * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
    559      * It is reset to zero by flush(), reload(), and stop().
    560      *
    561      * Parameters:
    562      *
    563      *  position:  Address where to return play head position.
    564      *
    565      * Returned status (from utils/Errors.h) can be:
    566      *  - NO_ERROR: successful operation
    567      *  - BAD_VALUE:  position is NULL
    568      */
    569             status_t    getPosition(uint32_t *position);
    570 
    571     /* For static buffer mode only, this returns the current playback position in frames
    572      * relative to start of buffer.  It is analogous to the position units used by
    573      * setLoop() and setPosition().  After underrun, the position will be at end of buffer.
    574      */
    575             status_t    getBufferPosition(uint32_t *position);
    576 
    577     /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
    578      * rewriting the buffer before restarting playback after a stop.
    579      * This method must be called with the AudioTrack in paused or stopped state.
    580      * Not allowed in streaming mode.
    581      *
    582      * Returned status (from utils/Errors.h) can be:
    583      *  - NO_ERROR: successful operation
    584      *  - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode.
    585      */
    586             status_t    reload();
    587 
    588     /**
    589      * @param transferType
    590      * @return text string that matches the enum name
    591      */
    592             static const char * convertTransferToText(transfer_type transferType);
    593 
    594     /* Returns a handle on the audio output used by this AudioTrack.
    595      *
    596      * Parameters:
    597      *  none.
    598      *
    599      * Returned value:
    600      *  handle on audio hardware output, or AUDIO_IO_HANDLE_NONE if the
    601      *  track needed to be re-created but that failed
    602      */
    603 private:
    604             audio_io_handle_t    getOutput() const;
    605 public:
    606 
    607     /* Selects the audio device to use for output of this AudioTrack. A value of
    608      * AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing.
    609      *
    610      * Parameters:
    611      *  The device ID of the selected device (as returned by the AudioDevicesManager API).
    612      *
    613      * Returned value:
    614      *  - NO_ERROR: successful operation
    615      *    TODO: what else can happen here?
    616      */
    617             status_t    setOutputDevice(audio_port_handle_t deviceId);
    618 
    619     /* Returns the ID of the audio device selected for this AudioTrack.
    620      * A value of AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing.
    621      *
    622      * Parameters:
    623      *  none.
    624      */
    625      audio_port_handle_t getOutputDevice();
    626 
    627      /* Returns the ID of the audio device actually used by the output to which this AudioTrack is
    628       * attached.
    629       * When the AudioTrack is inactive, the device ID returned can be either:
    630       * - AUDIO_PORT_HANDLE_NONE if the AudioTrack is not attached to any output.
    631       * - The device ID used before paused or stopped.
    632       * - The device ID selected by audio policy manager of setOutputDevice() if the AudioTrack
    633       * has not been started yet.
    634       *
    635       * Parameters:
    636       *  none.
    637       */
    638      audio_port_handle_t getRoutedDeviceId();
    639 
    640     /* Returns the unique session ID associated with this track.
    641      *
    642      * Parameters:
    643      *  none.
    644      *
    645      * Returned value:
    646      *  AudioTrack session ID.
    647      */
    648             audio_session_t getSessionId() const { return mSessionId; }
    649 
    650     /* Attach track auxiliary output to specified effect. Use effectId = 0
    651      * to detach track from effect.
    652      *
    653      * Parameters:
    654      *
    655      * effectId:  effectId obtained from AudioEffect::id().
    656      *
    657      * Returned status (from utils/Errors.h) can be:
    658      *  - NO_ERROR: successful operation
    659      *  - INVALID_OPERATION: the effect is not an auxiliary effect.
    660      *  - BAD_VALUE: The specified effect ID is invalid
    661      */
    662             status_t    attachAuxEffect(int effectId);
    663 
    664     /* Public API for TRANSFER_OBTAIN mode.
    665      * Obtains a buffer of up to "audioBuffer->frameCount" empty slots for frames.
    666      * After filling these slots with data, the caller should release them with releaseBuffer().
    667      * If the track buffer is not full, obtainBuffer() returns as many contiguous
    668      * [empty slots for] frames as are available immediately.
    669      *
    670      * If nonContig is non-NULL, it is an output parameter that will be set to the number of
    671      * additional non-contiguous frames that are predicted to be available immediately,
    672      * if the client were to release the first frames and then call obtainBuffer() again.
    673      * This value is only a prediction, and needs to be confirmed.
    674      * It will be set to zero for an error return.
    675      *
    676      * If the track buffer is full and track is stopped, obtainBuffer() returns WOULD_BLOCK
    677      * regardless of the value of waitCount.
    678      * If the track buffer is full and track is not stopped, obtainBuffer() blocks with a
    679      * maximum timeout based on waitCount; see chart below.
    680      * Buffers will be returned until the pool
    681      * is exhausted, at which point obtainBuffer() will either block
    682      * or return WOULD_BLOCK depending on the value of the "waitCount"
    683      * parameter.
    684      *
    685      * Interpretation of waitCount:
    686      *  +n  limits wait time to n * WAIT_PERIOD_MS,
    687      *  -1  causes an (almost) infinite wait time,
    688      *   0  non-blocking.
    689      *
    690      * Buffer fields
    691      * On entry:
    692      *  frameCount  number of [empty slots for] frames requested
    693      *  size        ignored
    694      *  raw         ignored
    695      * After error return:
    696      *  frameCount  0
    697      *  size        0
    698      *  raw         undefined
    699      * After successful return:
    700      *  frameCount  actual number of [empty slots for] frames available, <= number requested
    701      *  size        actual number of bytes available
    702      *  raw         pointer to the buffer
    703      */
    704             status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount,
    705                                 size_t *nonContig = NULL);
    706 
    707 private:
    708     /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
    709      * additional non-contiguous frames that are predicted to be available immediately,
    710      * if the client were to release the first frames and then call obtainBuffer() again.
    711      * This value is only a prediction, and needs to be confirmed.
    712      * It will be set to zero for an error return.
    713      * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
    714      * in case the requested amount of frames is in two or more non-contiguous regions.
    715      * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
    716      */
    717             status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
    718                                      struct timespec *elapsed = NULL, size_t *nonContig = NULL);
    719 public:
    720 
    721     /* Public API for TRANSFER_OBTAIN mode.
    722      * Release a filled buffer of frames for AudioFlinger to process.
    723      *
    724      * Buffer fields:
    725      *  frameCount  currently ignored but recommend to set to actual number of frames filled
    726      *  size        actual number of bytes filled, must be multiple of frameSize
    727      *  raw         ignored
    728      */
    729             void        releaseBuffer(const Buffer* audioBuffer);
    730 
    731     /* As a convenience we provide a write() interface to the audio buffer.
    732      * Input parameter 'size' is in byte units.
    733      * This is implemented on top of obtainBuffer/releaseBuffer. For best
    734      * performance use callbacks. Returns actual number of bytes written >= 0,
    735      * or one of the following negative status codes:
    736      *      INVALID_OPERATION   AudioTrack is configured for static buffer or streaming mode
    737      *      BAD_VALUE           size is invalid
    738      *      WOULD_BLOCK         when obtainBuffer() returns same, or
    739      *                          AudioTrack was stopped during the write
    740      *      DEAD_OBJECT         when AudioFlinger dies or the output device changes and
    741      *                          the track cannot be automatically restored.
    742      *                          The application needs to recreate the AudioTrack
    743      *                          because the audio device changed or AudioFlinger died.
    744      *                          This typically occurs for direct or offload tracks
    745      *                          or if mDoNotReconnect is true.
    746      *      or any other error code returned by IAudioTrack::start() or restoreTrack_l().
    747      * Default behavior is to only return when all data has been transferred. Set 'blocking' to
    748      * false for the method to return immediately without waiting to try multiple times to write
    749      * the full content of the buffer.
    750      */
    751             ssize_t     write(const void* buffer, size_t size, bool blocking = true);
    752 
    753     /*
    754      * Dumps the state of an audio track.
    755      * Not a general-purpose API; intended only for use by media player service to dump its tracks.
    756      */
    757             status_t    dump(int fd, const Vector<String16>& args) const;
    758 
    759     /*
    760      * Return the total number of frames which AudioFlinger desired but were unavailable,
    761      * and thus which resulted in an underrun.  Reset to zero by stop().
    762      */
    763             uint32_t    getUnderrunFrames() const;
    764 
    765     /* Get the flags */
    766             audio_output_flags_t getFlags() const { AutoMutex _l(mLock); return mFlags; }
    767 
    768     /* Set parameters - only possible when using direct output */
    769             status_t    setParameters(const String8& keyValuePairs);
    770 
    771     /* Sets the volume shaper object */
    772             media::VolumeShaper::Status applyVolumeShaper(
    773                     const sp<media::VolumeShaper::Configuration>& configuration,
    774                     const sp<media::VolumeShaper::Operation>& operation);
    775 
    776     /* Gets the volume shaper state */
    777             sp<media::VolumeShaper::State> getVolumeShaperState(int id);
    778 
    779     /* Selects the presentation (if available) */
    780             status_t    selectPresentation(int presentationId, int programId);
    781 
    782     /* Get parameters */
    783             String8     getParameters(const String8& keys);
    784 
    785     /* Poll for a timestamp on demand.
    786      * Use if EVENT_NEW_TIMESTAMP is not delivered often enough for your needs,
    787      * or if you need to get the most recent timestamp outside of the event callback handler.
    788      * Caution: calling this method too often may be inefficient;
    789      * if you need a high resolution mapping between frame position and presentation time,
    790      * consider implementing that at application level, based on the low resolution timestamps.
    791      * Returns NO_ERROR    if timestamp is valid.
    792      *         WOULD_BLOCK if called in STOPPED or FLUSHED state, or if called immediately after
    793      *                     start/ACTIVE, when the number of frames consumed is less than the
    794      *                     overall hardware latency to physical output. In WOULD_BLOCK cases,
    795      *                     one might poll again, or use getPosition(), or use 0 position and
    796      *                     current time for the timestamp.
    797      *         DEAD_OBJECT if AudioFlinger dies or the output device changes and
    798      *                     the track cannot be automatically restored.
    799      *                     The application needs to recreate the AudioTrack
    800      *                     because the audio device changed or AudioFlinger died.
    801      *                     This typically occurs for direct or offload tracks
    802      *                     or if mDoNotReconnect is true.
    803      *         INVALID_OPERATION  wrong state, or some other error.
    804      *
    805      * The timestamp parameter is undefined on return, if status is not NO_ERROR.
    806      */
    807             status_t    getTimestamp(AudioTimestamp& timestamp);
    808 private:
    809             status_t    getTimestamp_l(AudioTimestamp& timestamp);
    810 public:
    811 
    812     /* Return the extended timestamp, with additional timebase info and improved drain behavior.
    813      *
    814      * This is similar to the AudioTrack.java API:
    815      * getTimestamp(@NonNull AudioTimestamp timestamp, @AudioTimestamp.Timebase int timebase)
    816      *
    817      * Some differences between this method and the getTimestamp(AudioTimestamp& timestamp) method
    818      *
    819      *   1. stop() by itself does not reset the frame position.
    820      *      A following start() resets the frame position to 0.
    821      *   2. flush() by itself does not reset the frame position.
    822      *      The frame position advances by the number of frames flushed,
    823      *      when the first frame after flush reaches the audio sink.
    824      *   3. BOOTTIME clock offsets are provided to help synchronize with
    825      *      non-audio streams, e.g. sensor data.
    826      *   4. Position is returned with 64 bits of resolution.
    827      *
    828      * Parameters:
    829      *  timestamp: A pointer to the caller allocated ExtendedTimestamp.
    830      *
    831      * Returns NO_ERROR    on success; timestamp is filled with valid data.
    832      *         BAD_VALUE   if timestamp is NULL.
    833      *         WOULD_BLOCK if called immediately after start() when the number
    834      *                     of frames consumed is less than the
    835      *                     overall hardware latency to physical output. In WOULD_BLOCK cases,
    836      *                     one might poll again, or use getPosition(), or use 0 position and
    837      *                     current time for the timestamp.
    838      *                     If WOULD_BLOCK is returned, the timestamp is still
    839      *                     modified with the LOCATION_CLIENT portion filled.
    840      *         DEAD_OBJECT if AudioFlinger dies or the output device changes and
    841      *                     the track cannot be automatically restored.
    842      *                     The application needs to recreate the AudioTrack
    843      *                     because the audio device changed or AudioFlinger died.
    844      *                     This typically occurs for direct or offloaded tracks
    845      *                     or if mDoNotReconnect is true.
    846      *         INVALID_OPERATION  if called on a offloaded or direct track.
    847      *                     Use getTimestamp(AudioTimestamp& timestamp) instead.
    848      */
    849             status_t getTimestamp(ExtendedTimestamp *timestamp);
    850 private:
    851             status_t getTimestamp_l(ExtendedTimestamp *timestamp);
    852 public:
    853 
    854     /* Add an AudioDeviceCallback. The caller will be notified when the audio device to which this
    855      * AudioTrack is routed is updated.
    856      * Replaces any previously installed callback.
    857      * Parameters:
    858      *  callback:  The callback interface
    859      * Returns NO_ERROR if successful.
    860      *         INVALID_OPERATION if the same callback is already installed.
    861      *         NO_INIT or PREMISSION_DENIED if AudioFlinger service is not reachable
    862      *         BAD_VALUE if the callback is NULL
    863      */
    864             status_t addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback);
    865 
    866     /* remove an AudioDeviceCallback.
    867      * Parameters:
    868      *  callback:  The callback interface
    869      * Returns NO_ERROR if successful.
    870      *         INVALID_OPERATION if the callback is not installed
    871      *         BAD_VALUE if the callback is NULL
    872      */
    873             status_t removeAudioDeviceCallback(
    874                     const sp<AudioSystem::AudioDeviceCallback>& callback);
    875 
    876             // AudioSystem::AudioDeviceCallback> virtuals
    877             virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo,
    878                                              audio_port_handle_t deviceId);
    879 
    880 
    881 
    882     /* Obtain the pending duration in milliseconds for playback of pure PCM
    883      * (mixable without embedded timing) data remaining in AudioTrack.
    884      *
    885      * This is used to estimate the drain time for the client-server buffer
    886      * so the choice of ExtendedTimestamp::LOCATION_SERVER is default.
    887      * One may optionally request to find the duration to play through the HAL
    888      * by specifying a location ExtendedTimestamp::LOCATION_KERNEL; however,
    889      * INVALID_OPERATION may be returned if the kernel location is unavailable.
    890      *
    891      * Returns NO_ERROR  if successful.
    892      *         INVALID_OPERATION if ExtendedTimestamp::LOCATION_KERNEL cannot be obtained
    893      *                   or the AudioTrack does not contain pure PCM data.
    894      *         BAD_VALUE if msec is nullptr or location is invalid.
    895      */
    896             status_t pendingDuration(int32_t *msec,
    897                     ExtendedTimestamp::Location location = ExtendedTimestamp::LOCATION_SERVER);
    898 
    899     /* hasStarted() is used to determine if audio is now audible at the device after
    900      * a start() command. The underlying implementation checks a nonzero timestamp position
    901      * or increment for the audible assumption.
    902      *
    903      * hasStarted() returns true if the track has been started() and audio is audible
    904      * and no subsequent pause() or flush() has been called.  Immediately after pause() or
    905      * flush() hasStarted() will return false.
    906      *
    907      * If stop() has been called, hasStarted() will return true if audio is still being
    908      * delivered or has finished delivery (even if no audio was written) for both offloaded
    909      * and normal tracks. This property removes a race condition in checking hasStarted()
    910      * for very short clips, where stop() must be called to finish drain.
    911      *
    912      * In all cases, hasStarted() may turn false briefly after a subsequent start() is called
    913      * until audio becomes audible again.
    914      */
    915             bool hasStarted(); // not const
    916 
    917             bool isPlaying() {
    918                 AutoMutex lock(mLock);
    919                 return mState == STATE_ACTIVE || mState == STATE_STOPPING;
    920             }
    921 
    922     /* Get the unique port ID assigned to this AudioTrack instance by audio policy manager.
    923      * The ID is unique across all audioserver clients and can change during the life cycle
    924      * of a given AudioTrack instance if the connection to audioserver is restored.
    925      */
    926             audio_port_handle_t getPortId() const { return mPortId; };
    927 
    928  protected:
    929     /* copying audio tracks is not allowed */
    930                         AudioTrack(const AudioTrack& other);
    931             AudioTrack& operator = (const AudioTrack& other);
    932 
    933     /* a small internal class to handle the callback */
    934     class AudioTrackThread : public Thread
    935     {
    936     public:
    937         AudioTrackThread(AudioTrack& receiver);
    938 
    939         // Do not call Thread::requestExitAndWait() without first calling requestExit().
    940         // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
    941         virtual void        requestExit();
    942 
    943                 void        pause();    // suspend thread from execution at next loop boundary
    944                 void        resume();   // allow thread to execute, if not requested to exit
    945                 void        wake();     // wake to handle changed notification conditions.
    946 
    947     private:
    948                 void        pauseInternal(nsecs_t ns = 0LL);
    949                                         // like pause(), but only used internally within thread
    950 
    951         friend class AudioTrack;
    952         virtual bool        threadLoop();
    953         AudioTrack&         mReceiver;
    954         virtual ~AudioTrackThread();
    955         Mutex               mMyLock;    // Thread::mLock is private
    956         Condition           mMyCond;    // Thread::mThreadExitedCondition is private
    957         bool                mPaused;    // whether thread is requested to pause at next loop entry
    958         bool                mPausedInt; // whether thread internally requests pause
    959         nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
    960         bool                mIgnoreNextPausedInt;   // skip any internal pause and go immediately
    961                                         // to processAudioBuffer() as state may have changed
    962                                         // since pause time calculated.
    963     };
    964 
    965             // body of AudioTrackThread::threadLoop()
    966             // returns the maximum amount of time before we would like to run again, where:
    967             //      0           immediately
    968             //      > 0         no later than this many nanoseconds from now
    969             //      NS_WHENEVER still active but no particular deadline
    970             //      NS_INACTIVE inactive so don't run again until re-started
    971             //      NS_NEVER    never again
    972             static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
    973             nsecs_t processAudioBuffer();
    974 
    975             // caller must hold lock on mLock for all _l methods
    976 
    977             void updateLatency_l(); // updates mAfLatency and mLatency from AudioSystem cache
    978 
    979             status_t createTrack_l();
    980 
    981             // can only be called when mState != STATE_ACTIVE
    982             void flush_l();
    983 
    984             void setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
    985 
    986             // FIXME enum is faster than strcmp() for parameter 'from'
    987             status_t restoreTrack_l(const char *from);
    988 
    989             uint32_t    getUnderrunCount_l() const;
    990 
    991             bool     isOffloaded() const;
    992             bool     isDirect() const;
    993             bool     isOffloadedOrDirect() const;
    994 
    995             bool     isOffloaded_l() const
    996                 { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; }
    997 
    998             bool     isOffloadedOrDirect_l() const
    999                 { return (mFlags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD|
   1000                                                 AUDIO_OUTPUT_FLAG_DIRECT)) != 0; }
   1001 
   1002             bool     isDirect_l() const
   1003                 { return (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0; }
   1004 
   1005             // pure pcm data is mixable (which excludes HW_AV_SYNC, with embedded timing)
   1006             bool     isPurePcmData_l() const
   1007                 { return audio_is_linear_pcm(mFormat)
   1008                         && (mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) == 0; }
   1009 
   1010             // increment mPosition by the delta of mServer, and return new value of mPosition
   1011             Modulo<uint32_t> updateAndGetPosition_l();
   1012 
   1013             // check sample rate and speed is compatible with AudioTrack
   1014             bool     isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed);
   1015 
   1016             void     restartIfDisabled();
   1017 
   1018             void     updateRoutedDeviceId_l();
   1019 
   1020     // Next 4 fields may be changed if IAudioTrack is re-created, but always != 0
   1021     sp<IAudioTrack>         mAudioTrack;
   1022     sp<IMemory>             mCblkMemory;
   1023     audio_track_cblk_t*     mCblk;                  // re-load after mLock.unlock()
   1024     audio_io_handle_t       mOutput = AUDIO_IO_HANDLE_NONE; // from AudioSystem::getOutputForAttr()
   1025 
   1026     sp<AudioTrackThread>    mAudioTrackThread;
   1027     bool                    mThreadCanCallJava;
   1028 
   1029     float                   mVolume[2];
   1030     float                   mSendLevel;
   1031     mutable uint32_t        mSampleRate;            // mutable because getSampleRate() can update it
   1032     uint32_t                mOriginalSampleRate;
   1033     AudioPlaybackRate       mPlaybackRate;
   1034     float                   mMaxRequiredSpeed;      // use PCM buffer size to allow this speed
   1035 
   1036     // Corresponds to current IAudioTrack, value is reported back by AudioFlinger to the client.
   1037     // This allocated buffer size is maintained by the proxy.
   1038     size_t                  mFrameCount;            // maximum size of buffer
   1039 
   1040     size_t                  mReqFrameCount;         // frame count to request the first or next time
   1041                                                     // a new IAudioTrack is needed, non-decreasing
   1042 
   1043     // The following AudioFlinger server-side values are cached in createAudioTrack_l().
   1044     // These values can be used for informational purposes until the track is invalidated,
   1045     // whereupon restoreTrack_l() calls createTrack_l() to update the values.
   1046     uint32_t                mAfLatency;             // AudioFlinger latency in ms
   1047     size_t                  mAfFrameCount;          // AudioFlinger frame count
   1048     uint32_t                mAfSampleRate;          // AudioFlinger sample rate
   1049 
   1050     // constant after constructor or set()
   1051     audio_format_t          mFormat;                // as requested by client, not forced to 16-bit
   1052     audio_stream_type_t     mStreamType;            // mStreamType == AUDIO_STREAM_DEFAULT implies
   1053                                                     // this AudioTrack has valid attributes
   1054     uint32_t                mChannelCount;
   1055     audio_channel_mask_t    mChannelMask;
   1056     sp<IMemory>             mSharedBuffer;
   1057     transfer_type           mTransfer;
   1058     audio_offload_info_t    mOffloadInfoCopy;
   1059     const audio_offload_info_t* mOffloadInfo;
   1060     audio_attributes_t      mAttributes;
   1061 
   1062     size_t                  mFrameSize;             // frame size in bytes
   1063 
   1064     status_t                mStatus;
   1065 
   1066     // can change dynamically when IAudioTrack invalidated
   1067     uint32_t                mLatency;               // in ms
   1068 
   1069     // Indicates the current track state.  Protected by mLock.
   1070     enum State {
   1071         STATE_ACTIVE,
   1072         STATE_STOPPED,
   1073         STATE_PAUSED,
   1074         STATE_PAUSED_STOPPING,
   1075         STATE_FLUSHED,
   1076         STATE_STOPPING,
   1077     }                       mState;
   1078 
   1079     static constexpr const char *stateToString(State state)
   1080     {
   1081         switch (state) {
   1082         case STATE_ACTIVE:          return "STATE_ACTIVE";
   1083         case STATE_STOPPED:         return "STATE_STOPPED";
   1084         case STATE_PAUSED:          return "STATE_PAUSED";
   1085         case STATE_PAUSED_STOPPING: return "STATE_PAUSED_STOPPING";
   1086         case STATE_FLUSHED:         return "STATE_FLUSHED";
   1087         case STATE_STOPPING:        return "STATE_STOPPING";
   1088         default:                    return "UNKNOWN";
   1089         }
   1090     }
   1091 
   1092     // for client callback handler
   1093     callback_t              mCbf;                   // callback handler for events, or NULL
   1094     void*                   mUserData;
   1095 
   1096     // for notification APIs
   1097 
   1098     // next 2 fields are const after constructor or set()
   1099     uint32_t                mNotificationFramesReq; // requested number of frames between each
   1100                                                     // notification callback,
   1101                                                     // at initial source sample rate
   1102     uint32_t                mNotificationsPerBufferReq;
   1103                                                     // requested number of notifications per buffer,
   1104                                                     // currently only used for fast tracks with
   1105                                                     // default track buffer size
   1106 
   1107     uint32_t                mNotificationFramesAct; // actual number of frames between each
   1108                                                     // notification callback,
   1109                                                     // at initial source sample rate
   1110     bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
   1111                                                     // mRemainingFrames and mRetryOnPartialBuffer
   1112 
   1113                                                     // used for static track cbf and restoration
   1114     int32_t                 mLoopCount;             // last setLoop loopCount; zero means disabled
   1115     uint32_t                mLoopStart;             // last setLoop loopStart
   1116     uint32_t                mLoopEnd;               // last setLoop loopEnd
   1117     int32_t                 mLoopCountNotified;     // the last loopCount notified by callback.
   1118                                                     // mLoopCountNotified counts down, matching
   1119                                                     // the remaining loop count for static track
   1120                                                     // playback.
   1121 
   1122     // These are private to processAudioBuffer(), and are not protected by a lock
   1123     uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
   1124     bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
   1125     uint32_t                mObservedSequence;      // last observed value of mSequence
   1126 
   1127     Modulo<uint32_t>        mMarkerPosition;        // in wrapping (overflow) frame units
   1128     bool                    mMarkerReached;
   1129     Modulo<uint32_t>        mNewPosition;           // in frames
   1130     uint32_t                mUpdatePeriod;          // in frames, zero means no EVENT_NEW_POS
   1131 
   1132     Modulo<uint32_t>        mServer;                // in frames, last known mProxy->getPosition()
   1133                                                     // which is count of frames consumed by server,
   1134                                                     // reset by new IAudioTrack,
   1135                                                     // whether it is reset by stop() is TBD
   1136     Modulo<uint32_t>        mPosition;              // in frames, like mServer except continues
   1137                                                     // monotonically after new IAudioTrack,
   1138                                                     // and could be easily widened to uint64_t
   1139     Modulo<uint32_t>        mReleased;              // count of frames released to server
   1140                                                     // but not necessarily consumed by server,
   1141                                                     // reset by stop() but continues monotonically
   1142                                                     // after new IAudioTrack to restore mPosition,
   1143                                                     // and could be easily widened to uint64_t
   1144     int64_t                 mStartFromZeroUs;       // the start time after flush or stop,
   1145                                                     // when position should be 0.
   1146                                                     // only used for offloaded and direct tracks.
   1147     int64_t                 mStartNs;               // the time when start() is called.
   1148     ExtendedTimestamp       mStartEts;              // Extended timestamp at start for normal
   1149                                                     // AudioTracks.
   1150     AudioTimestamp          mStartTs;               // Timestamp at start for offloaded or direct
   1151                                                     // AudioTracks.
   1152 
   1153     bool                    mPreviousTimestampValid;// true if mPreviousTimestamp is valid
   1154     bool                    mTimestampStartupGlitchReported;      // reduce log spam
   1155     bool                    mTimestampRetrogradePositionReported; // reduce log spam
   1156     bool                    mTimestampRetrogradeTimeReported;     // reduce log spam
   1157     bool                    mTimestampStallReported;              // reduce log spam
   1158     bool                    mTimestampStaleTimeReported;          // reduce log spam
   1159     AudioTimestamp          mPreviousTimestamp;     // used to detect retrograde motion
   1160     ExtendedTimestamp::Location mPreviousLocation;  // location used for previous timestamp
   1161 
   1162     uint32_t                mUnderrunCountOffset;   // updated when restoring tracks
   1163 
   1164     int64_t                 mFramesWritten;         // total frames written. reset to zero after
   1165                                                     // the start() following stop(). It is not
   1166                                                     // changed after restoring the track or
   1167                                                     // after flush.
   1168     int64_t                 mFramesWrittenServerOffset; // An offset to server frames due to
   1169                                                     // restoring AudioTrack, or stop/start.
   1170                                                     // This offset is also used for static tracks.
   1171     int64_t                 mFramesWrittenAtRestore; // Frames written at restore point (or frames
   1172                                                     // delivered for static tracks).
   1173                                                     // -1 indicates no previous restore point.
   1174 
   1175     audio_output_flags_t    mFlags;                 // same as mOrigFlags, except for bits that may
   1176                                                     // be denied by client or server, such as
   1177                                                     // AUDIO_OUTPUT_FLAG_FAST.  mLock must be
   1178                                                     // held to read or write those bits reliably.
   1179     audio_output_flags_t    mOrigFlags;             // as specified in constructor or set(), const
   1180 
   1181     bool                    mDoNotReconnect;
   1182 
   1183     audio_session_t         mSessionId;
   1184     int                     mAuxEffectId;
   1185     audio_port_handle_t     mPortId;                    // Id from Audio Policy Manager
   1186 
   1187     mutable Mutex           mLock;
   1188 
   1189     int                     mPreviousPriority;          // before start()
   1190     SchedPolicy             mPreviousSchedulingGroup;
   1191     bool                    mAwaitBoost;    // thread should wait for priority boost before running
   1192 
   1193     // The proxy should only be referenced while a lock is held because the proxy isn't
   1194     // multi-thread safe, especially the SingleStateQueue part of the proxy.
   1195     // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
   1196     // provided that the caller also holds an extra reference to the proxy and shared memory to keep
   1197     // them around in case they are replaced during the obtainBuffer().
   1198     sp<StaticAudioTrackClientProxy> mStaticProxy;   // for type safety only
   1199     sp<AudioTrackClientProxy>       mProxy;         // primary owner of the memory
   1200 
   1201     bool                    mInUnderrun;            // whether track is currently in underrun state
   1202     uint32_t                mPausedPosition;
   1203 
   1204     // For Device Selection API
   1205     //  a value of AUDIO_PORT_HANDLE_NONE indicated default (AudioPolicyManager) routing.
   1206     audio_port_handle_t    mSelectedDeviceId; // Device requested by the application.
   1207     audio_port_handle_t    mRoutedDeviceId;   // Device actually selected by audio policy manager:
   1208                                               // May not match the app selection depending on other
   1209                                               // activity and connected devices.
   1210 
   1211     sp<media::VolumeHandler>       mVolumeHandler;
   1212 
   1213 private:
   1214     class DeathNotifier : public IBinder::DeathRecipient {
   1215     public:
   1216         DeathNotifier(AudioTrack* audioTrack) : mAudioTrack(audioTrack) { }
   1217     protected:
   1218         virtual void        binderDied(const wp<IBinder>& who);
   1219     private:
   1220         const wp<AudioTrack> mAudioTrack;
   1221     };
   1222 
   1223     sp<DeathNotifier>       mDeathNotifier;
   1224     uint32_t                mSequence;              // incremented for each new IAudioTrack attempt
   1225     uid_t                   mClientUid;
   1226     pid_t                   mClientPid;
   1227 
   1228     wp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
   1229 
   1230 private:
   1231     class MediaMetrics {
   1232       public:
   1233         MediaMetrics() : mAnalyticsItem(MediaAnalyticsItem::create("audiotrack")) {
   1234         }
   1235         ~MediaMetrics() {
   1236             // mAnalyticsItem alloc failure will be flagged in the constructor
   1237             // don't log empty records
   1238             if (mAnalyticsItem->count() > 0) {
   1239                 mAnalyticsItem->selfrecord();
   1240             }
   1241         }
   1242         void gather(const AudioTrack *track);
   1243         MediaAnalyticsItem *dup() { return mAnalyticsItem->dup(); }
   1244       private:
   1245         std::unique_ptr<MediaAnalyticsItem> mAnalyticsItem;
   1246     };
   1247     MediaMetrics mMediaMetrics;
   1248 };
   1249 
   1250 }; // namespace android
   1251 
   1252 #endif // ANDROID_AUDIOTRACK_H
   1253