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