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