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