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