AudioRecord.h revision bce50bfc3846ab008bafa75c5d3f29fd7b5395f7
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 ANDROID_AUDIORECORD_H
18#define ANDROID_AUDIORECORD_H
19
20#include <cutils/sched_policy.h>
21#include <media/AudioSystem.h>
22#include <media/IAudioRecord.h>
23#include <utils/threads.h>
24
25namespace android {
26
27// ----------------------------------------------------------------------------
28
29struct audio_track_cblk_t;
30class AudioRecordClientProxy;
31
32// ----------------------------------------------------------------------------
33
34class AudioRecord : public RefBase
35{
36public:
37
38    /* Events used by AudioRecord callback function (callback_t).
39     * Keep in sync with frameworks/base/media/java/android/media/AudioRecord.java NATIVE_EVENT_*.
40     */
41    enum event_type {
42        EVENT_MORE_DATA = 0,        // Request to read available data from buffer.
43                                    // If this event is delivered but the callback handler
44                                    // does not want to read the available data, the handler must
45                                    // explicitly
46                                    // ignore the event by setting frameCount to zero.
47        EVENT_OVERRUN = 1,          // Buffer overrun occurred.
48        EVENT_MARKER = 2,           // Record head is at the specified marker position
49                                    // (See setMarkerPosition()).
50        EVENT_NEW_POS = 3,          // Record head is at a new position
51                                    // (See setPositionUpdatePeriod()).
52        EVENT_NEW_IAUDIORECORD = 4, // IAudioRecord was re-created, either due to re-routing and
53                                    // voluntary invalidation by mediaserver, or mediaserver crash.
54    };
55
56    /* Client should declare Buffer on the stack and pass address to obtainBuffer()
57     * and releaseBuffer().  See also callback_t for EVENT_MORE_DATA.
58     */
59
60    class Buffer
61    {
62    public:
63        // FIXME use m prefix
64        size_t      frameCount;     // number of sample frames corresponding to size;
65                                    // on input it is the number of frames available,
66                                    // on output is the number of frames actually drained
67                                    // (currently ignored but will make the primary field in future)
68
69        size_t      size;           // input/output in bytes == frameCount * frameSize
70                                    // on output is the number of bytes actually drained
71                                    // FIXME this is redundant with respect to frameCount,
72                                    // and TRANSFER_OBTAIN mode is broken for 8-bit data
73                                    // since we don't define the frame format
74
75        union {
76            void*       raw;
77            short*      i16;        // signed 16-bit
78            int8_t*     i8;         // unsigned 8-bit, offset by 0x80
79        };
80    };
81
82    /* As a convenience, if a callback is supplied, a handler thread
83     * is automatically created with the appropriate priority. This thread
84     * invokes the callback when a new buffer becomes available or various conditions occur.
85     * Parameters:
86     *
87     * event:   type of event notified (see enum AudioRecord::event_type).
88     * user:    Pointer to context for use by the callback receiver.
89     * info:    Pointer to optional parameter according to event type:
90     *          - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read
91     *            more bytes than indicated by 'size' field and update 'size' if fewer bytes are
92     *            consumed.
93     *          - EVENT_OVERRUN: unused.
94     *          - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames.
95     *          - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames.
96     *          - EVENT_NEW_IAUDIORECORD: unused.
97     */
98
99    typedef void (*callback_t)(int event, void* user, void *info);
100
101    /* Returns the minimum frame count required for the successful creation of
102     * an AudioRecord object.
103     * Returned status (from utils/Errors.h) can be:
104     *  - NO_ERROR: successful operation
105     *  - NO_INIT: audio server or audio hardware not initialized
106     *  - BAD_VALUE: unsupported configuration
107     * frameCount is guaranteed to be non-zero if status is NO_ERROR,
108     * and is undefined otherwise.
109     */
110
111     static status_t getMinFrameCount(size_t* frameCount,
112                                      uint32_t sampleRate,
113                                      audio_format_t format,
114                                      audio_channel_mask_t channelMask);
115
116    /* How data is transferred from AudioRecord
117     */
118    enum transfer_type {
119        TRANSFER_DEFAULT,   // not specified explicitly; determine from the other parameters
120        TRANSFER_CALLBACK,  // callback EVENT_MORE_DATA
121        TRANSFER_OBTAIN,    // FIXME deprecated: call obtainBuffer() and releaseBuffer()
122        TRANSFER_SYNC,      // synchronous read()
123    };
124
125    /* Constructs an uninitialized AudioRecord. No connection with
126     * AudioFlinger takes place.  Use set() after this.
127     */
128                        AudioRecord();
129
130    /* Creates an AudioRecord object and registers it with AudioFlinger.
131     * Once created, the track needs to be started before it can be used.
132     * Unspecified values are set to appropriate default values.
133     *
134     * Parameters:
135     *
136     * inputSource:        Select the audio input to record from (e.g. AUDIO_SOURCE_DEFAULT).
137     * sampleRate:         Data sink sampling rate in Hz.
138     * format:             Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed
139     *                     16 bits per sample).
140     * channelMask:        Channel mask, such that audio_is_input_channel(channelMask) is true.
141     * frameCount:         Minimum size of track PCM buffer in frames. This defines the
142     *                     application's contribution to the
143     *                     latency of the track.  The actual size selected by the AudioRecord could
144     *                     be larger if the requested size is not compatible with current audio HAL
145     *                     latency.  Zero means to use a default value.
146     * cbf:                Callback function. If not null, this function is called periodically
147     *                     to consume new data and inform of marker, position updates, etc.
148     * user:               Context for use by the callback receiver.
149     * notificationFrames: The callback function is called each time notificationFrames PCM
150     *                     frames are ready in record track output buffer.
151     * sessionId:          Not yet supported.
152     * transferType:       How data is transferred from AudioRecord.
153     * flags:              See comments on audio_input_flags_t in <system/audio.h>
154     * threadCanCallJava:  Not present in parameter list, and so is fixed at false.
155     */
156
157                        AudioRecord(audio_source_t inputSource,
158                                    uint32_t sampleRate,
159                                    audio_format_t format,
160                                    audio_channel_mask_t channelMask,
161                                    size_t frameCount = 0,
162                                    callback_t cbf = NULL,
163                                    void* user = NULL,
164                                    uint32_t notificationFrames = 0,
165                                    int sessionId = AUDIO_SESSION_ALLOCATE,
166                                    transfer_type transferType = TRANSFER_DEFAULT,
167                                    audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE);
168
169    /* Terminates the AudioRecord and unregisters it from AudioFlinger.
170     * Also destroys all resources associated with the AudioRecord.
171     */
172protected:
173                        virtual ~AudioRecord();
174public:
175
176    /* Initialize an AudioRecord that was created using the AudioRecord() constructor.
177     * Don't call set() more than once, or after an AudioRecord() constructor that takes parameters.
178     * Returned status (from utils/Errors.h) can be:
179     *  - NO_ERROR: successful intialization
180     *  - INVALID_OPERATION: AudioRecord is already initialized or record device is already in use
181     *  - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...)
182     *  - NO_INIT: audio server or audio hardware not initialized
183     *  - PERMISSION_DENIED: recording is not allowed for the requesting process
184     * If status is not equal to NO_ERROR, don't call any other APIs on this AudioRecord.
185     *
186     * Parameters not listed in the AudioRecord constructors above:
187     *
188     * threadCanCallJava:  Whether callbacks are made from an attached thread and thus can call JNI.
189     */
190            status_t    set(audio_source_t inputSource,
191                            uint32_t sampleRate,
192                            audio_format_t format,
193                            audio_channel_mask_t channelMask,
194                            size_t frameCount = 0,
195                            callback_t cbf = NULL,
196                            void* user = NULL,
197                            uint32_t notificationFrames = 0,
198                            bool threadCanCallJava = false,
199                            int sessionId = AUDIO_SESSION_ALLOCATE,
200                            transfer_type transferType = TRANSFER_DEFAULT,
201                            audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE);
202
203    /* Result of constructing the AudioRecord. This must be checked for successful initialization
204     * before using any AudioRecord API (except for set()), because using
205     * an uninitialized AudioRecord produces undefined results.
206     * See set() method above for possible return codes.
207     */
208            status_t    initCheck() const   { return mStatus; }
209
210    /* Returns this track's estimated latency in milliseconds.
211     * This includes the latency due to AudioRecord buffer size,
212     * and audio hardware driver.
213     */
214            uint32_t    latency() const     { return mLatency; }
215
216   /* getters, see constructor and set() */
217
218            audio_format_t format() const   { return mFormat; }
219            uint32_t    channelCount() const    { return mChannelCount; }
220            size_t      frameCount() const  { return mFrameCount; }
221            size_t      frameSize() const   { return mFrameSize; }
222            audio_source_t inputSource() const  { return mInputSource; }
223
224    /* After it's created the track is not active. Call start() to
225     * make it active. If set, the callback will start being called.
226     * If event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until
227     * the specified event occurs on the specified trigger session.
228     */
229            status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
230                              int triggerSession = 0);
231
232    /* Stop a track.  The callback will cease being called.  Note that obtainBuffer() still
233     * works and will drain buffers until the pool is exhausted, and then will return WOULD_BLOCK.
234     */
235            void        stop();
236            bool        stopped() const;
237
238    /* Return the sink sample rate for this record track in Hz.
239     * Unlike AudioTrack, the sample rate is const after initialization, so doesn't need a lock.
240     */
241            uint32_t    getSampleRate() const   { return mSampleRate; }
242
243    /* Sets marker position. When record reaches the number of frames specified,
244     * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
245     * with marker == 0 cancels marker notification callback.
246     * To set a marker at a position which would compute as 0,
247     * a workaround is to set the marker at a nearby position such as ~0 or 1.
248     * If the AudioRecord has been opened with no callback function associated,
249     * the operation will fail.
250     *
251     * Parameters:
252     *
253     * marker:   marker position expressed in wrapping (overflow) frame units,
254     *           like the return value of getPosition().
255     *
256     * Returned status (from utils/Errors.h) can be:
257     *  - NO_ERROR: successful operation
258     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
259     */
260            status_t    setMarkerPosition(uint32_t marker);
261            status_t    getMarkerPosition(uint32_t *marker) const;
262
263    /* Sets position update period. Every time the number of frames specified has been recorded,
264     * a callback with event type EVENT_NEW_POS is called.
265     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
266     * callback.
267     * If the AudioRecord has been opened with no callback function associated,
268     * the operation will fail.
269     * Extremely small values may be rounded up to a value the implementation can support.
270     *
271     * Parameters:
272     *
273     * updatePeriod:  position update notification period expressed in frames.
274     *
275     * Returned status (from utils/Errors.h) can be:
276     *  - NO_ERROR: successful operation
277     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
278     */
279            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
280            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
281
282    /* Return the total number of frames recorded since recording started.
283     * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
284     * It is reset to zero by stop().
285     *
286     * Parameters:
287     *
288     *  position:  Address where to return record head position.
289     *
290     * Returned status (from utils/Errors.h) can be:
291     *  - NO_ERROR: successful operation
292     *  - BAD_VALUE:  position is NULL
293     */
294            status_t    getPosition(uint32_t *position) const;
295
296    /* Returns a handle on the audio input used by this AudioRecord.
297     *
298     * Parameters:
299     *  none.
300     *
301     * Returned value:
302     *  handle on audio hardware input
303     */
304            audio_io_handle_t    getInput() const;
305
306    /* Returns the audio session ID associated with this AudioRecord.
307     *
308     * Parameters:
309     *  none.
310     *
311     * Returned value:
312     *  AudioRecord session ID.
313     *
314     * No lock needed because session ID doesn't change after first set().
315     */
316            int    getSessionId() const { return mSessionId; }
317
318    /* Obtains a buffer of up to "audioBuffer->frameCount" full frames.
319     * After draining these frames of data, the caller should release them with releaseBuffer().
320     * If the track buffer is not empty, obtainBuffer() returns as many contiguous
321     * full frames as are available immediately.
322     * If the track buffer is empty and track is stopped, obtainBuffer() returns WOULD_BLOCK
323     * regardless of the value of waitCount.
324     * If the track buffer is empty and track is not stopped, obtainBuffer() blocks with a
325     * maximum timeout based on waitCount; see chart below.
326     * Buffers will be returned until the pool
327     * is exhausted, at which point obtainBuffer() will either block
328     * or return WOULD_BLOCK depending on the value of the "waitCount"
329     * parameter.
330     *
331     * obtainBuffer() and releaseBuffer() are deprecated for direct use by applications,
332     * which should use read() or callback EVENT_MORE_DATA instead.
333     *
334     * Interpretation of waitCount:
335     *  +n  limits wait time to n * WAIT_PERIOD_MS,
336     *  -1  causes an (almost) infinite wait time,
337     *   0  non-blocking.
338     *
339     * Buffer fields
340     * On entry:
341     *  frameCount  number of frames requested
342     * After error return:
343     *  frameCount  0
344     *  size        0
345     *  raw         undefined
346     * After successful return:
347     *  frameCount  actual number of frames available, <= number requested
348     *  size        actual number of bytes available
349     *  raw         pointer to the buffer
350     */
351
352    /* FIXME Deprecated public API for TRANSFER_OBTAIN mode */
353            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
354                                __attribute__((__deprecated__));
355
356private:
357    /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
358     * additional non-contiguous frames that are available immediately.
359     * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
360     * in case the requested amount of frames is in two or more non-contiguous regions.
361     * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
362     */
363            status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
364                                     struct timespec *elapsed = NULL, size_t *nonContig = NULL);
365public:
366
367    /* Release an emptied buffer of "audioBuffer->frameCount" frames for AudioFlinger to re-fill. */
368    // FIXME make private when obtainBuffer() for TRANSFER_OBTAIN is removed
369            void        releaseBuffer(Buffer* audioBuffer);
370
371    /* As a convenience we provide a read() interface to the audio buffer.
372     * Input parameter 'size' is in byte units.
373     * This is implemented on top of obtainBuffer/releaseBuffer. For best
374     * performance use callbacks. Returns actual number of bytes read >= 0,
375     * or one of the following negative status codes:
376     *      INVALID_OPERATION   AudioRecord is configured for streaming mode
377     *      BAD_VALUE           size is invalid
378     *      WOULD_BLOCK         when obtainBuffer() returns same, or
379     *                          AudioRecord was stopped during the read
380     *      or any other error code returned by IAudioRecord::start() or restoreRecord_l().
381     */
382            ssize_t     read(void* buffer, size_t size);
383
384    /* Return the number of input frames lost in the audio driver since the last call of this
385     * function.  Audio driver is expected to reset the value to 0 and restart counting upon
386     * returning the current value by this function call.  Such loss typically occurs when the
387     * user space process is blocked longer than the capacity of audio driver buffers.
388     * Units: the number of input audio frames.
389     * FIXME The side-effect of resetting the counter may be incompatible with multi-client.
390     * Consider making it more like AudioTrack::getUnderrunFrames which doesn't have side effects.
391     */
392            uint32_t    getInputFramesLost() const;
393
394private:
395    /* copying audio record objects is not allowed */
396                        AudioRecord(const AudioRecord& other);
397            AudioRecord& operator = (const AudioRecord& other);
398
399    /* a small internal class to handle the callback */
400    class AudioRecordThread : public Thread
401    {
402    public:
403        AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
404
405        // Do not call Thread::requestExitAndWait() without first calling requestExit().
406        // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
407        virtual void        requestExit();
408
409                void        pause();    // suspend thread from execution at next loop boundary
410                void        resume();   // allow thread to execute, if not requested to exit
411
412    private:
413                void        pauseInternal(nsecs_t ns = 0LL);
414                                        // like pause(), but only used internally within thread
415
416        friend class AudioRecord;
417        virtual bool        threadLoop();
418        AudioRecord&        mReceiver;
419        virtual ~AudioRecordThread();
420        Mutex               mMyLock;    // Thread::mLock is private
421        Condition           mMyCond;    // Thread::mThreadExitedCondition is private
422        bool                mPaused;    // whether thread is requested to pause at next loop entry
423        bool                mPausedInt; // whether thread internally requests pause
424        nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
425        bool                mIgnoreNextPausedInt;   // whether to ignore next mPausedInt request
426    };
427
428            // body of AudioRecordThread::threadLoop()
429            // returns the maximum amount of time before we would like to run again, where:
430            //      0           immediately
431            //      > 0         no later than this many nanoseconds from now
432            //      NS_WHENEVER still active but no particular deadline
433            //      NS_INACTIVE inactive so don't run again until re-started
434            //      NS_NEVER    never again
435            static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
436            nsecs_t processAudioBuffer();
437
438            // caller must hold lock on mLock for all _l methods
439
440            status_t openRecord_l(size_t epoch);
441
442            // FIXME enum is faster than strcmp() for parameter 'from'
443            status_t restoreRecord_l(const char *from);
444
445    sp<AudioRecordThread>   mAudioRecordThread;
446    mutable Mutex           mLock;
447
448    // Current client state:  false = stopped, true = active.  Protected by mLock.  If more states
449    // are added, consider changing this to enum State { ... } mState as in AudioTrack.
450    bool                    mActive;
451
452    // for client callback handler
453    callback_t              mCbf;               // callback handler for events, or NULL
454    void*                   mUserData;
455
456    // for notification APIs
457    uint32_t                mNotificationFramesReq; // requested number of frames between each
458                                                    // notification callback
459    uint32_t                mNotificationFramesAct; // actual number of frames between each
460                                                    // notification callback
461    bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
462                                                    // mRemainingFrames and mRetryOnPartialBuffer
463
464    // These are private to processAudioBuffer(), and are not protected by a lock
465    uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
466    bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
467    uint32_t                mObservedSequence;      // last observed value of mSequence
468
469    uint32_t                mMarkerPosition;    // in wrapping (overflow) frame units
470    bool                    mMarkerReached;
471    uint32_t                mNewPosition;       // in frames
472    uint32_t                mUpdatePeriod;      // in frames, zero means no EVENT_NEW_POS
473
474    status_t                mStatus;
475
476    size_t                  mFrameCount;            // corresponds to current IAudioRecord, value is
477                                                    // reported back by AudioFlinger to the client
478    size_t                  mReqFrameCount;         // frame count to request the first or next time
479                                                    // a new IAudioRecord is needed, non-decreasing
480
481    // constant after constructor or set()
482    uint32_t                mSampleRate;
483    audio_format_t          mFormat;
484    uint32_t                mChannelCount;
485    size_t                  mFrameSize;         // app-level frame size == AudioFlinger frame size
486    audio_source_t          mInputSource;
487    uint32_t                mLatency;           // in ms
488    audio_channel_mask_t    mChannelMask;
489    audio_input_flags_t     mFlags;
490    int                     mSessionId;
491    transfer_type           mTransfer;
492
493    // Next 4 fields may be changed if IAudioRecord is re-created, but always != 0
494    sp<IAudioRecord>        mAudioRecord;
495    sp<IMemory>             mCblkMemory;
496    audio_track_cblk_t*     mCblk;              // re-load after mLock.unlock()
497    audio_io_handle_t       mInput;             // returned by AudioSystem::getInput()
498
499    int                     mPreviousPriority;  // before start()
500    SchedPolicy             mPreviousSchedulingGroup;
501    bool                    mAwaitBoost;    // thread should wait for priority boost before running
502
503    // The proxy should only be referenced while a lock is held because the proxy isn't
504    // multi-thread safe.
505    // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
506    // provided that the caller also holds an extra reference to the proxy and shared memory to keep
507    // them around in case they are replaced during the obtainBuffer().
508    sp<AudioRecordClientProxy> mProxy;
509
510    bool                    mInOverrun;         // whether recorder is currently in overrun state
511
512private:
513    class DeathNotifier : public IBinder::DeathRecipient {
514    public:
515        DeathNotifier(AudioRecord* audioRecord) : mAudioRecord(audioRecord) { }
516    protected:
517        virtual void        binderDied(const wp<IBinder>& who);
518    private:
519        const wp<AudioRecord> mAudioRecord;
520    };
521
522    sp<DeathNotifier>       mDeathNotifier;
523    uint32_t                mSequence;              // incremented for each new IAudioRecord attempt
524};
525
526}; // namespace android
527
528#endif // ANDROID_AUDIORECORD_H
529