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