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 <memory>
21 #include <vector>
22 
23 #include <binder/IMemory.h>
24 #include <cutils/sched_policy.h>
25 #include <media/AudioSystem.h>
26 #include <media/AudioTimestamp.h>
27 #include <media/MediaMetricsItem.h>
28 #include <media/Modulo.h>
29 #include <media/MicrophoneInfo.h>
30 #include <media/RecordingActivityTracker.h>
31 #include <utils/RefBase.h>
32 #include <utils/threads.h>
33 
34 #include "android/media/IAudioRecord.h"
35 
36 namespace android {
37 
38 // ----------------------------------------------------------------------------
39 
40 struct audio_track_cblk_t;
41 class AudioRecordClientProxy;
42 
43 // ----------------------------------------------------------------------------
44 
45 class AudioRecord : public AudioSystem::AudioDeviceCallback
46 {
47 public:
48 
49     /* Events used by AudioRecord callback function (callback_t).
50      * Keep in sync with frameworks/base/media/java/android/media/AudioRecord.java NATIVE_EVENT_*.
51      */
52     enum event_type {
53         EVENT_MORE_DATA = 0,        // Request to read available data from buffer.
54                                     // If this event is delivered but the callback handler
55                                     // does not want to read the available data, the handler must
56                                     // explicitly ignore the event by setting frameCount to zero.
57         EVENT_OVERRUN = 1,          // Buffer overrun occurred.
58         EVENT_MARKER = 2,           // Record head is at the specified marker position
59                                     // (See setMarkerPosition()).
60         EVENT_NEW_POS = 3,          // Record head is at a new position
61                                     // (See setPositionUpdatePeriod()).
62         EVENT_NEW_IAUDIORECORD = 4, // IAudioRecord was re-created, either due to re-routing and
63                                     // voluntary invalidation by mediaserver, or mediaserver crash.
64     };
65 
66     /* Client should declare a Buffer and pass address to obtainBuffer()
67      * and releaseBuffer().  See also callback_t for EVENT_MORE_DATA.
68      */
69 
70     class Buffer
71     {
72     public:
73         // FIXME use m prefix
74         size_t      frameCount;     // number of sample frames corresponding to size;
75                                     // on input to obtainBuffer() it is the number of frames desired
76                                     // on output from obtainBuffer() it is the number of available
77                                     //    frames to be read
78                                     // on input to releaseBuffer() it is currently ignored
79 
80         size_t      size;           // input/output in bytes == frameCount * frameSize
81                                     // on input to obtainBuffer() it is ignored
82                                     // on output from obtainBuffer() it is the number of available
83                                     //    bytes to be read, which is frameCount * frameSize
84                                     // on input to releaseBuffer() it is the number of bytes to
85                                     //    release
86                                     // FIXME This is redundant with respect to frameCount.  Consider
87                                     //    removing size and making frameCount the primary field.
88 
89         union {
90             void*       raw;
91             int16_t*    i16;        // signed 16-bit
92             int8_t*     i8;         // unsigned 8-bit, offset by 0x80
93                                     // input to obtainBuffer(): unused, output: pointer to buffer
94         };
95 
96         uint32_t    sequence;       // IAudioRecord instance sequence number, as of obtainBuffer().
97                                     // It is set by obtainBuffer() and confirmed by releaseBuffer().
98                                     // Not "user-serviceable".
99                                     // TODO Consider sp<IMemory> instead, or in addition to this.
100     };
101 
102     /* As a convenience, if a callback is supplied, a handler thread
103      * is automatically created with the appropriate priority. This thread
104      * invokes the callback when a new buffer becomes available or various conditions occur.
105      * Parameters:
106      *
107      * event:   type of event notified (see enum AudioRecord::event_type).
108      * user:    Pointer to context for use by the callback receiver.
109      * info:    Pointer to optional parameter according to event type:
110      *          - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read
111      *                             more bytes than indicated by 'size' field and update 'size' if
112      *                             fewer bytes are consumed.
113      *          - EVENT_OVERRUN: unused.
114      *          - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames.
115      *          - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames.
116      *          - EVENT_NEW_IAUDIORECORD: unused.
117      */
118 
119     typedef void (*callback_t)(int event, void* user, void *info);
120 
121     /* Returns the minimum frame count required for the successful creation of
122      * an AudioRecord object.
123      * Returned status (from utils/Errors.h) can be:
124      *  - NO_ERROR: successful operation
125      *  - NO_INIT: audio server or audio hardware not initialized
126      *  - BAD_VALUE: unsupported configuration
127      * frameCount is guaranteed to be non-zero if status is NO_ERROR,
128      * and is undefined otherwise.
129      * FIXME This API assumes a route, and so should be deprecated.
130      */
131 
132      static status_t getMinFrameCount(size_t* frameCount,
133                                       uint32_t sampleRate,
134                                       audio_format_t format,
135                                       audio_channel_mask_t channelMask);
136 
137     /* How data is transferred from AudioRecord
138      */
139     enum transfer_type {
140         TRANSFER_DEFAULT,   // not specified explicitly; determine from the other parameters
141         TRANSFER_CALLBACK,  // callback EVENT_MORE_DATA
142         TRANSFER_OBTAIN,    // call obtainBuffer() and releaseBuffer()
143         TRANSFER_SYNC,      // synchronous read()
144     };
145 
146     /* Constructs an uninitialized AudioRecord. No connection with
147      * AudioFlinger takes place.  Use set() after this.
148      *
149      * Parameters:
150      *
151      * opPackageName:      The package name used for app ops.
152      */
153                         AudioRecord(const String16& opPackageName);
154 
155     /* Creates an AudioRecord object and registers it with AudioFlinger.
156      * Once created, the track needs to be started before it can be used.
157      * Unspecified values are set to appropriate default values.
158      *
159      * Parameters:
160      *
161      * inputSource:        Select the audio input to record from (e.g. AUDIO_SOURCE_DEFAULT).
162      * sampleRate:         Data sink sampling rate in Hz.  Zero means to use the source sample rate.
163      * format:             Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed
164      *                     16 bits per sample).
165      * channelMask:        Channel mask, such that audio_is_input_channel(channelMask) is true.
166      * opPackageName:      The package name used for app ops.
167      * frameCount:         Minimum size of track PCM buffer in frames. This defines the
168      *                     application's contribution to the
169      *                     latency of the track.  The actual size selected by the AudioRecord could
170      *                     be larger if the requested size is not compatible with current audio HAL
171      *                     latency.  Zero means to use a default value.
172      * cbf:                Callback function. If not null, this function is called periodically
173      *                     to consume new data in TRANSFER_CALLBACK mode
174      *                     and inform of marker, position updates, etc.
175      * user:               Context for use by the callback receiver.
176      * notificationFrames: The callback function is called each time notificationFrames PCM
177      *                     frames are ready in record track output buffer.
178      * sessionId:          Not yet supported.
179      * transferType:       How data is transferred from AudioRecord.
180      * flags:              See comments on audio_input_flags_t in <system/audio.h>
181      * pAttributes:        If not NULL, supersedes inputSource for use case selection.
182      * threadCanCallJava:  Not present in parameter list, and so is fixed at false.
183      */
184 
185                         AudioRecord(audio_source_t inputSource,
186                                     uint32_t sampleRate,
187                                     audio_format_t format,
188                                     audio_channel_mask_t channelMask,
189                                     const String16& opPackageName,
190                                     size_t frameCount = 0,
191                                     callback_t cbf = NULL,
192                                     void* user = NULL,
193                                     uint32_t notificationFrames = 0,
194                                     audio_session_t sessionId = AUDIO_SESSION_ALLOCATE,
195                                     transfer_type transferType = TRANSFER_DEFAULT,
196                                     audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE,
197                                     uid_t uid = AUDIO_UID_INVALID,
198                                     pid_t pid = -1,
199                                     const audio_attributes_t* pAttributes = NULL,
200                                     audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE,
201                                     audio_microphone_direction_t
202                                         selectedMicDirection = MIC_DIRECTION_UNSPECIFIED,
203                                     float selectedMicFieldDimension = MIC_FIELD_DIMENSION_DEFAULT);
204 
205     /* Terminates the AudioRecord and unregisters it from AudioFlinger.
206      * Also destroys all resources associated with the AudioRecord.
207      */
208 protected:
209                         virtual ~AudioRecord();
210 public:
211 
212     /* Initialize an AudioRecord that was created using the AudioRecord() constructor.
213      * Don't call set() more than once, or after an AudioRecord() constructor that takes parameters.
214      * set() is not multi-thread safe.
215      * Returned status (from utils/Errors.h) can be:
216      *  - NO_ERROR: successful intialization
217      *  - INVALID_OPERATION: AudioRecord is already initialized or record device is already in use
218      *  - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...)
219      *  - NO_INIT: audio server or audio hardware not initialized
220      *  - PERMISSION_DENIED: recording is not allowed for the requesting process
221      * If status is not equal to NO_ERROR, don't call any other APIs on this AudioRecord.
222      *
223      * Parameters not listed in the AudioRecord constructors above:
224      *
225      * threadCanCallJava:  Whether callbacks are made from an attached thread and thus can call JNI.
226      */
227             status_t    set(audio_source_t inputSource,
228                             uint32_t sampleRate,
229                             audio_format_t format,
230                             audio_channel_mask_t channelMask,
231                             size_t frameCount = 0,
232                             callback_t cbf = NULL,
233                             void* user = NULL,
234                             uint32_t notificationFrames = 0,
235                             bool threadCanCallJava = false,
236                             audio_session_t sessionId = AUDIO_SESSION_ALLOCATE,
237                             transfer_type transferType = TRANSFER_DEFAULT,
238                             audio_input_flags_t flags = AUDIO_INPUT_FLAG_NONE,
239                             uid_t uid = AUDIO_UID_INVALID,
240                             pid_t pid = -1,
241                             const audio_attributes_t* pAttributes = NULL,
242                             audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE,
243                             audio_microphone_direction_t
244                                 selectedMicDirection = MIC_DIRECTION_UNSPECIFIED,
245                             float selectedMicFieldDimension = MIC_FIELD_DIMENSION_DEFAULT);
246 
247     /* Result of constructing the AudioRecord. This must be checked for successful initialization
248      * before using any AudioRecord API (except for set()), because using
249      * an uninitialized AudioRecord produces undefined results.
250      * See set() method above for possible return codes.
251      */
initCheck()252             status_t    initCheck() const   { return mStatus; }
253 
254     /* Returns this track's estimated latency in milliseconds.
255      * This includes the latency due to AudioRecord buffer size, resampling if applicable,
256      * and audio hardware driver.
257      */
latency()258             uint32_t    latency() const     { return mLatency; }
259 
260    /* getters, see constructor and set() */
261 
format()262             audio_format_t format() const   { return mFormat; }
channelCount()263             uint32_t    channelCount() const    { return mChannelCount; }
frameCount()264             size_t      frameCount() const  { return mFrameCount; }
frameSize()265             size_t      frameSize() const   { return mFrameSize; }
inputSource()266             audio_source_t inputSource() const  { return mAttributes.source; }
267 
268     /*
269      * Return the period of the notification callback in frames.
270      * This value is set when the AudioRecord is constructed.
271      * It can be modified if the AudioRecord is rerouted.
272      */
getNotificationPeriodInFrames()273             uint32_t    getNotificationPeriodInFrames() const { return mNotificationFramesAct; }
274 
275     /*
276      * return metrics information for the current instance.
277      */
278             status_t getMetrics(mediametrics::Item * &item);
279 
280     /*
281      * Set name of API that is using this object.
282      * For example "aaudio" or "opensles".
283      * This may be logged or reported as part of MediaMetrics.
284      */
setCallerName(const std::string & name)285             void setCallerName(const std::string &name) {
286                 mCallerName = name;
287             }
288 
getCallerName()289             std::string getCallerName() const {
290                 return mCallerName;
291             };
292 
293     /* After it's created the track is not active. Call start() to
294      * make it active. If set, the callback will start being called.
295      * If event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until
296      * the specified event occurs on the specified trigger session.
297      */
298             status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
299                               audio_session_t triggerSession = AUDIO_SESSION_NONE);
300 
301     /* Stop a track.  The callback will cease being called.  Note that obtainBuffer() still
302      * works and will drain buffers until the pool is exhausted, and then will return WOULD_BLOCK.
303      */
304             void        stop();
305             bool        stopped() const;
306 
307     /* Return the sink sample rate for this record track in Hz.
308      * If specified as zero in constructor or set(), this will be the source sample rate.
309      * Unlike AudioTrack, the sample rate is const after initialization, so doesn't need a lock.
310      */
getSampleRate()311             uint32_t    getSampleRate() const   { return mSampleRate; }
312 
313     /* Sets marker position. When record reaches the number of frames specified,
314      * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
315      * with marker == 0 cancels marker notification callback.
316      * To set a marker at a position which would compute as 0,
317      * a workaround is to set the marker at a nearby position such as ~0 or 1.
318      * If the AudioRecord has been opened with no callback function associated,
319      * the operation will fail.
320      *
321      * Parameters:
322      *
323      * marker:   marker position expressed in wrapping (overflow) frame units,
324      *           like the return value of getPosition().
325      *
326      * Returned status (from utils/Errors.h) can be:
327      *  - NO_ERROR: successful operation
328      *  - INVALID_OPERATION: the AudioRecord has no callback installed.
329      */
330             status_t    setMarkerPosition(uint32_t marker);
331             status_t    getMarkerPosition(uint32_t *marker) const;
332 
333     /* Sets position update period. Every time the number of frames specified has been recorded,
334      * a callback with event type EVENT_NEW_POS is called.
335      * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
336      * callback.
337      * If the AudioRecord has been opened with no callback function associated,
338      * the operation will fail.
339      * Extremely small values may be rounded up to a value the implementation can support.
340      *
341      * Parameters:
342      *
343      * updatePeriod:  position update notification period expressed in frames.
344      *
345      * Returned status (from utils/Errors.h) can be:
346      *  - NO_ERROR: successful operation
347      *  - INVALID_OPERATION: the AudioRecord has no callback installed.
348      */
349             status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
350             status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
351 
352     /* Return the total number of frames recorded since recording started.
353      * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
354      * It is reset to zero by stop().
355      *
356      * Parameters:
357      *
358      *  position:  Address where to return record head position.
359      *
360      * Returned status (from utils/Errors.h) can be:
361      *  - NO_ERROR: successful operation
362      *  - BAD_VALUE:  position is NULL
363      */
364             status_t    getPosition(uint32_t *position) const;
365 
366     /* Return the record timestamp.
367      *
368      * Parameters:
369      *  timestamp: A pointer to the timestamp to be filled.
370      *
371      * Returned status (from utils/Errors.h) can be:
372      *  - NO_ERROR: successful operation
373      *  - BAD_VALUE: timestamp is NULL
374      */
375             status_t getTimestamp(ExtendedTimestamp *timestamp);
376 
377     /**
378      * @param transferType
379      * @return text string that matches the enum name
380      */
381     static const char * convertTransferToText(transfer_type transferType);
382 
383     /* Returns a handle on the audio input used by this AudioRecord.
384      *
385      * Parameters:
386      *  none.
387      *
388      * Returned value:
389      *  handle on audio hardware input
390      */
391 // FIXME The only known public caller is frameworks/opt/net/voip/src/jni/rtp/AudioGroup.cpp
getInput()392             audio_io_handle_t    getInput() const __attribute__((__deprecated__))
393                                                 { return getInputPrivate(); }
394 private:
395             audio_io_handle_t    getInputPrivate() const;
396 public:
397 
398     /* Returns the audio session ID associated with this AudioRecord.
399      *
400      * Parameters:
401      *  none.
402      *
403      * Returned value:
404      *  AudioRecord session ID.
405      *
406      * No lock needed because session ID doesn't change after first set().
407      */
getSessionId()408             audio_session_t getSessionId() const { return mSessionId; }
409 
410     /* Public API for TRANSFER_OBTAIN mode.
411      * Obtains a buffer of up to "audioBuffer->frameCount" full frames.
412      * After draining these frames of data, the caller should release them with releaseBuffer().
413      * If the track buffer is not empty, obtainBuffer() returns as many contiguous
414      * full frames as are available immediately.
415      *
416      * If nonContig is non-NULL, it is an output parameter that will be set to the number of
417      * additional non-contiguous frames that are predicted to be available immediately,
418      * if the client were to release the first frames and then call obtainBuffer() again.
419      * This value is only a prediction, and needs to be confirmed.
420      * It will be set to zero for an error return.
421      *
422      * If the track buffer is empty and track is stopped, obtainBuffer() returns WOULD_BLOCK
423      * regardless of the value of waitCount.
424      * If the track buffer is empty and track is not stopped, obtainBuffer() blocks with a
425      * maximum timeout based on waitCount; see chart below.
426      * Buffers will be returned until the pool
427      * is exhausted, at which point obtainBuffer() will either block
428      * or return WOULD_BLOCK depending on the value of the "waitCount"
429      * parameter.
430      *
431      * Interpretation of waitCount:
432      *  +n  limits wait time to n * WAIT_PERIOD_MS,
433      *  -1  causes an (almost) infinite wait time,
434      *   0  non-blocking.
435      *
436      * Buffer fields
437      * On entry:
438      *  frameCount  number of frames requested
439      *  size        ignored
440      *  raw         ignored
441      *  sequence    ignored
442      * After error return:
443      *  frameCount  0
444      *  size        0
445      *  raw         undefined
446      *  sequence    undefined
447      * After successful return:
448      *  frameCount  actual number of frames available, <= number requested
449      *  size        actual number of bytes available
450      *  raw         pointer to the buffer
451      *  sequence    IAudioRecord instance sequence number, as of obtainBuffer()
452      */
453 
454             status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount,
455                                 size_t *nonContig = NULL);
456 
457             // Explicit Routing
458     /**
459      * TODO Document this method.
460      */
461             status_t setInputDevice(audio_port_handle_t deviceId);
462 
463     /**
464      * TODO Document this method.
465      */
466             audio_port_handle_t getInputDevice();
467 
468      /* Returns the ID of the audio device actually used by the input to which this AudioRecord
469       * is attached.
470       * The device ID is relevant only if the AudioRecord is active.
471       * When the AudioRecord is inactive, the device ID returned can be either:
472       * - AUDIO_PORT_HANDLE_NONE if the AudioRecord is not attached to any output.
473       * - The device ID used before paused or stopped.
474       * - The device ID selected by audio policy manager of setOutputDevice() if the AudioRecord
475       * has not been started yet.
476       *
477       * Parameters:
478       *  none.
479       */
480      audio_port_handle_t getRoutedDeviceId();
481 
482     /* Add an AudioDeviceCallback. The caller will be notified when the audio device
483      * to which this AudioRecord is routed is updated.
484      * Replaces any previously installed callback.
485      * Parameters:
486      *  callback:  The callback interface
487      * Returns NO_ERROR if successful.
488      *         INVALID_OPERATION if the same callback is already installed.
489      *         NO_INIT or PREMISSION_DENIED if AudioFlinger service is not reachable
490      *         BAD_VALUE if the callback is NULL
491      */
492             status_t addAudioDeviceCallback(
493                     const sp<AudioSystem::AudioDeviceCallback>& callback);
494 
495     /* remove an AudioDeviceCallback.
496      * Parameters:
497      *  callback:  The callback interface
498      * Returns NO_ERROR if successful.
499      *         INVALID_OPERATION if the callback is not installed
500      *         BAD_VALUE if the callback is NULL
501      */
502             status_t removeAudioDeviceCallback(
503                     const sp<AudioSystem::AudioDeviceCallback>& callback);
504 
505             // AudioSystem::AudioDeviceCallback> virtuals
506             virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo,
507                                              audio_port_handle_t deviceId);
508 
509 private:
510     /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
511      * additional non-contiguous frames that are predicted to be available immediately,
512      * if the client were to release the first frames and then call obtainBuffer() again.
513      * This value is only a prediction, and needs to be confirmed.
514      * It will be set to zero for an error return.
515      * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
516      * in case the requested amount of frames is in two or more non-contiguous regions.
517      * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
518      */
519             status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
520                                      struct timespec *elapsed = NULL, size_t *nonContig = NULL);
521 public:
522 
523     /* Public API for TRANSFER_OBTAIN mode.
524      * Release an emptied buffer of "audioBuffer->frameCount" frames for AudioFlinger to re-fill.
525      *
526      * Buffer fields:
527      *  frameCount  currently ignored but recommend to set to actual number of frames consumed
528      *  size        actual number of bytes consumed, must be multiple of frameSize
529      *  raw         ignored
530      */
531             void        releaseBuffer(const Buffer* audioBuffer);
532 
533     /* As a convenience we provide a read() interface to the audio buffer.
534      * Input parameter 'size' is in byte units.
535      * This is implemented on top of obtainBuffer/releaseBuffer. For best
536      * performance use callbacks. Returns actual number of bytes read >= 0,
537      * or one of the following negative status codes:
538      *      INVALID_OPERATION   AudioRecord is configured for streaming mode
539      *      BAD_VALUE           size is invalid
540      *      WOULD_BLOCK         when obtainBuffer() returns same, or
541      *                          AudioRecord was stopped during the read
542      *      or any other error code returned by IAudioRecord::start() or restoreRecord_l().
543      * Default behavior is to only return when all data has been transferred. Set 'blocking' to
544      * false for the method to return immediately without waiting to try multiple times to read
545      * the full content of the buffer.
546      */
547             ssize_t     read(void* buffer, size_t size, bool blocking = true);
548 
549     /* Return the number of input frames lost in the audio driver since the last call of this
550      * function.  Audio driver is expected to reset the value to 0 and restart counting upon
551      * returning the current value by this function call.  Such loss typically occurs when the
552      * user space process is blocked longer than the capacity of audio driver buffers.
553      * Units: the number of input audio frames.
554      * FIXME The side-effect of resetting the counter may be incompatible with multi-client.
555      * Consider making it more like AudioTrack::getUnderrunFrames which doesn't have side effects.
556      */
557             uint32_t    getInputFramesLost() const;
558 
559     /* Get the flags */
getFlags()560             audio_input_flags_t getFlags() const { AutoMutex _l(mLock); return mFlags; }
561 
562     /* Get active microphones. A empty vector of MicrophoneInfo will be passed as a parameter,
563      * the data will be filled when querying the hal.
564      */
565             status_t    getActiveMicrophones(std::vector<media::MicrophoneInfo>* activeMicrophones);
566 
567     /* Set the Microphone direction (for processing purposes).
568      */
569             status_t    setPreferredMicrophoneDirection(audio_microphone_direction_t direction);
570 
571     /* Set the Microphone zoom factor (for processing purposes).
572      */
573             status_t    setPreferredMicrophoneFieldDimension(float zoom);
574 
575      /* Get the unique port ID assigned to this AudioRecord instance by audio policy manager.
576       * The ID is unique across all audioserver clients and can change during the life cycle
577       * of a given AudioRecord instance if the connection to audioserver is restored.
578       */
getPortId()579             audio_port_handle_t getPortId() const { return mPortId; };
580 
581      /*
582       * Dumps the state of an audio record.
583       */
584             status_t    dump(int fd, const Vector<String16>& args) const;
585 
586 private:
587     /* copying audio record objects is not allowed */
588                         AudioRecord(const AudioRecord& other);
589             AudioRecord& operator = (const AudioRecord& other);
590 
591     /* a small internal class to handle the callback */
592     class AudioRecordThread : public Thread
593     {
594     public:
595         AudioRecordThread(AudioRecord& receiver);
596 
597         // Do not call Thread::requestExitAndWait() without first calling requestExit().
598         // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
599         virtual void        requestExit();
600 
601                 void        pause();    // suspend thread from execution at next loop boundary
602                 void        resume();   // allow thread to execute, if not requested to exit
603                 void        wake();     // wake to handle changed notification conditions.
604 
605     private:
606                 void        pauseInternal(nsecs_t ns = 0LL);
607                                         // like pause(), but only used internally within thread
608 
609         friend class AudioRecord;
610         virtual bool        threadLoop();
611         AudioRecord&        mReceiver;
612         virtual ~AudioRecordThread();
613         Mutex               mMyLock;    // Thread::mLock is private
614         Condition           mMyCond;    // Thread::mThreadExitedCondition is private
615         bool                mPaused;    // whether thread is requested to pause at next loop entry
616         bool                mPausedInt; // whether thread internally requests pause
617         nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
618         bool                mIgnoreNextPausedInt;   // skip any internal pause and go immediately
619                                         // to processAudioBuffer() as state may have changed
620                                         // since pause time calculated.
621     };
622 
623             // body of AudioRecordThread::threadLoop()
624             // returns the maximum amount of time before we would like to run again, where:
625             //      0           immediately
626             //      > 0         no later than this many nanoseconds from now
627             //      NS_WHENEVER still active but no particular deadline
628             //      NS_INACTIVE inactive so don't run again until re-started
629             //      NS_NEVER    never again
630             static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
631             nsecs_t processAudioBuffer();
632 
633             // caller must hold lock on mLock for all _l methods
634 
635             status_t createRecord_l(const Modulo<uint32_t> &epoch, const String16& opPackageName);
636 
637             // FIXME enum is faster than strcmp() for parameter 'from'
638             status_t restoreRecord_l(const char *from);
639 
640             void     updateRoutedDeviceId_l();
641 
642     sp<AudioRecordThread>   mAudioRecordThread;
643     mutable Mutex           mLock;
644 
645     std::unique_ptr<RecordingActivityTracker> mTracker;
646 
647     // Current client state:  false = stopped, true = active.  Protected by mLock.  If more states
648     // are added, consider changing this to enum State { ... } mState as in AudioTrack.
649     bool                    mActive;
650 
651     // for client callback handler
652     callback_t              mCbf;                   // callback handler for events, or NULL
653     void*                   mUserData;
654 
655     // for notification APIs
656     uint32_t                mNotificationFramesReq; // requested number of frames between each
657                                                     // notification callback
658                                                     // as specified in constructor or set()
659     uint32_t                mNotificationFramesAct; // actual number of frames between each
660                                                     // notification callback
661     bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
662                                                     // mRemainingFrames and mRetryOnPartialBuffer
663 
664     // These are private to processAudioBuffer(), and are not protected by a lock
665     uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
666     bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
667     uint32_t                mObservedSequence;      // last observed value of mSequence
668 
669     Modulo<uint32_t>        mMarkerPosition;        // in wrapping (overflow) frame units
670     bool                    mMarkerReached;
671     Modulo<uint32_t>        mNewPosition;           // in frames
672     uint32_t                mUpdatePeriod;          // in frames, zero means no EVENT_NEW_POS
673 
674     status_t                mStatus;
675 
676     String16                mOpPackageName;         // The package name used for app ops.
677 
678     size_t                  mFrameCount;            // corresponds to current IAudioRecord, value is
679                                                     // reported back by AudioFlinger to the client
680     size_t                  mReqFrameCount;         // frame count to request the first or next time
681                                                     // a new IAudioRecord is needed, non-decreasing
682 
683     int64_t                 mFramesRead;            // total frames read. reset to zero after
684                                                     // the start() following stop(). It is not
685                                                     // changed after restoring the track.
686     int64_t                 mFramesReadServerOffset; // An offset to server frames read due to
687                                                     // restoring AudioRecord, or stop/start.
688     // constant after constructor or set()
689     uint32_t                mSampleRate;
690     audio_format_t          mFormat;
691     uint32_t                mChannelCount;
692     size_t                  mFrameSize;         // app-level frame size == AudioFlinger frame size
693     uint32_t                mLatency;           // in ms
694     audio_channel_mask_t    mChannelMask;
695 
696     audio_input_flags_t     mFlags;                 // same as mOrigFlags, except for bits that may
697                                                     // be denied by client or server, such as
698                                                     // AUDIO_INPUT_FLAG_FAST.  mLock must be
699                                                     // held to read or write those bits reliably.
700     audio_input_flags_t     mOrigFlags;             // as specified in constructor or set(), const
701 
702     audio_session_t         mSessionId;
703     audio_port_handle_t     mPortId;                    // Id from Audio Policy Manager
704     transfer_type           mTransfer;
705 
706     // Next 5 fields may be changed if IAudioRecord is re-created, but always != 0
707     // provided the initial set() was successful
708     sp<media::IAudioRecord> mAudioRecord;
709     sp<IMemory>             mCblkMemory;
710     audio_track_cblk_t*     mCblk;              // re-load after mLock.unlock()
711     sp<IMemory>             mBufferMemory;
712     audio_io_handle_t       mInput = AUDIO_IO_HANDLE_NONE; // from AudioSystem::getInputforAttr()
713 
714     int                     mPreviousPriority;  // before start()
715     SchedPolicy             mPreviousSchedulingGroup;
716     bool                    mAwaitBoost;    // thread should wait for priority boost before running
717 
718     // The proxy should only be referenced while a lock is held because the proxy isn't
719     // multi-thread safe.
720     // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
721     // provided that the caller also holds an extra reference to the proxy and shared memory to keep
722     // them around in case they are replaced during the obtainBuffer().
723     sp<AudioRecordClientProxy> mProxy;
724 
725     bool                    mInOverrun;         // whether recorder is currently in overrun state
726 
727     ExtendedTimestamp       mPreviousTimestamp{}; // used to detect retrograde motion
728     bool                    mTimestampRetrogradePositionReported = false; // reduce log spam
729     bool                    mTimestampRetrogradeTimeReported = false;     // reduce log spam
730 
731 private:
732     class DeathNotifier : public IBinder::DeathRecipient {
733     public:
DeathNotifier(AudioRecord * audioRecord)734         DeathNotifier(AudioRecord* audioRecord) : mAudioRecord(audioRecord) { }
735     protected:
736         virtual void        binderDied(const wp<IBinder>& who);
737     private:
738         const wp<AudioRecord> mAudioRecord;
739     };
740 
741     sp<DeathNotifier>       mDeathNotifier;
742     uint32_t                mSequence;              // incremented for each new IAudioRecord attempt
743     uid_t                   mClientUid;
744     pid_t                   mClientPid;
745     audio_attributes_t      mAttributes;
746 
747     // For Device Selection API
748     //  a value of AUDIO_PORT_HANDLE_NONE indicated default (AudioPolicyManager) routing.
749     audio_port_handle_t     mSelectedDeviceId; // Device requested by the application.
750     audio_port_handle_t     mRoutedDeviceId;   // Device actually selected by audio policy manager:
751                                               // May not match the app selection depending on other
752                                               // activity and connected devices
753     wp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
754 
755     audio_microphone_direction_t mSelectedMicDirection;
756     float mSelectedMicFieldDimension;
757 
758 private:
759     class MediaMetrics {
760       public:
MediaMetrics()761         MediaMetrics() : mMetricsItem(mediametrics::Item::create("audiorecord")),
762                          mCreatedNs(systemTime(SYSTEM_TIME_REALTIME)),
763                          mStartedNs(0), mDurationNs(0), mCount(0),
764                          mLastError(NO_ERROR) {
765         }
~MediaMetrics()766         ~MediaMetrics() {
767             // mMetricsItem alloc failure will be flagged in the constructor
768             // don't log empty records
769             if (mMetricsItem->count() > 0) {
770                 mMetricsItem->selfrecord();
771             }
772         }
773         void gather(const AudioRecord *record);
dup()774         mediametrics::Item *dup() { return mMetricsItem->dup(); }
775 
logStart(nsecs_t when)776         void logStart(nsecs_t when) { mStartedNs = when; mCount++; }
logStop(nsecs_t when)777         void logStop(nsecs_t when) { mDurationNs += (when-mStartedNs); mStartedNs = 0;}
markError(status_t errcode,const char * func)778         void markError(status_t errcode, const char *func)
779                  { mLastError = errcode; mLastErrorFunc = func;}
780       private:
781         std::unique_ptr<mediametrics::Item> mMetricsItem;
782         nsecs_t mCreatedNs;     // XXX: perhaps not worth it in production
783         nsecs_t mStartedNs;
784         nsecs_t mDurationNs;
785         int32_t mCount;
786 
787         status_t mLastError;
788         std::string mLastErrorFunc;
789     };
790     MediaMetrics mMediaMetrics;
791     std::string mMetricsId;  // GUARDED_BY(mLock), could change in createRecord_l().
792     std::string mCallerName; // for example "aaudio"
793 };
794 
795 }; // namespace android
796 
797 #endif // ANDROID_AUDIORECORD_H
798