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