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