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