AudioRecord.h revision e33054eb968cbf8ccaee1b0ff0301403902deed6
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 occurred.
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    /* Client should declare Buffer on the stack and pass address to obtainBuffer()
54     * and releaseBuffer().  See also callback_t for EVENT_MORE_DATA.
55     */
56
57    class Buffer
58    {
59    public:
60        size_t      frameCount;     // number of sample frames corresponding to size;
61                                    // on input it is the number of frames available,
62                                    // on output is the number of frames actually drained
63
64        size_t      size;           // total size in bytes == frameCount * frameSize
65        union {
66            void*       raw;
67            short*      i16;        // signed 16-bit
68            int8_t*     i8;         // unsigned 8-bit, offset by 0x80
69        };
70    };
71
72    /* As a convenience, if a callback is supplied, a handler thread
73     * is automatically created with the appropriate priority. This thread
74     * invokes the callback when a new buffer becomes ready or various conditions occur.
75     * Parameters:
76     *
77     * event:   type of event notified (see enum AudioRecord::event_type).
78     * user:    Pointer to context for use by the callback receiver.
79     * info:    Pointer to optional parameter according to event type:
80     *          - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read
81     *            more bytes than indicated by 'size' field and update 'size' if fewer bytes are
82     *            consumed.
83     *          - EVENT_OVERRUN: unused.
84     *          - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames.
85     *          - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames.
86     */
87
88    typedef void (*callback_t)(int event, void* user, void *info);
89
90    /* Returns the minimum frame count required for the successful creation of
91     * an AudioRecord object.
92     * Returned status (from utils/Errors.h) can be:
93     *  - NO_ERROR: successful operation
94     *  - NO_INIT: audio server or audio hardware not initialized
95     *  - BAD_VALUE: unsupported configuration
96     */
97
98     static status_t getMinFrameCount(size_t* frameCount,
99                                      uint32_t sampleRate,
100                                      audio_format_t format,
101                                      audio_channel_mask_t channelMask);
102
103    /* Constructs an uninitialized AudioRecord. No connection with
104     * AudioFlinger takes place.
105     */
106                        AudioRecord();
107
108    /* Creates an AudioRecord object and registers it with AudioFlinger.
109     * Once created, the track needs to be started before it can be used.
110     * Unspecified values are set to the audio hardware's current
111     * values.
112     *
113     * Parameters:
114     *
115     * inputSource:        Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT).
116     * sampleRate:         Track sampling rate in Hz.
117     * format:             Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed
118     *                     16 bits per sample).
119     * channelMask:        Channel mask.
120     * frameCount:         Minimum size of track PCM buffer in frames. This defines the
121     *                     application's contribution to the
122     *                     latency of the track.  The actual size selected by the AudioRecord could
123     *                     be larger if the requested size is not compatible with current audio HAL
124     *                     latency.  Zero means to use a default value.
125     * cbf:                Callback function. If not null, this function is called periodically
126     *                     to consume new PCM data.
127     * user:               Context for use by the callback receiver.
128     * notificationFrames: The callback function is called each time notificationFrames PCM
129     *                     frames are ready in record track output buffer.
130     * sessionId:          Not yet supported.
131     */
132
133                        AudioRecord(audio_source_t inputSource,
134                                    uint32_t sampleRate = 0,
135                                    audio_format_t format = AUDIO_FORMAT_DEFAULT,
136                                    audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO,
137                                    int frameCount      = 0,
138                                    callback_t cbf = NULL,
139                                    void* user = NULL,
140                                    int notificationFrames = 0,
141                                    int sessionId = 0);
142
143
144    /* Terminates the AudioRecord and unregisters it from AudioFlinger.
145     * Also destroys all resources associated with the AudioRecord.
146     */
147                        ~AudioRecord();
148
149
150    /* Initialize an uninitialized AudioRecord.
151     * Returned status (from utils/Errors.h) can be:
152     *  - NO_ERROR: successful intialization
153     *  - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use
154     *  - BAD_VALUE: invalid parameter (channels, format, sampleRate...)
155     *  - NO_INIT: audio server or audio hardware not initialized
156     *  - PERMISSION_DENIED: recording is not allowed for the requesting process
157     */
158            status_t    set(audio_source_t inputSource = AUDIO_SOURCE_DEFAULT,
159                            uint32_t sampleRate = 0,
160                            audio_format_t format = AUDIO_FORMAT_DEFAULT,
161                            audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO,
162                            int frameCount      = 0,
163                            callback_t cbf = NULL,
164                            void* user = NULL,
165                            int notificationFrames = 0,
166                            bool threadCanCallJava = false,
167                            int sessionId = 0);
168
169
170    /* Result of constructing the AudioRecord. This must be checked
171     * before using any AudioRecord API (except for set()), because using
172     * an uninitialized AudioRecord produces undefined results.
173     * See set() method above for possible return codes.
174     */
175            status_t    initCheck() const;
176
177    /* Returns this track's estimated latency in milliseconds.
178     * This includes the latency due to AudioRecord buffer size,
179     * and audio hardware driver.
180     */
181            uint32_t     latency() const;
182
183   /* getters, see constructor and set() */
184
185            audio_format_t format() const;
186            int         channelCount() const;
187            size_t      frameCount() const;
188            size_t      frameSize() const { return mFrameSize; }
189            audio_source_t inputSource() const;
190
191
192    /* After it's created the track is not active. Call start() to
193     * make it active. If set, the callback will start being called.
194     * If event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until
195     * the specified event occurs on the specified trigger session.
196     */
197            status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
198                              int triggerSession = 0);
199
200    /* Stop a track. If set, the callback will cease being called and
201     * obtainBuffer returns STOPPED. Note that obtainBuffer() still works
202     * and will drain buffers until the pool is exhausted.
203     */
204            void        stop();
205            bool        stopped() const;
206
207    /* Get sample rate for this record track in Hz.
208     */
209            uint32_t    getSampleRate() const;
210
211    /* Sets marker position. When record reaches the number of frames specified,
212     * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
213     * with marker == 0 cancels marker notification callback.
214     * If the AudioRecord has been opened with no callback function associated,
215     * the operation will fail.
216     *
217     * Parameters:
218     *
219     * marker:   marker position expressed in frames.
220     *
221     * Returned status (from utils/Errors.h) can be:
222     *  - NO_ERROR: successful operation
223     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
224     */
225            status_t    setMarkerPosition(uint32_t marker);
226            status_t    getMarkerPosition(uint32_t *marker) const;
227
228
229    /* Sets position update period. Every time the number of frames specified has been recorded,
230     * a callback with event type EVENT_NEW_POS is called.
231     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
232     * callback.
233     * If the AudioRecord has been opened with no callback function associated,
234     * the operation will fail.
235     *
236     * Parameters:
237     *
238     * updatePeriod:  position update notification period expressed in frames.
239     *
240     * Returned status (from utils/Errors.h) can be:
241     *  - NO_ERROR: successful operation
242     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
243     */
244            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
245            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
246
247
248    /* Gets record head position. The position is the total number of frames
249     * recorded since record start.
250     *
251     * Parameters:
252     *
253     *  position:  Address where to return record head position within AudioRecord buffer.
254     *
255     * Returned status (from utils/Errors.h) can be:
256     *  - NO_ERROR: successful operation
257     *  - BAD_VALUE:  position is NULL
258     */
259            status_t    getPosition(uint32_t *position) const;
260
261    /* Returns a handle on the audio input used by this AudioRecord.
262     *
263     * Parameters:
264     *  none.
265     *
266     * Returned value:
267     *  handle on audio hardware input
268     */
269            audio_io_handle_t    getInput() const;
270
271    /* Returns the audio session ID associated with this AudioRecord.
272     *
273     * Parameters:
274     *  none.
275     *
276     * Returned value:
277     *  AudioRecord session ID.
278     */
279            int    getSessionId() const;
280
281    /* Obtains a buffer of "frameCount" frames. The buffer must be
282     * drained entirely, and then released with releaseBuffer().
283     * If the track is stopped, obtainBuffer() returns
284     * STOPPED instead of NO_ERROR as long as there are buffers available,
285     * at which point NO_MORE_BUFFERS is returned.
286     * Buffers will be returned until the pool
287     * is exhausted, at which point obtainBuffer() will either block
288     * or return WOULD_BLOCK depending on the value of the "blocking"
289     * parameter.
290     *
291     * Interpretation of waitCount:
292     *  +n  limits wait time to n * WAIT_PERIOD_MS,
293     *  -1  causes an (almost) infinite wait time,
294     *   0  non-blocking.
295     */
296
297        enum {
298            NO_MORE_BUFFERS = 0x80000001,   // same name in AudioFlinger.h, ok to be different value
299            STOPPED = 1
300        };
301
302            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount);
303
304    /* Release an emptied buffer of "frameCount" frames for AudioFlinger to re-fill. */
305            void        releaseBuffer(Buffer* audioBuffer);
306
307
308    /* As a convenience we provide a read() interface to the audio buffer.
309     * This is implemented on top of obtainBuffer/releaseBuffer.
310     */
311            ssize_t     read(void* buffer, size_t size);
312
313    /* Return the number of input frames lost in the audio driver since the last call of this
314     * function.  Audio driver is expected to reset the value to 0 and restart counting upon
315     * returning the current value by this function call.  Such loss typically occurs when the
316     * user space process is blocked longer than the capacity of audio driver buffers.
317     * Units: the number of input audio frames.
318     */
319            unsigned int  getInputFramesLost() const;
320
321private:
322    /* copying audio record objects is not allowed */
323                        AudioRecord(const AudioRecord& other);
324            AudioRecord& operator = (const AudioRecord& other);
325
326    /* a small internal class to handle the callback */
327    class AudioRecordThread : public Thread
328    {
329    public:
330        AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
331
332        // Do not call Thread::requestExitAndWait() without first calling requestExit().
333        // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
334        virtual void        requestExit();
335
336                void        pause();    // suspend thread from execution at next loop boundary
337                void        resume();   // allow thread to execute, if not requested to exit
338
339    private:
340        friend class AudioRecord;
341        virtual bool        threadLoop();
342        AudioRecord& mReceiver;
343        virtual ~AudioRecordThread();
344        Mutex               mMyLock;    // Thread::mLock is private
345        Condition           mMyCond;    // Thread::mThreadExitedCondition is private
346        bool                mPaused;    // whether thread is currently paused
347    };
348
349            // body of AudioRecordThread::threadLoop()
350            bool processAudioBuffer(const sp<AudioRecordThread>& thread);
351
352            status_t openRecord_l(uint32_t sampleRate,
353                                audio_format_t format,
354                                audio_channel_mask_t channelMask,
355                                size_t frameCount,
356                                audio_io_handle_t input);
357            audio_io_handle_t getInput_l();
358            status_t restoreRecord_l(audio_track_cblk_t*& cblk);
359
360    sp<AudioRecordThread>   mAudioRecordThread;
361    mutable Mutex           mLock;
362
363    bool                    mActive;            // protected by mLock
364
365    // for client callback handler
366    callback_t              mCbf;               // callback handler for events, or NULL
367    void*                   mUserData;
368
369    // for notification APIs
370    uint32_t                mNotificationFrames;
371    uint32_t                mRemainingFrames;
372    uint32_t                mMarkerPosition;    // in frames
373    bool                    mMarkerReached;
374    uint32_t                mNewPosition;       // in frames
375    uint32_t                mUpdatePeriod;      // in ms
376
377    // constant after constructor or set()
378    size_t                  mFrameCount;
379    audio_format_t          mFormat;
380    uint8_t                 mChannelCount;
381    size_t                  mFrameSize;         // app-level frame size == AudioFlinger frame size
382    audio_source_t          mInputSource;
383    status_t                mStatus;
384    uint32_t                mLatency;
385    audio_channel_mask_t    mChannelMask;
386    audio_io_handle_t       mInput;                     // returned by AudioSystem::getInput()
387    int                     mSessionId;
388
389    // may be changed if IAudioRecord object is re-created
390    sp<IAudioRecord>        mAudioRecord;
391    sp<IMemory>             mCblkMemory;
392    audio_track_cblk_t*     mCblk;
393    void*                   mBuffers;           // starting address of buffers in shared memory
394
395    int                     mPreviousPriority;          // before start()
396    SchedPolicy             mPreviousSchedulingGroup;
397};
398
399}; // namespace android
400
401#endif /*AUDIORECORD_H_*/
402