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 RefBase
     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() const     { return mLatency; }
    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     /* Returns a handle on the audio output used by this AudioTrack.
    568      *
    569      * Parameters:
    570      *  none.
    571      *
    572      * Returned value:
    573      *  handle on audio hardware output, or AUDIO_IO_HANDLE_NONE if the
    574      *  track needed to be re-created but that failed
    575      */
    576 private:
    577             audio_io_handle_t    getOutput() const;
    578 public:
    579 
    580     /* Selects the audio device to use for output of this AudioTrack. A value of
    581      * AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing.
    582      *
    583      * Parameters:
    584      *  The device ID of the selected device (as returned by the AudioDevicesManager API).
    585      *
    586      * Returned value:
    587      *  - NO_ERROR: successful operation
    588      *    TODO: what else can happen here?
    589      */
    590             status_t    setOutputDevice(audio_port_handle_t deviceId);
    591 
    592     /* Returns the ID of the audio device selected for this AudioTrack.
    593      * A value of AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing.
    594      *
    595      * Parameters:
    596      *  none.
    597      */
    598      audio_port_handle_t getOutputDevice();
    599 
    600      /* Returns the ID of the audio device actually used by the output to which this AudioTrack is
    601       * attached.
    602       * A value of AUDIO_PORT_HANDLE_NONE indicates the audio track is not attached to any output.
    603       *
    604       * Parameters:
    605       *  none.
    606       */
    607      audio_port_handle_t getRoutedDeviceId();
    608 
    609     /* Returns the unique session ID associated with this track.
    610      *
    611      * Parameters:
    612      *  none.
    613      *
    614      * Returned value:
    615      *  AudioTrack session ID.
    616      */
    617             audio_session_t getSessionId() const { return mSessionId; }
    618 
    619     /* Attach track auxiliary output to specified effect. Use effectId = 0
    620      * to detach track from effect.
    621      *
    622      * Parameters:
    623      *
    624      * effectId:  effectId obtained from AudioEffect::id().
    625      *
    626      * Returned status (from utils/Errors.h) can be:
    627      *  - NO_ERROR: successful operation
    628      *  - INVALID_OPERATION: the effect is not an auxiliary effect.
    629      *  - BAD_VALUE: The specified effect ID is invalid
    630      */
    631             status_t    attachAuxEffect(int effectId);
    632 
    633     /* Public API for TRANSFER_OBTAIN mode.
    634      * Obtains a buffer of up to "audioBuffer->frameCount" empty slots for frames.
    635      * After filling these slots with data, the caller should release them with releaseBuffer().
    636      * If the track buffer is not full, obtainBuffer() returns as many contiguous
    637      * [empty slots for] frames as are available immediately.
    638      *
    639      * If nonContig is non-NULL, it is an output parameter that will be set to the number of
    640      * additional non-contiguous frames that are predicted to be available immediately,
    641      * if the client were to release the first frames and then call obtainBuffer() again.
    642      * This value is only a prediction, and needs to be confirmed.
    643      * It will be set to zero for an error return.
    644      *
    645      * If the track buffer is full and track is stopped, obtainBuffer() returns WOULD_BLOCK
    646      * regardless of the value of waitCount.
    647      * If the track buffer is full and track is not stopped, obtainBuffer() blocks with a
    648      * maximum timeout based on waitCount; see chart below.
    649      * Buffers will be returned until the pool
    650      * is exhausted, at which point obtainBuffer() will either block
    651      * or return WOULD_BLOCK depending on the value of the "waitCount"
    652      * parameter.
    653      *
    654      * Interpretation of waitCount:
    655      *  +n  limits wait time to n * WAIT_PERIOD_MS,
    656      *  -1  causes an (almost) infinite wait time,
    657      *   0  non-blocking.
    658      *
    659      * Buffer fields
    660      * On entry:
    661      *  frameCount  number of [empty slots for] frames requested
    662      *  size        ignored
    663      *  raw         ignored
    664      * After error return:
    665      *  frameCount  0
    666      *  size        0
    667      *  raw         undefined
    668      * After successful return:
    669      *  frameCount  actual number of [empty slots for] frames available, <= number requested
    670      *  size        actual number of bytes available
    671      *  raw         pointer to the buffer
    672      */
    673             status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount,
    674                                 size_t *nonContig = NULL);
    675 
    676 private:
    677     /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
    678      * additional non-contiguous frames that are predicted to be available immediately,
    679      * if the client were to release the first frames and then call obtainBuffer() again.
    680      * This value is only a prediction, and needs to be confirmed.
    681      * It will be set to zero for an error return.
    682      * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
    683      * in case the requested amount of frames is in two or more non-contiguous regions.
    684      * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
    685      */
    686             status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
    687                                      struct timespec *elapsed = NULL, size_t *nonContig = NULL);
    688 public:
    689 
    690     /* Public API for TRANSFER_OBTAIN mode.
    691      * Release a filled buffer of frames for AudioFlinger to process.
    692      *
    693      * Buffer fields:
    694      *  frameCount  currently ignored but recommend to set to actual number of frames filled
    695      *  size        actual number of bytes filled, must be multiple of frameSize
    696      *  raw         ignored
    697      */
    698             void        releaseBuffer(const Buffer* audioBuffer);
    699 
    700     /* As a convenience we provide a write() interface to the audio buffer.
    701      * Input parameter 'size' is in byte units.
    702      * This is implemented on top of obtainBuffer/releaseBuffer. For best
    703      * performance use callbacks. Returns actual number of bytes written >= 0,
    704      * or one of the following negative status codes:
    705      *      INVALID_OPERATION   AudioTrack is configured for static buffer or streaming mode
    706      *      BAD_VALUE           size is invalid
    707      *      WOULD_BLOCK         when obtainBuffer() returns same, or
    708      *                          AudioTrack was stopped during the write
    709      *      DEAD_OBJECT         when AudioFlinger dies or the output device changes and
    710      *                          the track cannot be automatically restored.
    711      *                          The application needs to recreate the AudioTrack
    712      *                          because the audio device changed or AudioFlinger died.
    713      *                          This typically occurs for direct or offload tracks
    714      *                          or if mDoNotReconnect is true.
    715      *      or any other error code returned by IAudioTrack::start() or restoreTrack_l().
    716      * Default behavior is to only return when all data has been transferred. Set 'blocking' to
    717      * false for the method to return immediately without waiting to try multiple times to write
    718      * the full content of the buffer.
    719      */
    720             ssize_t     write(const void* buffer, size_t size, bool blocking = true);
    721 
    722     /*
    723      * Dumps the state of an audio track.
    724      * Not a general-purpose API; intended only for use by media player service to dump its tracks.
    725      */
    726             status_t    dump(int fd, const Vector<String16>& args) const;
    727 
    728     /*
    729      * Return the total number of frames which AudioFlinger desired but were unavailable,
    730      * and thus which resulted in an underrun.  Reset to zero by stop().
    731      */
    732             uint32_t    getUnderrunFrames() const;
    733 
    734     /* Get the flags */
    735             audio_output_flags_t getFlags() const { AutoMutex _l(mLock); return mFlags; }
    736 
    737     /* Set parameters - only possible when using direct output */
    738             status_t    setParameters(const String8& keyValuePairs);
    739 
    740     /* Sets the volume shaper object */
    741             VolumeShaper::Status applyVolumeShaper(
    742                     const sp<VolumeShaper::Configuration>& configuration,
    743                     const sp<VolumeShaper::Operation>& operation);
    744 
    745     /* Gets the volume shaper state */
    746             sp<VolumeShaper::State> getVolumeShaperState(int id);
    747 
    748     /* Get parameters */
    749             String8     getParameters(const String8& keys);
    750 
    751     /* Poll for a timestamp on demand.
    752      * Use if EVENT_NEW_TIMESTAMP is not delivered often enough for your needs,
    753      * or if you need to get the most recent timestamp outside of the event callback handler.
    754      * Caution: calling this method too often may be inefficient;
    755      * if you need a high resolution mapping between frame position and presentation time,
    756      * consider implementing that at application level, based on the low resolution timestamps.
    757      * Returns NO_ERROR    if timestamp is valid.
    758      *         WOULD_BLOCK if called in STOPPED or FLUSHED state, or if called immediately after
    759      *                     start/ACTIVE, when the number of frames consumed is less than the
    760      *                     overall hardware latency to physical output. In WOULD_BLOCK cases,
    761      *                     one might poll again, or use getPosition(), or use 0 position and
    762      *                     current time for the timestamp.
    763      *         DEAD_OBJECT if AudioFlinger dies or the output device changes and
    764      *                     the track cannot be automatically restored.
    765      *                     The application needs to recreate the AudioTrack
    766      *                     because the audio device changed or AudioFlinger died.
    767      *                     This typically occurs for direct or offload tracks
    768      *                     or if mDoNotReconnect is true.
    769      *         INVALID_OPERATION  wrong state, or some other error.
    770      *
    771      * The timestamp parameter is undefined on return, if status is not NO_ERROR.
    772      */
    773             status_t    getTimestamp(AudioTimestamp& timestamp);
    774 private:
    775             status_t    getTimestamp_l(AudioTimestamp& timestamp);
    776 public:
    777 
    778     /* Return the extended timestamp, with additional timebase info and improved drain behavior.
    779      *
    780      * This is similar to the AudioTrack.java API:
    781      * getTimestamp(@NonNull AudioTimestamp timestamp, @AudioTimestamp.Timebase int timebase)
    782      *
    783      * Some differences between this method and the getTimestamp(AudioTimestamp& timestamp) method
    784      *
    785      *   1. stop() by itself does not reset the frame position.
    786      *      A following start() resets the frame position to 0.
    787      *   2. flush() by itself does not reset the frame position.
    788      *      The frame position advances by the number of frames flushed,
    789      *      when the first frame after flush reaches the audio sink.
    790      *   3. BOOTTIME clock offsets are provided to help synchronize with
    791      *      non-audio streams, e.g. sensor data.
    792      *   4. Position is returned with 64 bits of resolution.
    793      *
    794      * Parameters:
    795      *  timestamp: A pointer to the caller allocated ExtendedTimestamp.
    796      *
    797      * Returns NO_ERROR    on success; timestamp is filled with valid data.
    798      *         BAD_VALUE   if timestamp is NULL.
    799      *         WOULD_BLOCK if called immediately after start() when the number
    800      *                     of frames consumed is less than the
    801      *                     overall hardware latency to physical output. In WOULD_BLOCK cases,
    802      *                     one might poll again, or use getPosition(), or use 0 position and
    803      *                     current time for the timestamp.
    804      *                     If WOULD_BLOCK is returned, the timestamp is still
    805      *                     modified with the LOCATION_CLIENT portion filled.
    806      *         DEAD_OBJECT if AudioFlinger dies or the output device changes and
    807      *                     the track cannot be automatically restored.
    808      *                     The application needs to recreate the AudioTrack
    809      *                     because the audio device changed or AudioFlinger died.
    810      *                     This typically occurs for direct or offloaded tracks
    811      *                     or if mDoNotReconnect is true.
    812      *         INVALID_OPERATION  if called on a offloaded or direct track.
    813      *                     Use getTimestamp(AudioTimestamp& timestamp) instead.
    814      */
    815             status_t getTimestamp(ExtendedTimestamp *timestamp);
    816 private:
    817             status_t getTimestamp_l(ExtendedTimestamp *timestamp);
    818 public:
    819 
    820     /* Add an AudioDeviceCallback. The caller will be notified when the audio device to which this
    821      * AudioTrack is routed is updated.
    822      * Replaces any previously installed callback.
    823      * Parameters:
    824      *  callback:  The callback interface
    825      * Returns NO_ERROR if successful.
    826      *         INVALID_OPERATION if the same callback is already installed.
    827      *         NO_INIT or PREMISSION_DENIED if AudioFlinger service is not reachable
    828      *         BAD_VALUE if the callback is NULL
    829      */
    830             status_t addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback);
    831 
    832     /* remove an AudioDeviceCallback.
    833      * Parameters:
    834      *  callback:  The callback interface
    835      * Returns NO_ERROR if successful.
    836      *         INVALID_OPERATION if the callback is not installed
    837      *         BAD_VALUE if the callback is NULL
    838      */
    839             status_t removeAudioDeviceCallback(
    840                     const sp<AudioSystem::AudioDeviceCallback>& callback);
    841 
    842     /* Obtain the pending duration in milliseconds for playback of pure PCM
    843      * (mixable without embedded timing) data remaining in AudioTrack.
    844      *
    845      * This is used to estimate the drain time for the client-server buffer
    846      * so the choice of ExtendedTimestamp::LOCATION_SERVER is default.
    847      * One may optionally request to find the duration to play through the HAL
    848      * by specifying a location ExtendedTimestamp::LOCATION_KERNEL; however,
    849      * INVALID_OPERATION may be returned if the kernel location is unavailable.
    850      *
    851      * Returns NO_ERROR  if successful.
    852      *         INVALID_OPERATION if ExtendedTimestamp::LOCATION_KERNEL cannot be obtained
    853      *                   or the AudioTrack does not contain pure PCM data.
    854      *         BAD_VALUE if msec is nullptr or location is invalid.
    855      */
    856             status_t pendingDuration(int32_t *msec,
    857                     ExtendedTimestamp::Location location = ExtendedTimestamp::LOCATION_SERVER);
    858 
    859     /* hasStarted() is used to determine if audio is now audible at the device after
    860      * a start() command. The underlying implementation checks a nonzero timestamp position
    861      * or increment for the audible assumption.
    862      *
    863      * hasStarted() returns true if the track has been started() and audio is audible
    864      * and no subsequent pause() or flush() has been called.  Immediately after pause() or
    865      * flush() hasStarted() will return false.
    866      *
    867      * If stop() has been called, hasStarted() will return true if audio is still being
    868      * delivered or has finished delivery (even if no audio was written) for both offloaded
    869      * and normal tracks. This property removes a race condition in checking hasStarted()
    870      * for very short clips, where stop() must be called to finish drain.
    871      *
    872      * In all cases, hasStarted() may turn false briefly after a subsequent start() is called
    873      * until audio becomes audible again.
    874      */
    875             bool hasStarted(); // not const
    876 
    877             bool isPlaying() {
    878                 AutoMutex lock(mLock);
    879                 return mState == STATE_ACTIVE || mState == STATE_STOPPING;
    880             }
    881 protected:
    882     /* copying audio tracks is not allowed */
    883                         AudioTrack(const AudioTrack& other);
    884             AudioTrack& operator = (const AudioTrack& other);
    885 
    886     /* a small internal class to handle the callback */
    887     class AudioTrackThread : public Thread
    888     {
    889     public:
    890         AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
    891 
    892         // Do not call Thread::requestExitAndWait() without first calling requestExit().
    893         // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
    894         virtual void        requestExit();
    895 
    896                 void        pause();    // suspend thread from execution at next loop boundary
    897                 void        resume();   // allow thread to execute, if not requested to exit
    898                 void        wake();     // wake to handle changed notification conditions.
    899 
    900     private:
    901                 void        pauseInternal(nsecs_t ns = 0LL);
    902                                         // like pause(), but only used internally within thread
    903 
    904         friend class AudioTrack;
    905         virtual bool        threadLoop();
    906         AudioTrack&         mReceiver;
    907         virtual ~AudioTrackThread();
    908         Mutex               mMyLock;    // Thread::mLock is private
    909         Condition           mMyCond;    // Thread::mThreadExitedCondition is private
    910         bool                mPaused;    // whether thread is requested to pause at next loop entry
    911         bool                mPausedInt; // whether thread internally requests pause
    912         nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
    913         bool                mIgnoreNextPausedInt;   // skip any internal pause and go immediately
    914                                         // to processAudioBuffer() as state may have changed
    915                                         // since pause time calculated.
    916     };
    917 
    918             // body of AudioTrackThread::threadLoop()
    919             // returns the maximum amount of time before we would like to run again, where:
    920             //      0           immediately
    921             //      > 0         no later than this many nanoseconds from now
    922             //      NS_WHENEVER still active but no particular deadline
    923             //      NS_INACTIVE inactive so don't run again until re-started
    924             //      NS_NEVER    never again
    925             static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
    926             nsecs_t processAudioBuffer();
    927 
    928             // caller must hold lock on mLock for all _l methods
    929 
    930             status_t createTrack_l();
    931 
    932             // can only be called when mState != STATE_ACTIVE
    933             void flush_l();
    934 
    935             void setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
    936 
    937             // FIXME enum is faster than strcmp() for parameter 'from'
    938             status_t restoreTrack_l(const char *from);
    939 
    940             uint32_t    getUnderrunCount_l() const;
    941 
    942             bool     isOffloaded() const;
    943             bool     isDirect() const;
    944             bool     isOffloadedOrDirect() const;
    945 
    946             bool     isOffloaded_l() const
    947                 { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; }
    948 
    949             bool     isOffloadedOrDirect_l() const
    950                 { return (mFlags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD|
    951                                                 AUDIO_OUTPUT_FLAG_DIRECT)) != 0; }
    952 
    953             bool     isDirect_l() const
    954                 { return (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0; }
    955 
    956             // pure pcm data is mixable (which excludes HW_AV_SYNC, with embedded timing)
    957             bool     isPurePcmData_l() const
    958                 { return audio_is_linear_pcm(mFormat)
    959                         && (mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) == 0; }
    960 
    961             // increment mPosition by the delta of mServer, and return new value of mPosition
    962             Modulo<uint32_t> updateAndGetPosition_l();
    963 
    964             // check sample rate and speed is compatible with AudioTrack
    965             bool     isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const;
    966 
    967             void     restartIfDisabled();
    968 
    969     // Next 4 fields may be changed if IAudioTrack is re-created, but always != 0
    970     sp<IAudioTrack>         mAudioTrack;
    971     sp<IMemory>             mCblkMemory;
    972     audio_track_cblk_t*     mCblk;                  // re-load after mLock.unlock()
    973     audio_io_handle_t       mOutput;                // returned by AudioSystem::getOutput()
    974 
    975     sp<AudioTrackThread>    mAudioTrackThread;
    976     bool                    mThreadCanCallJava;
    977 
    978     float                   mVolume[2];
    979     float                   mSendLevel;
    980     mutable uint32_t        mSampleRate;            // mutable because getSampleRate() can update it
    981     uint32_t                mOriginalSampleRate;
    982     AudioPlaybackRate       mPlaybackRate;
    983     float                   mMaxRequiredSpeed;      // use PCM buffer size to allow this speed
    984 
    985     // Corresponds to current IAudioTrack, value is reported back by AudioFlinger to the client.
    986     // This allocated buffer size is maintained by the proxy.
    987     size_t                  mFrameCount;            // maximum size of buffer
    988 
    989     size_t                  mReqFrameCount;         // frame count to request the first or next time
    990                                                     // a new IAudioTrack is needed, non-decreasing
    991 
    992     // The following AudioFlinger server-side values are cached in createAudioTrack_l().
    993     // These values can be used for informational purposes until the track is invalidated,
    994     // whereupon restoreTrack_l() calls createTrack_l() to update the values.
    995     uint32_t                mAfLatency;             // AudioFlinger latency in ms
    996     size_t                  mAfFrameCount;          // AudioFlinger frame count
    997     uint32_t                mAfSampleRate;          // AudioFlinger sample rate
    998 
    999     // constant after constructor or set()
   1000     audio_format_t          mFormat;                // as requested by client, not forced to 16-bit
   1001     audio_stream_type_t     mStreamType;            // mStreamType == AUDIO_STREAM_DEFAULT implies
   1002                                                     // this AudioTrack has valid attributes
   1003     uint32_t                mChannelCount;
   1004     audio_channel_mask_t    mChannelMask;
   1005     sp<IMemory>             mSharedBuffer;
   1006     transfer_type           mTransfer;
   1007     audio_offload_info_t    mOffloadInfoCopy;
   1008     const audio_offload_info_t* mOffloadInfo;
   1009     audio_attributes_t      mAttributes;
   1010 
   1011     size_t                  mFrameSize;             // frame size in bytes
   1012 
   1013     status_t                mStatus;
   1014 
   1015     // can change dynamically when IAudioTrack invalidated
   1016     uint32_t                mLatency;               // in ms
   1017 
   1018     // Indicates the current track state.  Protected by mLock.
   1019     enum State {
   1020         STATE_ACTIVE,
   1021         STATE_STOPPED,
   1022         STATE_PAUSED,
   1023         STATE_PAUSED_STOPPING,
   1024         STATE_FLUSHED,
   1025         STATE_STOPPING,
   1026     }                       mState;
   1027 
   1028     // for client callback handler
   1029     callback_t              mCbf;                   // callback handler for events, or NULL
   1030     void*                   mUserData;
   1031 
   1032     // for notification APIs
   1033 
   1034     // next 2 fields are const after constructor or set()
   1035     uint32_t                mNotificationFramesReq; // requested number of frames between each
   1036                                                     // notification callback,
   1037                                                     // at initial source sample rate
   1038     uint32_t                mNotificationsPerBufferReq;
   1039                                                     // requested number of notifications per buffer,
   1040                                                     // currently only used for fast tracks with
   1041                                                     // default track buffer size
   1042 
   1043     uint32_t                mNotificationFramesAct; // actual number of frames between each
   1044                                                     // notification callback,
   1045                                                     // at initial source sample rate
   1046     bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
   1047                                                     // mRemainingFrames and mRetryOnPartialBuffer
   1048 
   1049                                                     // used for static track cbf and restoration
   1050     int32_t                 mLoopCount;             // last setLoop loopCount; zero means disabled
   1051     uint32_t                mLoopStart;             // last setLoop loopStart
   1052     uint32_t                mLoopEnd;               // last setLoop loopEnd
   1053     int32_t                 mLoopCountNotified;     // the last loopCount notified by callback.
   1054                                                     // mLoopCountNotified counts down, matching
   1055                                                     // the remaining loop count for static track
   1056                                                     // playback.
   1057 
   1058     // These are private to processAudioBuffer(), and are not protected by a lock
   1059     uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
   1060     bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
   1061     uint32_t                mObservedSequence;      // last observed value of mSequence
   1062 
   1063     Modulo<uint32_t>        mMarkerPosition;        // in wrapping (overflow) frame units
   1064     bool                    mMarkerReached;
   1065     Modulo<uint32_t>        mNewPosition;           // in frames
   1066     uint32_t                mUpdatePeriod;          // in frames, zero means no EVENT_NEW_POS
   1067 
   1068     Modulo<uint32_t>        mServer;                // in frames, last known mProxy->getPosition()
   1069                                                     // which is count of frames consumed by server,
   1070                                                     // reset by new IAudioTrack,
   1071                                                     // whether it is reset by stop() is TBD
   1072     Modulo<uint32_t>        mPosition;              // in frames, like mServer except continues
   1073                                                     // monotonically after new IAudioTrack,
   1074                                                     // and could be easily widened to uint64_t
   1075     Modulo<uint32_t>        mReleased;              // count of frames released to server
   1076                                                     // but not necessarily consumed by server,
   1077                                                     // reset by stop() but continues monotonically
   1078                                                     // after new IAudioTrack to restore mPosition,
   1079                                                     // and could be easily widened to uint64_t
   1080     int64_t                 mStartUs;               // the start time after flush or stop.
   1081                                                     // only used for offloaded and direct tracks.
   1082     ExtendedTimestamp       mStartEts;              // Extended timestamp at start for normal
   1083                                                     // AudioTracks.
   1084     AudioTimestamp          mStartTs;               // Timestamp at start for offloaded or direct
   1085                                                     // AudioTracks.
   1086 
   1087     bool                    mPreviousTimestampValid;// true if mPreviousTimestamp is valid
   1088     bool                    mTimestampStartupGlitchReported; // reduce log spam
   1089     bool                    mRetrogradeMotionReported; // reduce log spam
   1090     AudioTimestamp          mPreviousTimestamp;     // used to detect retrograde motion
   1091     ExtendedTimestamp::Location mPreviousLocation;  // location used for previous timestamp
   1092 
   1093     uint32_t                mUnderrunCountOffset;   // updated when restoring tracks
   1094 
   1095     int64_t                 mFramesWritten;         // total frames written. reset to zero after
   1096                                                     // the start() following stop(). It is not
   1097                                                     // changed after restoring the track or
   1098                                                     // after flush.
   1099     int64_t                 mFramesWrittenServerOffset; // An offset to server frames due to
   1100                                                     // restoring AudioTrack, or stop/start.
   1101                                                     // This offset is also used for static tracks.
   1102     int64_t                 mFramesWrittenAtRestore; // Frames written at restore point (or frames
   1103                                                     // delivered for static tracks).
   1104                                                     // -1 indicates no previous restore point.
   1105 
   1106     audio_output_flags_t    mFlags;                 // same as mOrigFlags, except for bits that may
   1107                                                     // be denied by client or server, such as
   1108                                                     // AUDIO_OUTPUT_FLAG_FAST.  mLock must be
   1109                                                     // held to read or write those bits reliably.
   1110     audio_output_flags_t    mOrigFlags;             // as specified in constructor or set(), const
   1111 
   1112     bool                    mDoNotReconnect;
   1113 
   1114     audio_session_t         mSessionId;
   1115     int                     mAuxEffectId;
   1116 
   1117     mutable Mutex           mLock;
   1118 
   1119     int                     mPreviousPriority;          // before start()
   1120     SchedPolicy             mPreviousSchedulingGroup;
   1121     bool                    mAwaitBoost;    // thread should wait for priority boost before running
   1122 
   1123     // The proxy should only be referenced while a lock is held because the proxy isn't
   1124     // multi-thread safe, especially the SingleStateQueue part of the proxy.
   1125     // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
   1126     // provided that the caller also holds an extra reference to the proxy and shared memory to keep
   1127     // them around in case they are replaced during the obtainBuffer().
   1128     sp<StaticAudioTrackClientProxy> mStaticProxy;   // for type safety only
   1129     sp<AudioTrackClientProxy>       mProxy;         // primary owner of the memory
   1130 
   1131     bool                    mInUnderrun;            // whether track is currently in underrun state
   1132     uint32_t                mPausedPosition;
   1133 
   1134     // For Device Selection API
   1135     //  a value of AUDIO_PORT_HANDLE_NONE indicated default (AudioPolicyManager) routing.
   1136     audio_port_handle_t     mSelectedDeviceId;
   1137 
   1138     sp<VolumeHandler>       mVolumeHandler;
   1139 
   1140 private:
   1141     class DeathNotifier : public IBinder::DeathRecipient {
   1142     public:
   1143         DeathNotifier(AudioTrack* audioTrack) : mAudioTrack(audioTrack) { }
   1144     protected:
   1145         virtual void        binderDied(const wp<IBinder>& who);
   1146     private:
   1147         const wp<AudioTrack> mAudioTrack;
   1148     };
   1149 
   1150     sp<DeathNotifier>       mDeathNotifier;
   1151     uint32_t                mSequence;              // incremented for each new IAudioTrack attempt
   1152     uid_t                   mClientUid;
   1153     pid_t                   mClientPid;
   1154 
   1155     sp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
   1156     audio_port_handle_t     mPortId;  // unique ID allocated by audio policy
   1157 };
   1158 
   1159 }; // namespace android
   1160 
   1161 #endif // ANDROID_AUDIOTRACK_H
   1162