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