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