AudioRecord.h revision be916aa1267e2e6b1c148f51d11bcbbc79cb864c
1/*
2 * Copyright (C) 2008 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 AUDIORECORD_H_
18#define AUDIORECORD_H_
19
20#include <stdint.h>
21#include <sys/types.h>
22
23#include <media/IAudioFlinger.h>
24#include <media/IAudioRecord.h>
25#include <media/AudioTrack.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
33
34namespace android {
35
36// ----------------------------------------------------------------------------
37
38class AudioRecord
39{
40public:
41
42    static const int DEFAULT_SAMPLE_RATE = 8000;
43
44    /* Events used by AudioRecord callback function (callback_t).
45     *
46     * to keep in sync with frameworks/base/media/java/android/media/AudioRecord.java
47     */
48    enum event_type {
49        EVENT_MORE_DATA = 0,        // Request to reqd more data from PCM buffer.
50        EVENT_OVERRUN = 1,          // PCM buffer overrun occured.
51        EVENT_MARKER = 2,           // Record head is at the specified marker position
52                                    // (See setMarkerPosition()).
53        EVENT_NEW_POS = 3,          // Record head is at a new position
54                                    // (See setPositionUpdatePeriod()).
55    };
56
57    /* Create Buffer on the stack and pass it to obtainBuffer()
58     * and releaseBuffer().
59     */
60
61    class Buffer
62    {
63    public:
64        enum {
65            MUTE    = 0x00000001
66        };
67        uint32_t    flags;
68        int         channelCount;
69        int         format;
70        size_t      frameCount;
71        size_t      size;
72        union {
73            void*       raw;
74            short*      i16;
75            int8_t*     i8;
76        };
77    };
78
79    /* These are static methods to control the system-wide AudioFlinger
80     * only privileged processes can have access to them
81     */
82
83//    static status_t setMasterMute(bool mute);
84
85    /* As a convenience, if a callback is supplied, a handler thread
86     * is automatically created with the appropriate priority. This thread
87     * invokes the callback when a new buffer becomes ready or an overrun condition occurs.
88     * Parameters:
89     *
90     * event:   type of event notified (see enum AudioRecord::event_type).
91     * user:    Pointer to context for use by the callback receiver.
92     * info:    Pointer to optional parameter according to event type:
93     *          - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read
94     *          more bytes than indicated by 'size' field and update 'size' if less bytes are
95     *          read.
96     *          - EVENT_OVERRUN: unused.
97     *          - EVENT_MARKER: pointer to an uin32_t containing the marker position in frames.
98     *          - EVENT_NEW_POS: pointer to an uin32_t containing the new position in frames.
99     */
100
101    typedef void (*callback_t)(int event, void* user, void *info);
102
103    /* Constructs an uninitialized AudioRecord. No connection with
104     * AudioFlinger takes place.
105     */
106                        AudioRecord();
107
108    /* Creates an AudioRecord track and registers it with AudioFlinger.
109     * Once created, the track needs to be started before it can be used.
110     * Unspecified values are set to the audio hardware's current
111     * values.
112     *
113     * Parameters:
114     *
115     * inputSource:        Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT).
116     * sampleRate:         Track sampling rate in Hz.
117     * format:             Audio format (e.g AudioSystem::PCM_16_BIT for signed
118     *                     16 bits per sample).
119     * channels:           Channel mask: see AudioSystem::audio_channels.
120     * frameCount:         Total size of track PCM buffer in frames. This defines the
121     *                     latency of the track.
122     * flags:              A bitmask of acoustic values from enum record_flags.  It enables
123     *                     AGC, NS, and IIR.
124     * cbf:                Callback function. If not null, this function is called periodically
125     *                     to provide new PCM data.
126     * notificationFrames: The callback function is called each time notificationFrames PCM
127     *                     frames are ready in record track output buffer.
128     * user                Context for use by the callback receiver.
129     */
130
131     enum record_flags {
132         RECORD_AGC_ENABLE = AudioSystem::AGC_ENABLE,
133         RECORD_NS_ENABLE  = AudioSystem::NS_ENABLE,
134         RECORD_IIR_ENABLE = AudioSystem::TX_IIR_ENABLE
135     };
136
137                        AudioRecord(int inputSource,
138                                    uint32_t sampleRate = 0,
139                                    int format          = 0,
140                                    uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
141                                    int frameCount      = 0,
142                                    uint32_t flags      = 0,
143                                    callback_t cbf = 0,
144                                    void* user = 0,
145                                    int notificationFrames = 0,
146                                    int sessionId = 0);
147
148
149    /* Terminates the AudioRecord and unregisters it from AudioFlinger.
150     * Also destroys all resources assotiated with the AudioRecord.
151     */
152                        ~AudioRecord();
153
154
155    /* Initialize an uninitialized AudioRecord.
156     * Returned status (from utils/Errors.h) can be:
157     *  - NO_ERROR: successful intialization
158     *  - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use
159     *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
160     *  - NO_INIT: audio server or audio hardware not initialized
161     *  - PERMISSION_DENIED: recording is not allowed for the requesting process
162     * */
163            status_t    set(int inputSource     = 0,
164                            uint32_t sampleRate = 0,
165                            int format          = 0,
166                            uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
167                            int frameCount      = 0,
168                            uint32_t flags      = 0,
169                            callback_t cbf = 0,
170                            void* user = 0,
171                            int notificationFrames = 0,
172                            bool threadCanCallJava = false,
173                            int sessionId = 0);
174
175
176    /* Result of constructing the AudioRecord. This must be checked
177     * before using any AudioRecord API (except for set()), using
178     * an uninitialized AudioRecord produces undefined results.
179     * See set() method above for possible return codes.
180     */
181            status_t    initCheck() const;
182
183    /* Returns this track's latency in milliseconds.
184     * This includes the latency due to AudioRecord buffer size
185     * and audio hardware driver.
186     */
187            uint32_t     latency() const;
188
189   /* getters, see constructor */
190
191            int         format() const;
192            int         channelCount() const;
193            int         channels() const;
194            uint32_t    frameCount() const;
195            int         frameSize() const;
196            int         inputSource() const;
197
198
199    /* After it's created the track is not active. Call start() to
200     * make it active. If set, the callback will start being called.
201     */
202            status_t    start();
203
204    /* Stop a track. If set, the callback will cease being called and
205     * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
206     * and will fill up buffers until the pool is exhausted.
207     */
208            status_t    stop();
209            bool        stopped() const;
210
211    /* get sample rate for this record track
212     */
213            uint32_t    getSampleRate();
214
215    /* Sets marker position. When record reaches the number of frames specified,
216     * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
217     * with marker == 0 cancels marker notification callback.
218     * If the AudioRecord has been opened with no callback function associated,
219     * the operation will fail.
220     *
221     * Parameters:
222     *
223     * marker:   marker position expressed in frames.
224     *
225     * Returned status (from utils/Errors.h) can be:
226     *  - NO_ERROR: successful operation
227     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
228     */
229            status_t    setMarkerPosition(uint32_t marker);
230            status_t    getMarkerPosition(uint32_t *marker);
231
232
233    /* Sets position update period. Every time the number of frames specified has been recorded,
234     * a callback with event type EVENT_NEW_POS is called.
235     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
236     * callback.
237     * If the AudioRecord has been opened with no callback function associated,
238     * the operation will fail.
239     *
240     * Parameters:
241     *
242     * updatePeriod:  position update notification period expressed in frames.
243     *
244     * Returned status (from utils/Errors.h) can be:
245     *  - NO_ERROR: successful operation
246     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
247     */
248            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
249            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod);
250
251
252    /* Gets record head position. The position is the  total number of frames
253     * recorded since record start.
254     *
255     * Parameters:
256     *
257     *  position:  Address where to return record head position within AudioRecord buffer.
258     *
259     * Returned status (from utils/Errors.h) can be:
260     *  - NO_ERROR: successful operation
261     *  - BAD_VALUE:  position is NULL
262     */
263            status_t    getPosition(uint32_t *position);
264
265    /* returns a handle on the audio input used by this AudioRecord.
266     *
267     * Parameters:
268     *  none.
269     *
270     * Returned value:
271     *  handle on audio hardware input
272     */
273            audio_io_handle_t    getInput();
274
275    /* returns the audio session ID associated to this AudioRecord.
276     *
277     * Parameters:
278     *  none.
279     *
280     * Returned value:
281     *  AudioRecord session ID.
282     */
283            int    getSessionId();
284
285    /* obtains a buffer of "frameCount" frames. The buffer must be
286     * filled entirely. If the track is stopped, obtainBuffer() returns
287     * STOPPED instead of NO_ERROR as long as there are buffers availlable,
288     * at which point NO_MORE_BUFFERS is returned.
289     * Buffers will be returned until the pool (buffercount())
290     * is exhausted, at which point obtainBuffer() will either block
291     * or return WOULD_BLOCK depending on the value of the "blocking"
292     * parameter.
293     */
294
295        enum {
296            NO_MORE_BUFFERS = 0x80000001,
297            STOPPED = 1
298        };
299
300            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
301            void        releaseBuffer(Buffer* audioBuffer);
302
303
304    /* As a convenience we provide a read() interface to the audio buffer.
305     * This is implemented on top of lockBuffer/unlockBuffer.
306     */
307            ssize_t     read(void* buffer, size_t size);
308
309    /* Return the amount of input frames lost in the audio driver since the last call of this function.
310     * Audio driver is expected to reset the value to 0 and restart counting upon returning the current value by this function call.
311     * Such loss typically occurs when the user space process is blocked longer than the capacity of audio driver buffers.
312     * Unit: the number of input audio frames
313     */
314            unsigned int  getInputFramesLost();
315
316private:
317    /* copying audio tracks is not allowed */
318                        AudioRecord(const AudioRecord& other);
319            AudioRecord& operator = (const AudioRecord& other);
320
321    /* a small internal class to handle the callback */
322    class ClientRecordThread : public Thread
323    {
324    public:
325        ClientRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
326    private:
327        friend class AudioRecord;
328        virtual bool        threadLoop();
329        virtual status_t    readyToRun() { return NO_ERROR; }
330        virtual void        onFirstRef() {}
331        AudioRecord& mReceiver;
332        Mutex       mLock;
333    };
334
335            bool processAudioBuffer(const sp<ClientRecordThread>& thread);
336            status_t openRecord(uint32_t sampleRate,
337                                int format,
338                                int channelCount,
339                                int frameCount,
340                                uint32_t flags,
341                                audio_io_handle_t input);
342
343    sp<IAudioRecord>        mAudioRecord;
344    sp<IMemory>             mCblkMemory;
345    sp<ClientRecordThread>  mClientRecordThread;
346    Mutex                   mRecordThreadLock;
347
348    uint32_t                mFrameCount;
349
350    audio_track_cblk_t*     mCblk;
351    uint8_t                 mFormat;
352    uint8_t                 mChannelCount;
353    uint8_t                 mInputSource;
354    uint8_t                 mReserved;
355    status_t                mStatus;
356    uint32_t                mLatency;
357
358    volatile int32_t        mActive;
359
360    callback_t              mCbf;
361    void*                   mUserData;
362    uint32_t                mNotificationFrames;
363    uint32_t                mRemainingFrames;
364    uint32_t                mMarkerPosition;
365    bool                    mMarkerReached;
366    uint32_t                mNewPosition;
367    uint32_t                mUpdatePeriod;
368    uint32_t                mFlags;
369    uint32_t                mChannels;
370    audio_io_handle_t       mInput;
371    int                     mSessionId;
372};
373
374}; // namespace android
375
376#endif /*AUDIORECORD_H_*/
377