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