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