AudioTrack.h revision 92d23b433bd770c22c2d4a30b573602f5565de1b
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    /* Get parameters */
769            String8     getParameters(const String8& keys);
770
771    /* Poll for a timestamp on demand.
772     * Use if EVENT_NEW_TIMESTAMP is not delivered often enough for your needs,
773     * or if you need to get the most recent timestamp outside of the event callback handler.
774     * Caution: calling this method too often may be inefficient;
775     * if you need a high resolution mapping between frame position and presentation time,
776     * consider implementing that at application level, based on the low resolution timestamps.
777     * Returns NO_ERROR    if timestamp is valid.
778     *         WOULD_BLOCK if called in STOPPED or FLUSHED state, or if called immediately after
779     *                     start/ACTIVE, when the number of frames consumed is less than the
780     *                     overall hardware latency to physical output. In WOULD_BLOCK cases,
781     *                     one might poll again, or use getPosition(), or use 0 position and
782     *                     current time for the timestamp.
783     *         DEAD_OBJECT if AudioFlinger dies or the output device changes and
784     *                     the track cannot be automatically restored.
785     *                     The application needs to recreate the AudioTrack
786     *                     because the audio device changed or AudioFlinger died.
787     *                     This typically occurs for direct or offload tracks
788     *                     or if mDoNotReconnect is true.
789     *         INVALID_OPERATION  wrong state, or some other error.
790     *
791     * The timestamp parameter is undefined on return, if status is not NO_ERROR.
792     */
793            status_t    getTimestamp(AudioTimestamp& timestamp);
794private:
795            status_t    getTimestamp_l(AudioTimestamp& timestamp);
796public:
797
798    /* Return the extended timestamp, with additional timebase info and improved drain behavior.
799     *
800     * This is similar to the AudioTrack.java API:
801     * getTimestamp(@NonNull AudioTimestamp timestamp, @AudioTimestamp.Timebase int timebase)
802     *
803     * Some differences between this method and the getTimestamp(AudioTimestamp& timestamp) method
804     *
805     *   1. stop() by itself does not reset the frame position.
806     *      A following start() resets the frame position to 0.
807     *   2. flush() by itself does not reset the frame position.
808     *      The frame position advances by the number of frames flushed,
809     *      when the first frame after flush reaches the audio sink.
810     *   3. BOOTTIME clock offsets are provided to help synchronize with
811     *      non-audio streams, e.g. sensor data.
812     *   4. Position is returned with 64 bits of resolution.
813     *
814     * Parameters:
815     *  timestamp: A pointer to the caller allocated ExtendedTimestamp.
816     *
817     * Returns NO_ERROR    on success; timestamp is filled with valid data.
818     *         BAD_VALUE   if timestamp is NULL.
819     *         WOULD_BLOCK if called immediately after start() when the number
820     *                     of frames consumed is less than the
821     *                     overall hardware latency to physical output. In WOULD_BLOCK cases,
822     *                     one might poll again, or use getPosition(), or use 0 position and
823     *                     current time for the timestamp.
824     *                     If WOULD_BLOCK is returned, the timestamp is still
825     *                     modified with the LOCATION_CLIENT portion filled.
826     *         DEAD_OBJECT if AudioFlinger dies or the output device changes and
827     *                     the track cannot be automatically restored.
828     *                     The application needs to recreate the AudioTrack
829     *                     because the audio device changed or AudioFlinger died.
830     *                     This typically occurs for direct or offloaded tracks
831     *                     or if mDoNotReconnect is true.
832     *         INVALID_OPERATION  if called on a offloaded or direct track.
833     *                     Use getTimestamp(AudioTimestamp& timestamp) instead.
834     */
835            status_t getTimestamp(ExtendedTimestamp *timestamp);
836private:
837            status_t getTimestamp_l(ExtendedTimestamp *timestamp);
838public:
839
840    /* Add an AudioDeviceCallback. The caller will be notified when the audio device to which this
841     * AudioTrack is routed is updated.
842     * Replaces any previously installed callback.
843     * Parameters:
844     *  callback:  The callback interface
845     * Returns NO_ERROR if successful.
846     *         INVALID_OPERATION if the same callback is already installed.
847     *         NO_INIT or PREMISSION_DENIED if AudioFlinger service is not reachable
848     *         BAD_VALUE if the callback is NULL
849     */
850            status_t addAudioDeviceCallback(const sp<AudioSystem::AudioDeviceCallback>& callback);
851
852    /* remove an AudioDeviceCallback.
853     * Parameters:
854     *  callback:  The callback interface
855     * Returns NO_ERROR if successful.
856     *         INVALID_OPERATION if the callback is not installed
857     *         BAD_VALUE if the callback is NULL
858     */
859            status_t removeAudioDeviceCallback(
860                    const sp<AudioSystem::AudioDeviceCallback>& callback);
861
862            // AudioSystem::AudioDeviceCallback> virtuals
863            virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo,
864                                             audio_port_handle_t deviceId);
865
866
867
868    /* Obtain the pending duration in milliseconds for playback of pure PCM
869     * (mixable without embedded timing) data remaining in AudioTrack.
870     *
871     * This is used to estimate the drain time for the client-server buffer
872     * so the choice of ExtendedTimestamp::LOCATION_SERVER is default.
873     * One may optionally request to find the duration to play through the HAL
874     * by specifying a location ExtendedTimestamp::LOCATION_KERNEL; however,
875     * INVALID_OPERATION may be returned if the kernel location is unavailable.
876     *
877     * Returns NO_ERROR  if successful.
878     *         INVALID_OPERATION if ExtendedTimestamp::LOCATION_KERNEL cannot be obtained
879     *                   or the AudioTrack does not contain pure PCM data.
880     *         BAD_VALUE if msec is nullptr or location is invalid.
881     */
882            status_t pendingDuration(int32_t *msec,
883                    ExtendedTimestamp::Location location = ExtendedTimestamp::LOCATION_SERVER);
884
885    /* hasStarted() is used to determine if audio is now audible at the device after
886     * a start() command. The underlying implementation checks a nonzero timestamp position
887     * or increment for the audible assumption.
888     *
889     * hasStarted() returns true if the track has been started() and audio is audible
890     * and no subsequent pause() or flush() has been called.  Immediately after pause() or
891     * flush() hasStarted() will return false.
892     *
893     * If stop() has been called, hasStarted() will return true if audio is still being
894     * delivered or has finished delivery (even if no audio was written) for both offloaded
895     * and normal tracks. This property removes a race condition in checking hasStarted()
896     * for very short clips, where stop() must be called to finish drain.
897     *
898     * In all cases, hasStarted() may turn false briefly after a subsequent start() is called
899     * until audio becomes audible again.
900     */
901            bool hasStarted(); // not const
902
903            bool isPlaying() {
904                AutoMutex lock(mLock);
905                return mState == STATE_ACTIVE || mState == STATE_STOPPING;
906            }
907protected:
908    /* copying audio tracks is not allowed */
909                        AudioTrack(const AudioTrack& other);
910            AudioTrack& operator = (const AudioTrack& other);
911
912    /* a small internal class to handle the callback */
913    class AudioTrackThread : public Thread
914    {
915    public:
916        AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
917
918        // Do not call Thread::requestExitAndWait() without first calling requestExit().
919        // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
920        virtual void        requestExit();
921
922                void        pause();    // suspend thread from execution at next loop boundary
923                void        resume();   // allow thread to execute, if not requested to exit
924                void        wake();     // wake to handle changed notification conditions.
925
926    private:
927                void        pauseInternal(nsecs_t ns = 0LL);
928                                        // like pause(), but only used internally within thread
929
930        friend class AudioTrack;
931        virtual bool        threadLoop();
932        AudioTrack&         mReceiver;
933        virtual ~AudioTrackThread();
934        Mutex               mMyLock;    // Thread::mLock is private
935        Condition           mMyCond;    // Thread::mThreadExitedCondition is private
936        bool                mPaused;    // whether thread is requested to pause at next loop entry
937        bool                mPausedInt; // whether thread internally requests pause
938        nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
939        bool                mIgnoreNextPausedInt;   // skip any internal pause and go immediately
940                                        // to processAudioBuffer() as state may have changed
941                                        // since pause time calculated.
942    };
943
944            // body of AudioTrackThread::threadLoop()
945            // returns the maximum amount of time before we would like to run again, where:
946            //      0           immediately
947            //      > 0         no later than this many nanoseconds from now
948            //      NS_WHENEVER still active but no particular deadline
949            //      NS_INACTIVE inactive so don't run again until re-started
950            //      NS_NEVER    never again
951            static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
952            nsecs_t processAudioBuffer();
953
954            // caller must hold lock on mLock for all _l methods
955
956            void updateLatency_l(); // updates mAfLatency and mLatency from AudioSystem cache
957
958            status_t createTrack_l();
959
960            // can only be called when mState != STATE_ACTIVE
961            void flush_l();
962
963            void setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
964
965            // FIXME enum is faster than strcmp() for parameter 'from'
966            status_t restoreTrack_l(const char *from);
967
968            uint32_t    getUnderrunCount_l() const;
969
970            bool     isOffloaded() const;
971            bool     isDirect() const;
972            bool     isOffloadedOrDirect() const;
973
974            bool     isOffloaded_l() const
975                { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; }
976
977            bool     isOffloadedOrDirect_l() const
978                { return (mFlags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD|
979                                                AUDIO_OUTPUT_FLAG_DIRECT)) != 0; }
980
981            bool     isDirect_l() const
982                { return (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0; }
983
984            // pure pcm data is mixable (which excludes HW_AV_SYNC, with embedded timing)
985            bool     isPurePcmData_l() const
986                { return audio_is_linear_pcm(mFormat)
987                        && (mAttributes.flags & AUDIO_FLAG_HW_AV_SYNC) == 0; }
988
989            // increment mPosition by the delta of mServer, and return new value of mPosition
990            Modulo<uint32_t> updateAndGetPosition_l();
991
992            // check sample rate and speed is compatible with AudioTrack
993            bool     isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed);
994
995            void     restartIfDisabled();
996
997            void     updateRoutedDeviceId_l();
998
999    // Next 4 fields may be changed if IAudioTrack is re-created, but always != 0
1000    sp<IAudioTrack>         mAudioTrack;
1001    sp<IMemory>             mCblkMemory;
1002    audio_track_cblk_t*     mCblk;                  // re-load after mLock.unlock()
1003    audio_io_handle_t       mOutput;                // returned by AudioSystem::getOutputForAttr()
1004
1005    sp<AudioTrackThread>    mAudioTrackThread;
1006    bool                    mThreadCanCallJava;
1007
1008    float                   mVolume[2];
1009    float                   mSendLevel;
1010    mutable uint32_t        mSampleRate;            // mutable because getSampleRate() can update it
1011    uint32_t                mOriginalSampleRate;
1012    AudioPlaybackRate       mPlaybackRate;
1013    float                   mMaxRequiredSpeed;      // use PCM buffer size to allow this speed
1014
1015    // Corresponds to current IAudioTrack, value is reported back by AudioFlinger to the client.
1016    // This allocated buffer size is maintained by the proxy.
1017    size_t                  mFrameCount;            // maximum size of buffer
1018
1019    size_t                  mReqFrameCount;         // frame count to request the first or next time
1020                                                    // a new IAudioTrack is needed, non-decreasing
1021
1022    // The following AudioFlinger server-side values are cached in createAudioTrack_l().
1023    // These values can be used for informational purposes until the track is invalidated,
1024    // whereupon restoreTrack_l() calls createTrack_l() to update the values.
1025    uint32_t                mAfLatency;             // AudioFlinger latency in ms
1026    size_t                  mAfFrameCount;          // AudioFlinger frame count
1027    uint32_t                mAfSampleRate;          // AudioFlinger sample rate
1028
1029    // constant after constructor or set()
1030    audio_format_t          mFormat;                // as requested by client, not forced to 16-bit
1031    audio_stream_type_t     mStreamType;            // mStreamType == AUDIO_STREAM_DEFAULT implies
1032                                                    // this AudioTrack has valid attributes
1033    uint32_t                mChannelCount;
1034    audio_channel_mask_t    mChannelMask;
1035    sp<IMemory>             mSharedBuffer;
1036    transfer_type           mTransfer;
1037    audio_offload_info_t    mOffloadInfoCopy;
1038    const audio_offload_info_t* mOffloadInfo;
1039    audio_attributes_t      mAttributes;
1040
1041    size_t                  mFrameSize;             // frame size in bytes
1042
1043    status_t                mStatus;
1044
1045    // can change dynamically when IAudioTrack invalidated
1046    uint32_t                mLatency;               // in ms
1047
1048    // Indicates the current track state.  Protected by mLock.
1049    enum State {
1050        STATE_ACTIVE,
1051        STATE_STOPPED,
1052        STATE_PAUSED,
1053        STATE_PAUSED_STOPPING,
1054        STATE_FLUSHED,
1055        STATE_STOPPING,
1056    }                       mState;
1057
1058    // for client callback handler
1059    callback_t              mCbf;                   // callback handler for events, or NULL
1060    void*                   mUserData;
1061
1062    // for notification APIs
1063
1064    // next 2 fields are const after constructor or set()
1065    uint32_t                mNotificationFramesReq; // requested number of frames between each
1066                                                    // notification callback,
1067                                                    // at initial source sample rate
1068    uint32_t                mNotificationsPerBufferReq;
1069                                                    // requested number of notifications per buffer,
1070                                                    // currently only used for fast tracks with
1071                                                    // default track buffer size
1072
1073    uint32_t                mNotificationFramesAct; // actual number of frames between each
1074                                                    // notification callback,
1075                                                    // at initial source sample rate
1076    bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
1077                                                    // mRemainingFrames and mRetryOnPartialBuffer
1078
1079                                                    // used for static track cbf and restoration
1080    int32_t                 mLoopCount;             // last setLoop loopCount; zero means disabled
1081    uint32_t                mLoopStart;             // last setLoop loopStart
1082    uint32_t                mLoopEnd;               // last setLoop loopEnd
1083    int32_t                 mLoopCountNotified;     // the last loopCount notified by callback.
1084                                                    // mLoopCountNotified counts down, matching
1085                                                    // the remaining loop count for static track
1086                                                    // playback.
1087
1088    // These are private to processAudioBuffer(), and are not protected by a lock
1089    uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
1090    bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
1091    uint32_t                mObservedSequence;      // last observed value of mSequence
1092
1093    Modulo<uint32_t>        mMarkerPosition;        // in wrapping (overflow) frame units
1094    bool                    mMarkerReached;
1095    Modulo<uint32_t>        mNewPosition;           // in frames
1096    uint32_t                mUpdatePeriod;          // in frames, zero means no EVENT_NEW_POS
1097
1098    Modulo<uint32_t>        mServer;                // in frames, last known mProxy->getPosition()
1099                                                    // which is count of frames consumed by server,
1100                                                    // reset by new IAudioTrack,
1101                                                    // whether it is reset by stop() is TBD
1102    Modulo<uint32_t>        mPosition;              // in frames, like mServer except continues
1103                                                    // monotonically after new IAudioTrack,
1104                                                    // and could be easily widened to uint64_t
1105    Modulo<uint32_t>        mReleased;              // count of frames released to server
1106                                                    // but not necessarily consumed by server,
1107                                                    // reset by stop() but continues monotonically
1108                                                    // after new IAudioTrack to restore mPosition,
1109                                                    // and could be easily widened to uint64_t
1110    int64_t                 mStartFromZeroUs;       // the start time after flush or stop,
1111                                                    // when position should be 0.
1112                                                    // only used for offloaded and direct tracks.
1113    int64_t                 mStartNs;               // the time when start() is called.
1114    ExtendedTimestamp       mStartEts;              // Extended timestamp at start for normal
1115                                                    // AudioTracks.
1116    AudioTimestamp          mStartTs;               // Timestamp at start for offloaded or direct
1117                                                    // AudioTracks.
1118
1119    bool                    mPreviousTimestampValid;// true if mPreviousTimestamp is valid
1120    bool                    mTimestampStartupGlitchReported; // reduce log spam
1121    bool                    mRetrogradeMotionReported; // reduce log spam
1122    AudioTimestamp          mPreviousTimestamp;     // used to detect retrograde motion
1123    ExtendedTimestamp::Location mPreviousLocation;  // location used for previous timestamp
1124
1125    uint32_t                mUnderrunCountOffset;   // updated when restoring tracks
1126
1127    int64_t                 mFramesWritten;         // total frames written. reset to zero after
1128                                                    // the start() following stop(). It is not
1129                                                    // changed after restoring the track or
1130                                                    // after flush.
1131    int64_t                 mFramesWrittenServerOffset; // An offset to server frames due to
1132                                                    // restoring AudioTrack, or stop/start.
1133                                                    // This offset is also used for static tracks.
1134    int64_t                 mFramesWrittenAtRestore; // Frames written at restore point (or frames
1135                                                    // delivered for static tracks).
1136                                                    // -1 indicates no previous restore point.
1137
1138    audio_output_flags_t    mFlags;                 // same as mOrigFlags, except for bits that may
1139                                                    // be denied by client or server, such as
1140                                                    // AUDIO_OUTPUT_FLAG_FAST.  mLock must be
1141                                                    // held to read or write those bits reliably.
1142    audio_output_flags_t    mOrigFlags;             // as specified in constructor or set(), const
1143
1144    bool                    mDoNotReconnect;
1145
1146    audio_session_t         mSessionId;
1147    int                     mAuxEffectId;
1148
1149    mutable Mutex           mLock;
1150
1151    int                     mPreviousPriority;          // before start()
1152    SchedPolicy             mPreviousSchedulingGroup;
1153    bool                    mAwaitBoost;    // thread should wait for priority boost before running
1154
1155    // The proxy should only be referenced while a lock is held because the proxy isn't
1156    // multi-thread safe, especially the SingleStateQueue part of the proxy.
1157    // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
1158    // provided that the caller also holds an extra reference to the proxy and shared memory to keep
1159    // them around in case they are replaced during the obtainBuffer().
1160    sp<StaticAudioTrackClientProxy> mStaticProxy;   // for type safety only
1161    sp<AudioTrackClientProxy>       mProxy;         // primary owner of the memory
1162
1163    bool                    mInUnderrun;            // whether track is currently in underrun state
1164    uint32_t                mPausedPosition;
1165
1166    // For Device Selection API
1167    //  a value of AUDIO_PORT_HANDLE_NONE indicated default (AudioPolicyManager) routing.
1168    audio_port_handle_t    mSelectedDeviceId; // Device requested by the application.
1169    audio_port_handle_t    mRoutedDeviceId;   // Device actually selected by audio policy manager:
1170                                              // May not match the app selection depending on other
1171                                              // activity and connected devices.
1172
1173    sp<media::VolumeHandler>       mVolumeHandler;
1174
1175private:
1176    class DeathNotifier : public IBinder::DeathRecipient {
1177    public:
1178        DeathNotifier(AudioTrack* audioTrack) : mAudioTrack(audioTrack) { }
1179    protected:
1180        virtual void        binderDied(const wp<IBinder>& who);
1181    private:
1182        const wp<AudioTrack> mAudioTrack;
1183    };
1184
1185    sp<DeathNotifier>       mDeathNotifier;
1186    uint32_t                mSequence;              // incremented for each new IAudioTrack attempt
1187    uid_t                   mClientUid;
1188    pid_t                   mClientPid;
1189
1190    wp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
1191
1192private:
1193    class MediaMetrics {
1194      public:
1195        MediaMetrics() : mAnalyticsItem(new MediaAnalyticsItem("audiotrack")) {
1196        }
1197        ~MediaMetrics() {
1198            // mAnalyticsItem alloc failure will be flagged in the constructor
1199            // don't log empty records
1200            if (mAnalyticsItem->count() > 0) {
1201                mAnalyticsItem->selfrecord();
1202            }
1203        }
1204        void gather(const AudioTrack *track);
1205        MediaAnalyticsItem *dup() { return mAnalyticsItem->dup(); }
1206      private:
1207        std::unique_ptr<MediaAnalyticsItem> mAnalyticsItem;
1208    };
1209    MediaMetrics mMediaMetrics;
1210};
1211
1212}; // namespace android
1213
1214#endif // ANDROID_AUDIOTRACK_H
1215