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