AudioRecord.h revision 1703cdfee717b1b312bf8979816a9e2f16a82e5d
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    /* Returns the minimum frame count required for the successful creation of
104     * an AudioRecord object.
105     * Returned status (from utils/Errors.h) can be:
106     *  - NO_ERROR: successful operation
107     *  - NO_INIT: audio server or audio hardware not initialized
108     *  - BAD_VALUE: unsupported configuration
109     */
110
111     static status_t getMinFrameCount(int* frameCount,
112                                      uint32_t sampleRate,
113                                      int format,
114                                      int channelCount);
115
116    /* Constructs an uninitialized AudioRecord. No connection with
117     * AudioFlinger takes place.
118     */
119                        AudioRecord();
120
121    /* Creates an AudioRecord track and registers it with AudioFlinger.
122     * Once created, the track needs to be started before it can be used.
123     * Unspecified values are set to the audio hardware's current
124     * values.
125     *
126     * Parameters:
127     *
128     * inputSource:        Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT).
129     * sampleRate:         Track sampling rate in Hz.
130     * format:             Audio format (e.g AudioSystem::PCM_16_BIT for signed
131     *                     16 bits per sample).
132     * channels:           Channel mask: see AudioSystem::audio_channels.
133     * frameCount:         Total size of track PCM buffer in frames. This defines the
134     *                     latency of the track.
135     * flags:              A bitmask of acoustic values from enum record_flags.  It enables
136     *                     AGC, NS, and IIR.
137     * cbf:                Callback function. If not null, this function is called periodically
138     *                     to provide new PCM data.
139     * notificationFrames: The callback function is called each time notificationFrames PCM
140     *                     frames are ready in record track output buffer.
141     * user                Context for use by the callback receiver.
142     */
143
144     enum record_flags {
145         RECORD_AGC_ENABLE = AudioSystem::AGC_ENABLE,
146         RECORD_NS_ENABLE  = AudioSystem::NS_ENABLE,
147         RECORD_IIR_ENABLE = AudioSystem::TX_IIR_ENABLE
148     };
149
150                        AudioRecord(int inputSource,
151                                    uint32_t sampleRate = 0,
152                                    int format          = 0,
153                                    uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
154                                    int frameCount      = 0,
155                                    uint32_t flags      = 0,
156                                    callback_t cbf = 0,
157                                    void* user = 0,
158                                    int notificationFrames = 0,
159                                    int sessionId = 0);
160
161
162    /* Terminates the AudioRecord and unregisters it from AudioFlinger.
163     * Also destroys all resources assotiated with the AudioRecord.
164     */
165                        ~AudioRecord();
166
167
168    /* Initialize an uninitialized AudioRecord.
169     * Returned status (from utils/Errors.h) can be:
170     *  - NO_ERROR: successful intialization
171     *  - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use
172     *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
173     *  - NO_INIT: audio server or audio hardware not initialized
174     *  - PERMISSION_DENIED: recording is not allowed for the requesting process
175     * */
176            status_t    set(int inputSource     = 0,
177                            uint32_t sampleRate = 0,
178                            int format          = 0,
179                            uint32_t channels = AudioSystem::CHANNEL_IN_MONO,
180                            int frameCount      = 0,
181                            uint32_t flags      = 0,
182                            callback_t cbf = 0,
183                            void* user = 0,
184                            int notificationFrames = 0,
185                            bool threadCanCallJava = false,
186                            int sessionId = 0);
187
188
189    /* Result of constructing the AudioRecord. This must be checked
190     * before using any AudioRecord API (except for set()), using
191     * an uninitialized AudioRecord produces undefined results.
192     * See set() method above for possible return codes.
193     */
194            status_t    initCheck() const;
195
196    /* Returns this track's latency in milliseconds.
197     * This includes the latency due to AudioRecord buffer size
198     * and audio hardware driver.
199     */
200            uint32_t     latency() const;
201
202   /* getters, see constructor */
203
204            int         format() const;
205            int         channelCount() const;
206            int         channels() const;
207            uint32_t    frameCount() const;
208            int         frameSize() const;
209            int         inputSource() const;
210
211
212    /* After it's created the track is not active. Call start() to
213     * make it active. If set, the callback will start being called.
214     */
215            status_t    start();
216
217    /* Stop a track. If set, the callback will cease being called and
218     * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
219     * and will fill up buffers until the pool is exhausted.
220     */
221            status_t    stop();
222            bool        stopped() const;
223
224    /* get sample rate for this record track
225     */
226            uint32_t    getSampleRate();
227
228    /* Sets marker position. When record reaches the number of frames specified,
229     * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
230     * with marker == 0 cancels marker notification callback.
231     * If the AudioRecord has been opened with no callback function associated,
232     * the operation will fail.
233     *
234     * Parameters:
235     *
236     * marker:   marker position expressed in frames.
237     *
238     * Returned status (from utils/Errors.h) can be:
239     *  - NO_ERROR: successful operation
240     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
241     */
242            status_t    setMarkerPosition(uint32_t marker);
243            status_t    getMarkerPosition(uint32_t *marker);
244
245
246    /* Sets position update period. Every time the number of frames specified has been recorded,
247     * a callback with event type EVENT_NEW_POS is called.
248     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
249     * callback.
250     * If the AudioRecord has been opened with no callback function associated,
251     * the operation will fail.
252     *
253     * Parameters:
254     *
255     * updatePeriod:  position update notification period expressed in frames.
256     *
257     * Returned status (from utils/Errors.h) can be:
258     *  - NO_ERROR: successful operation
259     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
260     */
261            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
262            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod);
263
264
265    /* Gets record head position. The position is the  total number of frames
266     * recorded since record start.
267     *
268     * Parameters:
269     *
270     *  position:  Address where to return record head position within AudioRecord buffer.
271     *
272     * Returned status (from utils/Errors.h) can be:
273     *  - NO_ERROR: successful operation
274     *  - BAD_VALUE:  position is NULL
275     */
276            status_t    getPosition(uint32_t *position);
277
278    /* returns a handle on the audio input used by this AudioRecord.
279     *
280     * Parameters:
281     *  none.
282     *
283     * Returned value:
284     *  handle on audio hardware input
285     */
286            audio_io_handle_t    getInput();
287
288    /* returns the audio session ID associated to this AudioRecord.
289     *
290     * Parameters:
291     *  none.
292     *
293     * Returned value:
294     *  AudioRecord session ID.
295     */
296            int    getSessionId();
297
298    /* obtains a buffer of "frameCount" frames. The buffer must be
299     * filled entirely. If the track is stopped, obtainBuffer() returns
300     * STOPPED instead of NO_ERROR as long as there are buffers availlable,
301     * at which point NO_MORE_BUFFERS is returned.
302     * Buffers will be returned until the pool (buffercount())
303     * is exhausted, at which point obtainBuffer() will either block
304     * or return WOULD_BLOCK depending on the value of the "blocking"
305     * parameter.
306     */
307
308        enum {
309            NO_MORE_BUFFERS = 0x80000001,
310            STOPPED = 1
311        };
312
313            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
314            void        releaseBuffer(Buffer* audioBuffer);
315
316
317    /* As a convenience we provide a read() interface to the audio buffer.
318     * This is implemented on top of lockBuffer/unlockBuffer.
319     */
320            ssize_t     read(void* buffer, size_t size);
321
322    /* Return the amount of input frames lost in the audio driver since the last call of this function.
323     * Audio driver is expected to reset the value to 0 and restart counting upon returning the current value by this function call.
324     * Such loss typically occurs when the user space process is blocked longer than the capacity of audio driver buffers.
325     * Unit: the number of input audio frames
326     */
327            unsigned int  getInputFramesLost();
328
329private:
330    /* copying audio tracks is not allowed */
331                        AudioRecord(const AudioRecord& other);
332            AudioRecord& operator = (const AudioRecord& other);
333
334    /* a small internal class to handle the callback */
335    class ClientRecordThread : public Thread
336    {
337    public:
338        ClientRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
339    private:
340        friend class AudioRecord;
341        virtual bool        threadLoop();
342        virtual status_t    readyToRun() { return NO_ERROR; }
343        virtual void        onFirstRef() {}
344        AudioRecord& mReceiver;
345        Mutex       mLock;
346    };
347
348            bool processAudioBuffer(const sp<ClientRecordThread>& thread);
349            status_t openRecord_l(uint32_t sampleRate,
350                                int format,
351                                int channelCount,
352                                int frameCount,
353                                uint32_t flags,
354                                audio_io_handle_t input);
355            audio_io_handle_t getInput_l();
356            status_t restoreRecord_l(audio_track_cblk_t*& cblk);
357
358    sp<IAudioRecord>        mAudioRecord;
359    sp<IMemory>             mCblkMemory;
360    sp<ClientRecordThread>  mClientRecordThread;
361    Mutex                   mLock;
362
363    uint32_t                mFrameCount;
364
365    audio_track_cblk_t*     mCblk;
366    uint8_t                 mFormat;
367    uint8_t                 mChannelCount;
368    uint8_t                 mInputSource;
369    uint8_t                 mReserved;
370    status_t                mStatus;
371    uint32_t                mLatency;
372
373    volatile int32_t        mActive;
374
375    callback_t              mCbf;
376    void*                   mUserData;
377    uint32_t                mNotificationFrames;
378    uint32_t                mRemainingFrames;
379    uint32_t                mMarkerPosition;
380    bool                    mMarkerReached;
381    uint32_t                mNewPosition;
382    uint32_t                mUpdatePeriod;
383    uint32_t                mFlags;
384    uint32_t                mChannels;
385    audio_io_handle_t       mInput;
386    int                     mSessionId;
387};
388
389}; // namespace android
390
391#endif /*AUDIORECORD_H_*/
392