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