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