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