AudioTrack.h revision 0ca3cf94c0dfc173ad7886ae162c4b67067539f6
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 <stdint.h>
21#include <sys/types.h>
22
23#include <media/IAudioFlinger.h>
24#include <media/IAudioTrack.h>
25#include <media/AudioSystem.h>
26
27#include <utils/RefBase.h>
28#include <utils/Errors.h>
29#include <binder/IInterface.h>
30#include <binder/IMemory.h>
31#include <utils/threads.h>
32
33namespace android {
34
35// ----------------------------------------------------------------------------
36
37class audio_track_cblk_t;
38
39// ----------------------------------------------------------------------------
40
41class AudioTrack : virtual public RefBase
42{
43public:
44    enum channel_index {
45        MONO   = 0,
46        LEFT   = 0,
47        RIGHT  = 1
48    };
49
50    /* Events used by AudioTrack callback function (audio_track_cblk_t).
51     */
52    enum event_type {
53        EVENT_MORE_DATA = 0,        // Request to write more data to PCM buffer.
54        EVENT_UNDERRUN = 1,         // PCM buffer underrun occured.
55        EVENT_LOOP_END = 2,         // Sample loop end was reached; playback restarted from loop start if loop count was not 0.
56        EVENT_MARKER = 3,           // Playback head is at the specified marker position (See setMarkerPosition()).
57        EVENT_NEW_POS = 4,          // Playback head is at a new position (See setPositionUpdatePeriod()).
58        EVENT_BUFFER_END = 5        // Playback head is at the end of the buffer.
59    };
60
61    /* Client should declare Buffer on the stack and pass address to obtainBuffer()
62     * and releaseBuffer().  See also callback_t for EVENT_MORE_DATA.
63     */
64
65    class Buffer
66    {
67    public:
68        enum {
69            MUTE    = 0x00000001
70        };
71        uint32_t    flags;        // 0 or MUTE
72        audio_format_t format; // but AUDIO_FORMAT_PCM_8_BIT -> AUDIO_FORMAT_PCM_16_BIT
73        // accessed directly by WebKit ANP callback
74        int         channelCount; // will be removed in the future, do not use
75
76        size_t      frameCount;   // number of sample frames corresponding to size;
77                                  // on input it is the number of frames desired,
78                                  // on output is the number of frames actually filled
79
80        size_t      size;         // input/output in byte units
81        union {
82            void*       raw;
83            short*      i16;    // signed 16-bit
84            int8_t*     i8;     // unsigned 8-bit, offset by 0x80
85        };
86    };
87
88
89    /* As a convenience, if a callback is supplied, a handler thread
90     * is automatically created with the appropriate priority. This thread
91     * invokes the callback when a new buffer becomes available or various conditions occur.
92     * Parameters:
93     *
94     * event:   type of event notified (see enum AudioTrack::event_type).
95     * user:    Pointer to context for use by the callback receiver.
96     * info:    Pointer to optional parameter according to event type:
97     *          - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write
98     *            more bytes than indicated by 'size' field and update 'size' if fewer bytes are
99     *            written.
100     *          - EVENT_UNDERRUN: unused.
101     *          - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining.
102     *          - EVENT_MARKER: pointer to an uint32_t containing the marker position in frames.
103     *          - EVENT_NEW_POS: pointer to an uint32_t containing the new position in frames.
104     *          - EVENT_BUFFER_END: unused.
105     */
106
107    typedef void (*callback_t)(int event, void* user, void *info);
108
109    /* Returns the minimum frame count required for the successful creation of
110     * an AudioTrack object.
111     * Returned status (from utils/Errors.h) can be:
112     *  - NO_ERROR: successful operation
113     *  - NO_INIT: audio server or audio hardware not initialized
114     */
115
116     static status_t getMinFrameCount(int* frameCount,
117                                      audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT,
118                                      uint32_t sampleRate = 0);
119
120    /* Constructs an uninitialized AudioTrack. No connection with
121     * AudioFlinger takes place.
122     */
123                        AudioTrack();
124
125    /* Creates an audio track and registers it with AudioFlinger.
126     * Once created, the track needs to be started before it can be used.
127     * Unspecified values are set to the audio hardware's current
128     * values.
129     *
130     * Parameters:
131     *
132     * streamType:         Select the type of audio stream this track is attached to
133     *                     (e.g. AUDIO_STREAM_MUSIC).
134     * sampleRate:         Track sampling rate in Hz.
135     * format:             Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed
136     *                     16 bits per sample).
137     * channelMask:        Channel mask: see audio_channels_t.
138     * frameCount:         Minimum size of track PCM buffer in frames. This defines the
139     *                     latency of the track. The actual size selected by the AudioTrack could be
140     *                     larger if the requested size is not compatible with current audio HAL
141     *                     latency.
142     * flags:              See comments on audio_output_flags_t in <system/audio.h>.
143     * cbf:                Callback function. If not null, this function is called periodically
144     *                     to request new PCM data.
145     * user:               Context for use by the callback receiver.
146     * notificationFrames: The callback function is called each time notificationFrames PCM
147     *                     frames have been consumed from track input buffer.
148     * sessionId:          Specific session ID, or zero to use default.
149     * threadCanCallJava:  Whether callbacks are made from an attached thread and thus can call JNI.
150     *                     If not present in parameter list, then fixed at false.
151     */
152
153                        AudioTrack( audio_stream_type_t streamType,
154                                    uint32_t sampleRate  = 0,
155                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
156                                    int channelMask      = 0,
157                                    int frameCount       = 0,
158                                    audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
159                                    callback_t cbf       = NULL,
160                                    void* user           = NULL,
161                                    int notificationFrames = 0,
162                                    int sessionId        = 0);
163
164                        // DEPRECATED
165                        explicit AudioTrack( int streamType,
166                                    uint32_t sampleRate  = 0,
167                                    int format = AUDIO_FORMAT_DEFAULT,
168                                    int channelMask      = 0,
169                                    int frameCount       = 0,
170                                    uint32_t flags       = (uint32_t) AUDIO_OUTPUT_FLAG_NONE,
171                                    callback_t cbf       = 0,
172                                    void* user           = 0,
173                                    int notificationFrames = 0,
174                                    int sessionId        = 0);
175
176    /* Creates an audio track and registers it with AudioFlinger. With this constructor,
177     * the PCM data to be rendered by AudioTrack is passed in a shared memory buffer
178     * identified by the argument sharedBuffer. This prototype is for static buffer playback.
179     * PCM data must be present in memory before the AudioTrack is started.
180     * The write() and flush() methods are not supported in this case.
181     * It is recommended to pass a callback function to be notified of playback end by an
182     * EVENT_UNDERRUN event.
183     */
184
185                        AudioTrack( audio_stream_type_t streamType,
186                                    uint32_t sampleRate = 0,
187                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
188                                    int channelMask     = 0,
189                                    const sp<IMemory>& sharedBuffer = 0,
190                                    audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
191                                    callback_t cbf      = NULL,
192                                    void* user          = NULL,
193                                    int notificationFrames = 0,
194                                    int sessionId       = 0);
195
196    /* Terminates the AudioTrack and unregisters it from AudioFlinger.
197     * Also destroys all resources associated with the AudioTrack.
198     */
199                        ~AudioTrack();
200
201
202    /* Initialize an uninitialized AudioTrack.
203     * Returned status (from utils/Errors.h) can be:
204     *  - NO_ERROR: successful initialization
205     *  - INVALID_OPERATION: AudioTrack is already initialized
206     *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
207     *  - NO_INIT: audio server or audio hardware not initialized
208     * */
209            status_t    set(audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT,
210                            uint32_t sampleRate = 0,
211                            audio_format_t format = AUDIO_FORMAT_DEFAULT,
212                            int channelMask     = 0,
213                            int frameCount      = 0,
214                            audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
215                            callback_t cbf      = NULL,
216                            void* user          = NULL,
217                            int notificationFrames = 0,
218                            const sp<IMemory>& sharedBuffer = 0,
219                            bool threadCanCallJava = false,
220                            int sessionId       = 0);
221
222
223    /* Result of constructing the AudioTrack. This must be checked
224     * before using any AudioTrack API (except for set()), because using
225     * an uninitialized AudioTrack produces undefined results.
226     * See set() method above for possible return codes.
227     */
228            status_t    initCheck() const;
229
230    /* Returns this track's estimated latency in milliseconds.
231     * This includes the latency due to AudioTrack buffer size, AudioMixer (if any)
232     * and audio hardware driver.
233     */
234            uint32_t     latency() const;
235
236    /* getters, see constructors and set() */
237
238            audio_stream_type_t streamType() const;
239            audio_format_t format() const;
240            int         channelCount() const;
241            uint32_t    frameCount() const;
242
243    /* Return channelCount * (bit depth per channel / 8).
244     * channelCount is determined from channelMask, and bit depth comes from format.
245     */
246            size_t      frameSize() const;
247
248            sp<IMemory>& sharedBuffer();
249
250
251    /* After it's created the track is not active. Call start() to
252     * make it active. If set, the callback will start being called.
253     */
254            void        start();
255
256    /* Stop a track. If set, the callback will cease being called and
257     * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
258     * and will fill up buffers until the pool is exhausted.
259     */
260            void        stop();
261            bool        stopped() const;
262
263    /* Flush a stopped track. All pending buffers are discarded.
264     * This function has no effect if the track is not stopped.
265     */
266            void        flush();
267
268    /* Pause a track. If set, the callback will cease being called and
269     * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
270     * and will fill up buffers until the pool is exhausted.
271     */
272            void        pause();
273
274    /* Mute or unmute this track.
275     * While muted, the callback, if set, is still called.
276     */
277            void        mute(bool);
278            bool        muted() const;
279
280    /* Set volume for this track, mostly used for games' sound effects
281     * left and right volumes. Levels must be >= 0.0 and <= 1.0.
282     */
283            status_t    setVolume(float left, float right);
284            void        getVolume(float* left, float* right) const;
285
286    /* Set the send level for this track. An auxiliary effect should be attached
287     * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0.
288     */
289            status_t    setAuxEffectSendLevel(float level);
290            void        getAuxEffectSendLevel(float* level) const;
291
292    /* Set sample rate for this track, mostly used for games' sound effects
293     */
294            status_t    setSampleRate(int sampleRate);
295            uint32_t    getSampleRate() const;
296
297    /* Enables looping and sets the start and end points of looping.
298     *
299     * Parameters:
300     *
301     * loopStart:   loop start expressed as the number of PCM frames played since AudioTrack start.
302     * loopEnd:     loop end expressed as the number of PCM frames played since AudioTrack start.
303     * loopCount:   number of loops to execute. Calling setLoop() with loopCount == 0 cancels any
304     *              pending or active loop. loopCount = -1 means infinite looping.
305     *
306     * For proper operation the following condition must be respected:
307     *          (loopEnd-loopStart) <= framecount()
308     */
309            status_t    setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount);
310
311    /* Sets marker position. When playback reaches the number of frames specified, a callback with
312     * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker
313     * notification callback.
314     * If the AudioTrack has been opened with no callback function associated, the operation will fail.
315     *
316     * Parameters:
317     *
318     * marker:   marker position expressed in frames.
319     *
320     * Returned status (from utils/Errors.h) can be:
321     *  - NO_ERROR: successful operation
322     *  - INVALID_OPERATION: the AudioTrack has no callback installed.
323     */
324            status_t    setMarkerPosition(uint32_t marker);
325            status_t    getMarkerPosition(uint32_t *marker) const;
326
327
328    /* Sets position update period. Every time the number of frames specified has been played,
329     * a callback with event type EVENT_NEW_POS is called.
330     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
331     * callback.
332     * If the AudioTrack has been opened with no callback function associated, the operation will fail.
333     *
334     * Parameters:
335     *
336     * updatePeriod:  position update notification period expressed in frames.
337     *
338     * Returned status (from utils/Errors.h) can be:
339     *  - NO_ERROR: successful operation
340     *  - INVALID_OPERATION: the AudioTrack has no callback installed.
341     */
342            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
343            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
344
345    /* Sets playback head position within AudioTrack buffer. The new position is specified
346     * in number of frames.
347     * This method must be called with the AudioTrack in paused or stopped state.
348     * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames.
349     * Therefore using this method makes sense only when playing a "static" audio buffer
350     * as opposed to streaming.
351     * The getPosition() method on the other hand returns the total number of frames played since
352     * playback start.
353     *
354     * Parameters:
355     *
356     * position:  New playback head position within AudioTrack buffer.
357     *
358     * Returned status (from utils/Errors.h) can be:
359     *  - NO_ERROR: successful operation
360     *  - INVALID_OPERATION: the AudioTrack is not stopped.
361     *  - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer
362     */
363            status_t    setPosition(uint32_t position);
364            status_t    getPosition(uint32_t *position);
365
366    /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids
367     * rewriting the buffer before restarting playback after a stop.
368     * This method must be called with the AudioTrack in paused or stopped state.
369     *
370     * Returned status (from utils/Errors.h) can be:
371     *  - NO_ERROR: successful operation
372     *  - INVALID_OPERATION: the AudioTrack is not stopped.
373     */
374            status_t    reload();
375
376    /* Returns a handle on the audio output used by this AudioTrack.
377     *
378     * Parameters:
379     *  none.
380     *
381     * Returned value:
382     *  handle on audio hardware output
383     */
384            audio_io_handle_t    getOutput();
385
386    /* Returns the unique session ID associated with this track.
387     *
388     * Parameters:
389     *  none.
390     *
391     * Returned value:
392     *  AudioTrack session ID.
393     */
394            int    getSessionId() const;
395
396    /* Attach track auxiliary output to specified effect. Use effectId = 0
397     * to detach track from effect.
398     *
399     * Parameters:
400     *
401     * effectId:  effectId obtained from AudioEffect::id().
402     *
403     * Returned status (from utils/Errors.h) can be:
404     *  - NO_ERROR: successful operation
405     *  - INVALID_OPERATION: the effect is not an auxiliary effect.
406     *  - BAD_VALUE: The specified effect ID is invalid
407     */
408            status_t    attachAuxEffect(int effectId);
409
410    /* Obtains a buffer of "frameCount" frames. The buffer must be
411     * filled entirely, and then released with releaseBuffer().
412     * If the track is stopped, obtainBuffer() returns
413     * STOPPED instead of NO_ERROR as long as there are buffers available,
414     * at which point NO_MORE_BUFFERS is returned.
415     * Buffers will be returned until the pool (buffercount())
416     * is exhausted, at which point obtainBuffer() will either block
417     * or return WOULD_BLOCK depending on the value of the "blocking"
418     * parameter.
419     *
420     * Interpretation of waitCount:
421     *  +n  limits wait time to n * WAIT_PERIOD_MS,
422     *  -1  causes an (almost) infinite wait time,
423     *   0  non-blocking.
424     */
425
426        enum {
427            NO_MORE_BUFFERS = 0x80000001,   // same name in AudioFlinger.h, ok to be different value
428            STOPPED = 1
429        };
430
431            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
432
433    /* Release a filled buffer of "frameCount" frames for AudioFlinger to process. */
434            void        releaseBuffer(Buffer* audioBuffer);
435
436    /* As a convenience we provide a write() interface to the audio buffer.
437     * This is implemented on top of obtainBuffer/releaseBuffer. For best
438     * performance use callbacks. Returns actual number of bytes written >= 0,
439     * or one of the following negative status codes:
440     *      INVALID_OPERATION   AudioTrack is configured for shared buffer mode
441     *      BAD_VALUE           size is invalid
442     *      STOPPED             AudioTrack was stopped during the write
443     *      NO_MORE_BUFFERS     when obtainBuffer() returns same
444     *      or any other error code returned by IAudioTrack::start() or restoreTrack_l().
445     */
446            ssize_t     write(const void* buffer, size_t size);
447
448    /*
449     * Dumps the state of an audio track.
450     */
451            status_t dump(int fd, const Vector<String16>& args) const;
452
453protected:
454    /* copying audio tracks is not allowed */
455                        AudioTrack(const AudioTrack& other);
456            AudioTrack& operator = (const AudioTrack& other);
457
458    /* a small internal class to handle the callback */
459    class AudioTrackThread : public Thread
460    {
461    public:
462        AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false);
463    private:
464        friend class AudioTrack;
465        virtual bool        threadLoop();
466        virtual status_t    readyToRun();
467        virtual void        onFirstRef();
468        AudioTrack& mReceiver;
469    };
470
471            // body of AudioTrackThread::threadLoop()
472            bool processAudioBuffer(const sp<AudioTrackThread>& thread);
473
474            status_t createTrack_l(audio_stream_type_t streamType,
475                                 uint32_t sampleRate,
476                                 audio_format_t format,
477                                 uint32_t channelMask,
478                                 int frameCount,
479                                 audio_output_flags_t flags,
480                                 const sp<IMemory>& sharedBuffer,
481                                 audio_io_handle_t output);
482            void flush_l();
483            status_t setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount);
484            audio_io_handle_t getOutput_l();
485            status_t restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart);
486            bool stopped_l() const { return !mActive; }
487
488    sp<IAudioTrack>         mAudioTrack;
489    sp<IMemory>             mCblkMemory;
490    sp<AudioTrackThread>    mAudioTrackThread;
491
492    float                   mVolume[2];
493    float                   mSendLevel;
494    uint32_t                mFrameCount;
495
496    audio_track_cblk_t*     mCblk;
497    audio_format_t          mFormat;
498    audio_stream_type_t     mStreamType;
499    uint8_t                 mChannelCount;
500    uint8_t                 mMuted;
501    uint8_t                 mReserved;
502    uint32_t                mChannelMask;
503    status_t                mStatus;
504    uint32_t                mLatency;
505
506    bool                    mActive;                // protected by mLock
507
508    callback_t              mCbf;                   // callback handler for events, or NULL
509    void*                   mUserData;
510    uint32_t                mNotificationFramesReq; // requested number of frames between each notification callback
511    uint32_t                mNotificationFramesAct; // actual number of frames between each notification callback
512    sp<IMemory>             mSharedBuffer;
513    int                     mLoopCount;
514    uint32_t                mRemainingFrames;
515    uint32_t                mMarkerPosition;
516    bool                    mMarkerReached;
517    uint32_t                mNewPosition;
518    uint32_t                mUpdatePeriod;
519    bool                    mFlushed; // FIXME will be made obsolete by making flush() synchronous
520    audio_output_flags_t    mFlags;
521    int                     mSessionId;
522    int                     mAuxEffectId;
523    mutable Mutex           mLock;
524    status_t                mRestoreStatus;
525    bool                    mIsTimed;
526    int                     mPreviousPriority;          // before start()
527    int                     mPreviousSchedulingGroup;
528};
529
530class TimedAudioTrack : public AudioTrack
531{
532public:
533    TimedAudioTrack();
534
535    /* allocate a shared memory buffer that can be passed to queueTimedBuffer */
536    status_t allocateTimedBuffer(size_t size, sp<IMemory>* buffer);
537
538    /* queue a buffer obtained via allocateTimedBuffer for playback at the
539       given timestamp.  PTS units a microseconds on the media time timeline.
540       The media time transform (set with setMediaTimeTransform) set by the
541       audio producer will handle converting from media time to local time
542       (perhaps going through the common time timeline in the case of
543       synchronized multiroom audio case) */
544    status_t queueTimedBuffer(const sp<IMemory>& buffer, int64_t pts);
545
546    /* define a transform between media time and either common time or
547       local time */
548    enum TargetTimeline {LOCAL_TIME, COMMON_TIME};
549    status_t setMediaTimeTransform(const LinearTransform& xform,
550                                   TargetTimeline target);
551};
552
553}; // namespace android
554
555#endif // ANDROID_AUDIOTRACK_H
556