• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
25 namespace android {
26 
27 // ----------------------------------------------------------------------------
28 
29 struct audio_track_cblk_t;
30 class AudioRecordClientProxy;
31 
32 // ----------------------------------------------------------------------------
33 
34 class AudioRecord : public RefBase
35 {
36 public:
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      */
172 protected:
173                         virtual ~AudioRecord();
174 public:
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      */
initCheck()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      */
latency()214             uint32_t    latency() const     { return mLatency; }
215 
216    /* getters, see constructor and set() */
217 
format()218             audio_format_t format() const   { return mFormat; }
channelCount()219             uint32_t    channelCount() const    { return mChannelCount; }
frameCount()220             size_t      frameCount() const  { return mFrameCount; }
frameSize()221             size_t      frameSize() const   { return mFrameSize; }
inputSource()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      */
getSampleRate()241             uint32_t    getSampleRate() const   { return mSampleRate; }
242 
243     /* Return the notification frame count.
244      * This is approximately how often the callback is invoked, for transfer type TRANSFER_CALLBACK.
245      */
notificationFrames()246             size_t      notificationFrames() const  { return mNotificationFramesAct; }
247 
248     /* Sets marker position. When record reaches the number of frames specified,
249      * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
250      * with marker == 0 cancels marker notification callback.
251      * To set a marker at a position which would compute as 0,
252      * a workaround is to set the marker at a nearby position such as ~0 or 1.
253      * If the AudioRecord has been opened with no callback function associated,
254      * the operation will fail.
255      *
256      * Parameters:
257      *
258      * marker:   marker position expressed in wrapping (overflow) frame units,
259      *           like the return value of getPosition().
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    setMarkerPosition(uint32_t marker);
266             status_t    getMarkerPosition(uint32_t *marker) const;
267 
268     /* Sets position update period. Every time the number of frames specified has been recorded,
269      * a callback with event type EVENT_NEW_POS is called.
270      * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
271      * callback.
272      * If the AudioRecord has been opened with no callback function associated,
273      * the operation will fail.
274      * Extremely small values may be rounded up to a value the implementation can support.
275      *
276      * Parameters:
277      *
278      * updatePeriod:  position update notification period expressed in frames.
279      *
280      * Returned status (from utils/Errors.h) can be:
281      *  - NO_ERROR: successful operation
282      *  - INVALID_OPERATION: the AudioRecord has no callback installed.
283      */
284             status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
285             status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
286 
287     /* Return the total number of frames recorded since recording started.
288      * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
289      * It is reset to zero by stop().
290      *
291      * Parameters:
292      *
293      *  position:  Address where to return record head position.
294      *
295      * Returned status (from utils/Errors.h) can be:
296      *  - NO_ERROR: successful operation
297      *  - BAD_VALUE:  position is NULL
298      */
299             status_t    getPosition(uint32_t *position) const;
300 
301     /* Returns a handle on the audio input used by this AudioRecord.
302      *
303      * Parameters:
304      *  none.
305      *
306      * Returned value:
307      *  handle on audio hardware input
308      */
309             audio_io_handle_t    getInput() const;
310 
311     /* Returns the audio session ID associated with this AudioRecord.
312      *
313      * Parameters:
314      *  none.
315      *
316      * Returned value:
317      *  AudioRecord session ID.
318      *
319      * No lock needed because session ID doesn't change after first set().
320      */
getSessionId()321             int    getSessionId() const { return mSessionId; }
322 
323     /* Obtains a buffer of up to "audioBuffer->frameCount" full frames.
324      * After draining these frames of data, the caller should release them with releaseBuffer().
325      * If the track buffer is not empty, obtainBuffer() returns as many contiguous
326      * full frames as are available immediately.
327      * If the track buffer is empty and track is stopped, obtainBuffer() returns WOULD_BLOCK
328      * regardless of the value of waitCount.
329      * If the track buffer is empty and track is not stopped, obtainBuffer() blocks with a
330      * maximum timeout based on waitCount; see chart below.
331      * Buffers will be returned until the pool
332      * is exhausted, at which point obtainBuffer() will either block
333      * or return WOULD_BLOCK depending on the value of the "waitCount"
334      * parameter.
335      *
336      * obtainBuffer() and releaseBuffer() are deprecated for direct use by applications,
337      * which should use read() or callback EVENT_MORE_DATA instead.
338      *
339      * Interpretation of waitCount:
340      *  +n  limits wait time to n * WAIT_PERIOD_MS,
341      *  -1  causes an (almost) infinite wait time,
342      *   0  non-blocking.
343      *
344      * Buffer fields
345      * On entry:
346      *  frameCount  number of frames requested
347      * After error return:
348      *  frameCount  0
349      *  size        0
350      *  raw         undefined
351      * After successful return:
352      *  frameCount  actual number of frames available, <= number requested
353      *  size        actual number of bytes available
354      *  raw         pointer to the buffer
355      */
356 
357     /* FIXME Deprecated public API for TRANSFER_OBTAIN mode */
358             status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount)
359                                 __attribute__((__deprecated__));
360 
361 private:
362     /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
363      * additional non-contiguous frames that are available immediately.
364      * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
365      * in case the requested amount of frames is in two or more non-contiguous regions.
366      * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
367      */
368             status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
369                                      struct timespec *elapsed = NULL, size_t *nonContig = NULL);
370 public:
371 
372     /* Release an emptied buffer of "audioBuffer->frameCount" frames for AudioFlinger to re-fill. */
373     // FIXME make private when obtainBuffer() for TRANSFER_OBTAIN is removed
374             void        releaseBuffer(Buffer* audioBuffer);
375 
376     /* As a convenience we provide a read() interface to the audio buffer.
377      * Input parameter 'size' is in byte units.
378      * This is implemented on top of obtainBuffer/releaseBuffer. For best
379      * performance use callbacks. Returns actual number of bytes read >= 0,
380      * or one of the following negative status codes:
381      *      INVALID_OPERATION   AudioRecord is configured for streaming mode
382      *      BAD_VALUE           size is invalid
383      *      WOULD_BLOCK         when obtainBuffer() returns same, or
384      *                          AudioRecord was stopped during the read
385      *      or any other error code returned by IAudioRecord::start() or restoreRecord_l().
386      */
387             ssize_t     read(void* buffer, size_t size);
388 
389     /* Return the number of input frames lost in the audio driver since the last call of this
390      * function.  Audio driver is expected to reset the value to 0 and restart counting upon
391      * returning the current value by this function call.  Such loss typically occurs when the
392      * user space process is blocked longer than the capacity of audio driver buffers.
393      * Units: the number of input audio frames.
394      * FIXME The side-effect of resetting the counter may be incompatible with multi-client.
395      * Consider making it more like AudioTrack::getUnderrunFrames which doesn't have side effects.
396      */
397             uint32_t    getInputFramesLost() const;
398 
399 private:
400     /* copying audio record objects is not allowed */
401                         AudioRecord(const AudioRecord& other);
402             AudioRecord& operator = (const AudioRecord& other);
403 
404     /* a small internal class to handle the callback */
405     class AudioRecordThread : public Thread
406     {
407     public:
408         AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
409 
410         // Do not call Thread::requestExitAndWait() without first calling requestExit().
411         // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
412         virtual void        requestExit();
413 
414                 void        pause();    // suspend thread from execution at next loop boundary
415                 void        resume();   // allow thread to execute, if not requested to exit
416 
417     private:
418                 void        pauseInternal(nsecs_t ns = 0LL);
419                                         // like pause(), but only used internally within thread
420 
421         friend class AudioRecord;
422         virtual bool        threadLoop();
423         AudioRecord&        mReceiver;
424         virtual ~AudioRecordThread();
425         Mutex               mMyLock;    // Thread::mLock is private
426         Condition           mMyCond;    // Thread::mThreadExitedCondition is private
427         bool                mPaused;    // whether thread is requested to pause at next loop entry
428         bool                mPausedInt; // whether thread internally requests pause
429         nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
430         bool                mIgnoreNextPausedInt;   // whether to ignore next mPausedInt request
431     };
432 
433             // body of AudioRecordThread::threadLoop()
434             // returns the maximum amount of time before we would like to run again, where:
435             //      0           immediately
436             //      > 0         no later than this many nanoseconds from now
437             //      NS_WHENEVER still active but no particular deadline
438             //      NS_INACTIVE inactive so don't run again until re-started
439             //      NS_NEVER    never again
440             static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
441             nsecs_t processAudioBuffer();
442 
443             // caller must hold lock on mLock for all _l methods
444 
445             status_t openRecord_l(size_t epoch);
446 
447             // FIXME enum is faster than strcmp() for parameter 'from'
448             status_t restoreRecord_l(const char *from);
449 
450     sp<AudioRecordThread>   mAudioRecordThread;
451     mutable Mutex           mLock;
452 
453     // Current client state:  false = stopped, true = active.  Protected by mLock.  If more states
454     // are added, consider changing this to enum State { ... } mState as in AudioTrack.
455     bool                    mActive;
456 
457     // for client callback handler
458     callback_t              mCbf;               // callback handler for events, or NULL
459     void*                   mUserData;
460 
461     // for notification APIs
462     uint32_t                mNotificationFramesReq; // requested number of frames between each
463                                                     // notification callback
464                                                     // as specified in constructor or set()
465     uint32_t                mNotificationFramesAct; // actual number of frames between each
466                                                     // notification callback
467     bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
468                                                     // mRemainingFrames and mRetryOnPartialBuffer
469 
470     // These are private to processAudioBuffer(), and are not protected by a lock
471     uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
472     bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
473     uint32_t                mObservedSequence;      // last observed value of mSequence
474 
475     uint32_t                mMarkerPosition;    // in wrapping (overflow) frame units
476     bool                    mMarkerReached;
477     uint32_t                mNewPosition;       // in frames
478     uint32_t                mUpdatePeriod;      // in frames, zero means no EVENT_NEW_POS
479 
480     status_t                mStatus;
481 
482     size_t                  mFrameCount;            // corresponds to current IAudioRecord, value is
483                                                     // reported back by AudioFlinger to the client
484     size_t                  mReqFrameCount;         // frame count to request the first or next time
485                                                     // a new IAudioRecord is needed, non-decreasing
486 
487     // constant after constructor or set()
488     uint32_t                mSampleRate;
489     audio_format_t          mFormat;
490     uint32_t                mChannelCount;
491     size_t                  mFrameSize;         // app-level frame size == AudioFlinger frame size
492     audio_source_t          mInputSource;
493     uint32_t                mLatency;           // in ms
494     audio_channel_mask_t    mChannelMask;
495     audio_input_flags_t     mFlags;
496     int                     mSessionId;
497     transfer_type           mTransfer;
498 
499     // Next 5 fields may be changed if IAudioRecord is re-created, but always != 0
500     // provided the initial set() was successful
501     sp<IAudioRecord>        mAudioRecord;
502     sp<IMemory>             mCblkMemory;
503     audio_track_cblk_t*     mCblk;              // re-load after mLock.unlock()
504     sp<IMemory>             mBufferMemory;
505     audio_io_handle_t       mInput;             // returned by AudioSystem::getInput()
506 
507     int                     mPreviousPriority;  // before start()
508     SchedPolicy             mPreviousSchedulingGroup;
509     bool                    mAwaitBoost;    // thread should wait for priority boost before running
510 
511     // The proxy should only be referenced while a lock is held because the proxy isn't
512     // multi-thread safe.
513     // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
514     // provided that the caller also holds an extra reference to the proxy and shared memory to keep
515     // them around in case they are replaced during the obtainBuffer().
516     sp<AudioRecordClientProxy> mProxy;
517 
518     bool                    mInOverrun;         // whether recorder is currently in overrun state
519 
520 private:
521     class DeathNotifier : public IBinder::DeathRecipient {
522     public:
DeathNotifier(AudioRecord * audioRecord)523         DeathNotifier(AudioRecord* audioRecord) : mAudioRecord(audioRecord) { }
524     protected:
525         virtual void        binderDied(const wp<IBinder>& who);
526     private:
527         const wp<AudioRecord> mAudioRecord;
528     };
529 
530     sp<DeathNotifier>       mDeathNotifier;
531     uint32_t                mSequence;              // incremented for each new IAudioRecord attempt
532 };
533 
534 }; // namespace android
535 
536 #endif // ANDROID_AUDIORECORD_H
537