AudioRecord.h revision c2f1f07084818942352c6bbfb36af9b6b330eb4e
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
147
148    /* Terminates the AudioRecord and unregisters it from AudioFlinger.
149     * Also destroys all resources assotiated with the AudioRecord.
150     */
151                        ~AudioRecord();
152
153
154    /* Initialize an uninitialized AudioRecord.
155     * Returned status (from utils/Errors.h) can be:
156     *  - NO_ERROR: successful intialization
157     *  - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use
158     *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
159     *  - NO_INIT: audio server or audio hardware not initialized
160     *  - PERMISSION_DENIED: recording is not allowed for the requesting process
161     * */
162            status_t    set(int inputSource     = 0,
163                            uint32_t sampleRate = 0,
164                            int format          = 0,
165                            uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
166                            int frameCount      = 0,
167                            uint32_t flags      = 0,
168                            callback_t cbf = 0,
169                            void* user = 0,
170                            int notificationFrames = 0,
171                            bool threadCanCallJava = false);
172
173
174    /* Result of constructing the AudioRecord. This must be checked
175     * before using any AudioRecord API (except for set()), using
176     * an uninitialized AudioRecord produces undefined results.
177     * See set() method above for possible return codes.
178     */
179            status_t    initCheck() const;
180
181    /* Returns this track's latency in milliseconds.
182     * This includes the latency due to AudioRecord buffer size
183     * and audio hardware driver.
184     */
185            uint32_t     latency() const;
186
187   /* getters, see constructor */
188
189            int         format() const;
190            int         channelCount() const;
191            int         channels() const;
192            uint32_t    frameCount() const;
193            int         frameSize() const;
194            int         inputSource() const;
195
196
197    /* After it's created the track is not active. Call start() to
198     * make it active. If set, the callback will start being called.
199     */
200            status_t    start();
201
202    /* Stop a track. If set, the callback will cease being called and
203     * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
204     * and will fill up buffers until the pool is exhausted.
205     */
206            status_t    stop();
207            bool        stopped() const;
208
209    /* get sample rate for this record track
210     */
211            uint32_t    getSampleRate();
212
213    /* Sets marker position. When record reaches the number of frames specified,
214     * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
215     * with marker == 0 cancels marker notification callback.
216     * If the AudioRecord has been opened with no callback function associated,
217     * the operation will fail.
218     *
219     * Parameters:
220     *
221     * marker:   marker position expressed in frames.
222     *
223     * Returned status (from utils/Errors.h) can be:
224     *  - NO_ERROR: successful operation
225     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
226     */
227            status_t    setMarkerPosition(uint32_t marker);
228            status_t    getMarkerPosition(uint32_t *marker);
229
230
231    /* Sets position update period. Every time the number of frames specified has been recorded,
232     * a callback with event type EVENT_NEW_POS is called.
233     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
234     * callback.
235     * If the AudioRecord has been opened with no callback function associated,
236     * the operation will fail.
237     *
238     * Parameters:
239     *
240     * updatePeriod:  position update notification period expressed in frames.
241     *
242     * Returned status (from utils/Errors.h) can be:
243     *  - NO_ERROR: successful operation
244     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
245     */
246            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
247            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod);
248
249
250    /* Gets record head position. The position is the  total number of frames
251     * recorded since record start.
252     *
253     * Parameters:
254     *
255     *  position:  Address where to return record head position within AudioRecord buffer.
256     *
257     * Returned status (from utils/Errors.h) can be:
258     *  - NO_ERROR: successful operation
259     *  - BAD_VALUE:  position is NULL
260     */
261            status_t    getPosition(uint32_t *position);
262
263    /* returns a handle on the audio input used by this AudioRecord.
264     *
265     * Parameters:
266     *  none.
267     *
268     * Returned value:
269     *  handle on audio hardware input
270     */
271            audio_io_handle_t    getInput() { return mInput; }
272
273    /* obtains a buffer of "frameCount" frames. The buffer must be
274     * filled entirely. If the track is stopped, obtainBuffer() returns
275     * STOPPED instead of NO_ERROR as long as there are buffers availlable,
276     * at which point NO_MORE_BUFFERS is returned.
277     * Buffers will be returned until the pool (buffercount())
278     * is exhausted, at which point obtainBuffer() will either block
279     * or return WOULD_BLOCK depending on the value of the "blocking"
280     * parameter.
281     */
282
283        enum {
284            NO_MORE_BUFFERS = 0x80000001,
285            STOPPED = 1
286        };
287
288            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
289            void        releaseBuffer(Buffer* audioBuffer);
290
291
292    /* As a convenience we provide a read() interface to the audio buffer.
293     * This is implemented on top of lockBuffer/unlockBuffer.
294     */
295            ssize_t     read(void* buffer, size_t size);
296
297private:
298    /* copying audio tracks is not allowed */
299                        AudioRecord(const AudioRecord& other);
300            AudioRecord& operator = (const AudioRecord& other);
301
302    /* a small internal class to handle the callback */
303    class ClientRecordThread : public Thread
304    {
305    public:
306        ClientRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
307    private:
308        friend class AudioRecord;
309        virtual bool        threadLoop();
310        virtual status_t    readyToRun() { return NO_ERROR; }
311        virtual void        onFirstRef() {}
312        AudioRecord& mReceiver;
313        Mutex       mLock;
314    };
315
316            bool processAudioBuffer(const sp<ClientRecordThread>& thread);
317
318    sp<IAudioRecord>        mAudioRecord;
319    sp<IMemory>             mCblkMemory;
320    sp<ClientRecordThread>  mClientRecordThread;
321    Mutex                   mRecordThreadLock;
322
323    uint32_t                mFrameCount;
324
325    audio_track_cblk_t*     mCblk;
326    uint8_t                 mFormat;
327    uint8_t                 mChannelCount;
328    uint8_t                 mInputSource;
329    uint8_t                 mReserved;
330    status_t                mStatus;
331    uint32_t                mLatency;
332
333    volatile int32_t        mActive;
334
335    callback_t              mCbf;
336    void*                   mUserData;
337    uint32_t                mNotificationFrames;
338    uint32_t                mRemainingFrames;
339    uint32_t                mMarkerPosition;
340    bool                    mMarkerReached;
341    uint32_t                mNewPosition;
342    uint32_t                mUpdatePeriod;
343    audio_io_handle_t       mInput;
344};
345
346}; // namespace android
347
348#endif /*AUDIORECORD_H_*/
349