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
27namespace android {
28
29// ----------------------------------------------------------------------------
30
31struct audio_track_cblk_t;
32class AudioRecordClientProxy;
33
34// ----------------------------------------------------------------------------
35
36class AudioRecord : public RefBase
37{
38public:
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                                    uid_t uid = AUDIO_UID_INVALID,
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     */
190protected:
191                        virtual ~AudioRecord();
192public:
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                            uid_t uid = AUDIO_UID_INVALID,
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     */
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     */
236            uint32_t    latency() const     { return mLatency; }
237
238   /* getters, see constructor and set() */
239
240            audio_format_t format() const   { return mFormat; }
241            uint32_t    channelCount() const    { return mChannelCount; }
242            size_t      frameCount() const  { return mFrameCount; }
243            size_t      frameSize() const   { return mFrameSize; }
244            audio_source_t inputSource() const  { return mAttributes.source; }
245
246    /*
247     * Return the period of the notification callback in frames.
248     * This value is set when the AudioRecord is constructed.
249     * It can be modified if the AudioRecord is rerouted.
250     */
251            uint32_t    getNotificationPeriodInFrames() const { return mNotificationFramesAct; }
252
253    /* After it's created the track is not active. Call start() to
254     * make it active. If set, the callback will start being called.
255     * If event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until
256     * the specified event occurs on the specified trigger session.
257     */
258            status_t    start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE,
259                              audio_session_t triggerSession = AUDIO_SESSION_NONE);
260
261    /* Stop a track.  The callback will cease being called.  Note that obtainBuffer() still
262     * works and will drain buffers until the pool is exhausted, and then will return WOULD_BLOCK.
263     */
264            void        stop();
265            bool        stopped() const;
266
267    /* Return the sink sample rate for this record track in Hz.
268     * If specified as zero in constructor or set(), this will be the source sample rate.
269     * Unlike AudioTrack, the sample rate is const after initialization, so doesn't need a lock.
270     */
271            uint32_t    getSampleRate() const   { return mSampleRate; }
272
273    /* Sets marker position. When record reaches the number of frames specified,
274     * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition
275     * with marker == 0 cancels marker notification callback.
276     * To set a marker at a position which would compute as 0,
277     * a workaround is to set the marker at a nearby position such as ~0 or 1.
278     * If the AudioRecord has been opened with no callback function associated,
279     * the operation will fail.
280     *
281     * Parameters:
282     *
283     * marker:   marker position expressed in wrapping (overflow) frame units,
284     *           like the return value of getPosition().
285     *
286     * Returned status (from utils/Errors.h) can be:
287     *  - NO_ERROR: successful operation
288     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
289     */
290            status_t    setMarkerPosition(uint32_t marker);
291            status_t    getMarkerPosition(uint32_t *marker) const;
292
293    /* Sets position update period. Every time the number of frames specified has been recorded,
294     * a callback with event type EVENT_NEW_POS is called.
295     * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification
296     * callback.
297     * If the AudioRecord has been opened with no callback function associated,
298     * the operation will fail.
299     * Extremely small values may be rounded up to a value the implementation can support.
300     *
301     * Parameters:
302     *
303     * updatePeriod:  position update notification period expressed in frames.
304     *
305     * Returned status (from utils/Errors.h) can be:
306     *  - NO_ERROR: successful operation
307     *  - INVALID_OPERATION: the AudioRecord has no callback installed.
308     */
309            status_t    setPositionUpdatePeriod(uint32_t updatePeriod);
310            status_t    getPositionUpdatePeriod(uint32_t *updatePeriod) const;
311
312    /* Return the total number of frames recorded since recording started.
313     * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz.
314     * It is reset to zero by stop().
315     *
316     * Parameters:
317     *
318     *  position:  Address where to return record head position.
319     *
320     * Returned status (from utils/Errors.h) can be:
321     *  - NO_ERROR: successful operation
322     *  - BAD_VALUE:  position is NULL
323     */
324            status_t    getPosition(uint32_t *position) const;
325
326    /* Return the record timestamp.
327     *
328     * Parameters:
329     *  timestamp: A pointer to the timestamp to be filled.
330     *
331     * Returned status (from utils/Errors.h) can be:
332     *  - NO_ERROR: successful operation
333     *  - BAD_VALUE: timestamp is NULL
334     */
335            status_t getTimestamp(ExtendedTimestamp *timestamp);
336
337    /* Returns a handle on the audio input used by this AudioRecord.
338     *
339     * Parameters:
340     *  none.
341     *
342     * Returned value:
343     *  handle on audio hardware input
344     */
345// FIXME The only known public caller is frameworks/opt/net/voip/src/jni/rtp/AudioGroup.cpp
346            audio_io_handle_t    getInput() const __attribute__((__deprecated__))
347                                                { return getInputPrivate(); }
348private:
349            audio_io_handle_t    getInputPrivate() const;
350public:
351
352    /* Returns the audio session ID associated with this AudioRecord.
353     *
354     * Parameters:
355     *  none.
356     *
357     * Returned value:
358     *  AudioRecord session ID.
359     *
360     * No lock needed because session ID doesn't change after first set().
361     */
362            audio_session_t getSessionId() const { return mSessionId; }
363
364    /* Public API for TRANSFER_OBTAIN mode.
365     * Obtains a buffer of up to "audioBuffer->frameCount" full frames.
366     * After draining these frames of data, the caller should release them with releaseBuffer().
367     * If the track buffer is not empty, obtainBuffer() returns as many contiguous
368     * full frames as are available immediately.
369     *
370     * If nonContig is non-NULL, it is an output parameter that will be set to the number of
371     * additional non-contiguous frames that are predicted to be available immediately,
372     * if the client were to release the first frames and then call obtainBuffer() again.
373     * This value is only a prediction, and needs to be confirmed.
374     * It will be set to zero for an error return.
375     *
376     * If the track buffer is empty and track is stopped, obtainBuffer() returns WOULD_BLOCK
377     * regardless of the value of waitCount.
378     * If the track buffer is empty and track is not stopped, obtainBuffer() blocks with a
379     * maximum timeout based on waitCount; see chart below.
380     * Buffers will be returned until the pool
381     * is exhausted, at which point obtainBuffer() will either block
382     * or return WOULD_BLOCK depending on the value of the "waitCount"
383     * parameter.
384     *
385     * Interpretation of waitCount:
386     *  +n  limits wait time to n * WAIT_PERIOD_MS,
387     *  -1  causes an (almost) infinite wait time,
388     *   0  non-blocking.
389     *
390     * Buffer fields
391     * On entry:
392     *  frameCount  number of frames requested
393     *  size        ignored
394     *  raw         ignored
395     * After error return:
396     *  frameCount  0
397     *  size        0
398     *  raw         undefined
399     * After successful return:
400     *  frameCount  actual number of frames available, <= number requested
401     *  size        actual number of bytes available
402     *  raw         pointer to the buffer
403     */
404
405            status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount,
406                                size_t *nonContig = NULL);
407
408            // Explicit Routing
409    /**
410     * TODO Document this method.
411     */
412            status_t setInputDevice(audio_port_handle_t deviceId);
413
414    /**
415     * TODO Document this method.
416     */
417            audio_port_handle_t getInputDevice();
418
419     /* Returns the ID of the audio device actually used by the input to which this AudioRecord
420      * is attached.
421      * A value of AUDIO_PORT_HANDLE_NONE indicates the AudioRecord is not attached to any input.
422      *
423      * Parameters:
424      *  none.
425      */
426     audio_port_handle_t getRoutedDeviceId();
427
428    /* Add an AudioDeviceCallback. The caller will be notified when the audio device
429     * to which this AudioRecord is routed is updated.
430     * Replaces any previously installed callback.
431     * Parameters:
432     *  callback:  The callback interface
433     * Returns NO_ERROR if successful.
434     *         INVALID_OPERATION if the same callback is already installed.
435     *         NO_INIT or PREMISSION_DENIED if AudioFlinger service is not reachable
436     *         BAD_VALUE if the callback is NULL
437     */
438            status_t addAudioDeviceCallback(
439                    const sp<AudioSystem::AudioDeviceCallback>& callback);
440
441    /* remove an AudioDeviceCallback.
442     * Parameters:
443     *  callback:  The callback interface
444     * Returns NO_ERROR if successful.
445     *         INVALID_OPERATION if the callback is not installed
446     *         BAD_VALUE if the callback is NULL
447     */
448            status_t removeAudioDeviceCallback(
449                    const sp<AudioSystem::AudioDeviceCallback>& callback);
450
451private:
452    /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
453     * additional non-contiguous frames that are predicted to be available immediately,
454     * if the client were to release the first frames and then call obtainBuffer() again.
455     * This value is only a prediction, and needs to be confirmed.
456     * It will be set to zero for an error return.
457     * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
458     * in case the requested amount of frames is in two or more non-contiguous regions.
459     * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
460     */
461            status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
462                                     struct timespec *elapsed = NULL, size_t *nonContig = NULL);
463public:
464
465    /* Public API for TRANSFER_OBTAIN mode.
466     * Release an emptied buffer of "audioBuffer->frameCount" frames for AudioFlinger to re-fill.
467     *
468     * Buffer fields:
469     *  frameCount  currently ignored but recommend to set to actual number of frames consumed
470     *  size        actual number of bytes consumed, must be multiple of frameSize
471     *  raw         ignored
472     */
473            void        releaseBuffer(const Buffer* audioBuffer);
474
475    /* As a convenience we provide a read() interface to the audio buffer.
476     * Input parameter 'size' is in byte units.
477     * This is implemented on top of obtainBuffer/releaseBuffer. For best
478     * performance use callbacks. Returns actual number of bytes read >= 0,
479     * or one of the following negative status codes:
480     *      INVALID_OPERATION   AudioRecord is configured for streaming mode
481     *      BAD_VALUE           size is invalid
482     *      WOULD_BLOCK         when obtainBuffer() returns same, or
483     *                          AudioRecord was stopped during the read
484     *      or any other error code returned by IAudioRecord::start() or restoreRecord_l().
485     * Default behavior is to only return when all data has been transferred. Set 'blocking' to
486     * false for the method to return immediately without waiting to try multiple times to read
487     * the full content of the buffer.
488     */
489            ssize_t     read(void* buffer, size_t size, bool blocking = true);
490
491    /* Return the number of input frames lost in the audio driver since the last call of this
492     * function.  Audio driver is expected to reset the value to 0 and restart counting upon
493     * returning the current value by this function call.  Such loss typically occurs when the
494     * user space process is blocked longer than the capacity of audio driver buffers.
495     * Units: the number of input audio frames.
496     * FIXME The side-effect of resetting the counter may be incompatible with multi-client.
497     * Consider making it more like AudioTrack::getUnderrunFrames which doesn't have side effects.
498     */
499            uint32_t    getInputFramesLost() const;
500
501    /* Get the flags */
502            audio_input_flags_t getFlags() const { AutoMutex _l(mLock); return mFlags; }
503
504private:
505    /* copying audio record objects is not allowed */
506                        AudioRecord(const AudioRecord& other);
507            AudioRecord& operator = (const AudioRecord& other);
508
509    /* a small internal class to handle the callback */
510    class AudioRecordThread : public Thread
511    {
512    public:
513        AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
514
515        // Do not call Thread::requestExitAndWait() without first calling requestExit().
516        // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
517        virtual void        requestExit();
518
519                void        pause();    // suspend thread from execution at next loop boundary
520                void        resume();   // allow thread to execute, if not requested to exit
521                void        wake();     // wake to handle changed notification conditions.
522
523    private:
524                void        pauseInternal(nsecs_t ns = 0LL);
525                                        // like pause(), but only used internally within thread
526
527        friend class AudioRecord;
528        virtual bool        threadLoop();
529        AudioRecord&        mReceiver;
530        virtual ~AudioRecordThread();
531        Mutex               mMyLock;    // Thread::mLock is private
532        Condition           mMyCond;    // Thread::mThreadExitedCondition is private
533        bool                mPaused;    // whether thread is requested to pause at next loop entry
534        bool                mPausedInt; // whether thread internally requests pause
535        nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
536        bool                mIgnoreNextPausedInt;   // skip any internal pause and go immediately
537                                        // to processAudioBuffer() as state may have changed
538                                        // since pause time calculated.
539    };
540
541            // body of AudioRecordThread::threadLoop()
542            // returns the maximum amount of time before we would like to run again, where:
543            //      0           immediately
544            //      > 0         no later than this many nanoseconds from now
545            //      NS_WHENEVER still active but no particular deadline
546            //      NS_INACTIVE inactive so don't run again until re-started
547            //      NS_NEVER    never again
548            static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
549            nsecs_t processAudioBuffer();
550
551            // caller must hold lock on mLock for all _l methods
552
553            status_t openRecord_l(const Modulo<uint32_t> &epoch, const String16& opPackageName);
554
555            // FIXME enum is faster than strcmp() for parameter 'from'
556            status_t restoreRecord_l(const char *from);
557
558    sp<AudioRecordThread>   mAudioRecordThread;
559    mutable Mutex           mLock;
560
561    // Current client state:  false = stopped, true = active.  Protected by mLock.  If more states
562    // are added, consider changing this to enum State { ... } mState as in AudioTrack.
563    bool                    mActive;
564
565    // for client callback handler
566    callback_t              mCbf;                   // callback handler for events, or NULL
567    void*                   mUserData;
568
569    // for notification APIs
570    uint32_t                mNotificationFramesReq; // requested number of frames between each
571                                                    // notification callback
572                                                    // as specified in constructor or set()
573    uint32_t                mNotificationFramesAct; // actual number of frames between each
574                                                    // notification callback
575    bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
576                                                    // mRemainingFrames and mRetryOnPartialBuffer
577
578    // These are private to processAudioBuffer(), and are not protected by a lock
579    uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
580    bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
581    uint32_t                mObservedSequence;      // last observed value of mSequence
582
583    Modulo<uint32_t>        mMarkerPosition;        // in wrapping (overflow) frame units
584    bool                    mMarkerReached;
585    Modulo<uint32_t>        mNewPosition;           // in frames
586    uint32_t                mUpdatePeriod;          // in frames, zero means no EVENT_NEW_POS
587
588    status_t                mStatus;
589
590    String16                mOpPackageName;         // The package name used for app ops.
591
592    size_t                  mFrameCount;            // corresponds to current IAudioRecord, value is
593                                                    // reported back by AudioFlinger to the client
594    size_t                  mReqFrameCount;         // frame count to request the first or next time
595                                                    // a new IAudioRecord is needed, non-decreasing
596
597    int64_t                 mFramesRead;            // total frames read. reset to zero after
598                                                    // the start() following stop(). It is not
599                                                    // changed after restoring the track.
600    int64_t                 mFramesReadServerOffset; // An offset to server frames read due to
601                                                    // restoring AudioRecord, or stop/start.
602    // constant after constructor or set()
603    uint32_t                mSampleRate;
604    audio_format_t          mFormat;
605    uint32_t                mChannelCount;
606    size_t                  mFrameSize;         // app-level frame size == AudioFlinger frame size
607    uint32_t                mLatency;           // in ms
608    audio_channel_mask_t    mChannelMask;
609
610    audio_input_flags_t     mFlags;                 // same as mOrigFlags, except for bits that may
611                                                    // be denied by client or server, such as
612                                                    // AUDIO_INPUT_FLAG_FAST.  mLock must be
613                                                    // held to read or write those bits reliably.
614    audio_input_flags_t     mOrigFlags;             // as specified in constructor or set(), const
615
616    audio_session_t         mSessionId;
617    transfer_type           mTransfer;
618
619    // Next 5 fields may be changed if IAudioRecord is re-created, but always != 0
620    // provided the initial set() was successful
621    sp<IAudioRecord>        mAudioRecord;
622    sp<IMemory>             mCblkMemory;
623    audio_track_cblk_t*     mCblk;              // re-load after mLock.unlock()
624    sp<IMemory>             mBufferMemory;
625    audio_io_handle_t       mInput;             // returned by AudioSystem::getInput()
626
627    int                     mPreviousPriority;  // before start()
628    SchedPolicy             mPreviousSchedulingGroup;
629    bool                    mAwaitBoost;    // thread should wait for priority boost before running
630
631    // The proxy should only be referenced while a lock is held because the proxy isn't
632    // multi-thread safe.
633    // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
634    // provided that the caller also holds an extra reference to the proxy and shared memory to keep
635    // them around in case they are replaced during the obtainBuffer().
636    sp<AudioRecordClientProxy> mProxy;
637
638    bool                    mInOverrun;         // whether recorder is currently in overrun state
639
640private:
641    class DeathNotifier : public IBinder::DeathRecipient {
642    public:
643        DeathNotifier(AudioRecord* audioRecord) : mAudioRecord(audioRecord) { }
644    protected:
645        virtual void        binderDied(const wp<IBinder>& who);
646    private:
647        const wp<AudioRecord> mAudioRecord;
648    };
649
650    sp<DeathNotifier>       mDeathNotifier;
651    uint32_t                mSequence;              // incremented for each new IAudioRecord attempt
652    uid_t                   mClientUid;
653    pid_t                   mClientPid;
654    audio_attributes_t      mAttributes;
655
656    // For Device Selection API
657    //  a value of AUDIO_PORT_HANDLE_NONE indicated default (AudioPolicyManager) routing.
658    audio_port_handle_t    mSelectedDeviceId;
659    sp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
660    audio_port_handle_t    mPortId;  // unique ID allocated by audio policy
661
662};
663
664}; // namespace android
665
666#endif // ANDROID_AUDIORECORD_H
667