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