Home | History | Annotate | Download | only in media
      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 AudioSystem::AudioDeviceCallback
     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                                     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      */
    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                             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     /**
    338      * @param transferType
    339      * @return text string that matches the enum name
    340      */
    341     static const char * convertTransferToText(transfer_type transferType);
    342 
    343     /* Returns a handle on the audio input used by this AudioRecord.
    344      *
    345      * Parameters:
    346      *  none.
    347      *
    348      * Returned value:
    349      *  handle on audio hardware input
    350      */
    351 // FIXME The only known public caller is frameworks/opt/net/voip/src/jni/rtp/AudioGroup.cpp
    352             audio_io_handle_t    getInput() const __attribute__((__deprecated__))
    353                                                 { return getInputPrivate(); }
    354 private:
    355             audio_io_handle_t    getInputPrivate() const;
    356 public:
    357 
    358     /* Returns the audio session ID associated with this AudioRecord.
    359      *
    360      * Parameters:
    361      *  none.
    362      *
    363      * Returned value:
    364      *  AudioRecord session ID.
    365      *
    366      * No lock needed because session ID doesn't change after first set().
    367      */
    368             audio_session_t getSessionId() const { return mSessionId; }
    369 
    370     /* Public API for TRANSFER_OBTAIN mode.
    371      * Obtains a buffer of up to "audioBuffer->frameCount" full frames.
    372      * After draining these frames of data, the caller should release them with releaseBuffer().
    373      * If the track buffer is not empty, obtainBuffer() returns as many contiguous
    374      * full frames as are available immediately.
    375      *
    376      * If nonContig is non-NULL, it is an output parameter that will be set to the number of
    377      * additional non-contiguous frames that are predicted to be available immediately,
    378      * if the client were to release the first frames and then call obtainBuffer() again.
    379      * This value is only a prediction, and needs to be confirmed.
    380      * It will be set to zero for an error return.
    381      *
    382      * If the track buffer is empty and track is stopped, obtainBuffer() returns WOULD_BLOCK
    383      * regardless of the value of waitCount.
    384      * If the track buffer is empty and track is not stopped, obtainBuffer() blocks with a
    385      * maximum timeout based on waitCount; see chart below.
    386      * Buffers will be returned until the pool
    387      * is exhausted, at which point obtainBuffer() will either block
    388      * or return WOULD_BLOCK depending on the value of the "waitCount"
    389      * parameter.
    390      *
    391      * Interpretation of waitCount:
    392      *  +n  limits wait time to n * WAIT_PERIOD_MS,
    393      *  -1  causes an (almost) infinite wait time,
    394      *   0  non-blocking.
    395      *
    396      * Buffer fields
    397      * On entry:
    398      *  frameCount  number of frames requested
    399      *  size        ignored
    400      *  raw         ignored
    401      * After error return:
    402      *  frameCount  0
    403      *  size        0
    404      *  raw         undefined
    405      * After successful return:
    406      *  frameCount  actual number of frames available, <= number requested
    407      *  size        actual number of bytes available
    408      *  raw         pointer to the buffer
    409      */
    410 
    411             status_t    obtainBuffer(Buffer* audioBuffer, int32_t waitCount,
    412                                 size_t *nonContig = NULL);
    413 
    414             // Explicit Routing
    415     /**
    416      * TODO Document this method.
    417      */
    418             status_t setInputDevice(audio_port_handle_t deviceId);
    419 
    420     /**
    421      * TODO Document this method.
    422      */
    423             audio_port_handle_t getInputDevice();
    424 
    425      /* Returns the ID of the audio device actually used by the input to which this AudioRecord
    426       * is attached.
    427       * The device ID is relevant only if the AudioRecord is active.
    428       * When the AudioRecord is inactive, the device ID returned can be either:
    429       * - AUDIO_PORT_HANDLE_NONE if the AudioRecord is not attached to any output.
    430       * - The device ID used before paused or stopped.
    431       * - The device ID selected by audio policy manager of setOutputDevice() if the AudioRecord
    432       * has not been started yet.
    433       *
    434       * Parameters:
    435       *  none.
    436       */
    437      audio_port_handle_t getRoutedDeviceId();
    438 
    439     /* Add an AudioDeviceCallback. The caller will be notified when the audio device
    440      * to which this AudioRecord is routed is updated.
    441      * Replaces any previously installed callback.
    442      * Parameters:
    443      *  callback:  The callback interface
    444      * Returns NO_ERROR if successful.
    445      *         INVALID_OPERATION if the same callback is already installed.
    446      *         NO_INIT or PREMISSION_DENIED if AudioFlinger service is not reachable
    447      *         BAD_VALUE if the callback is NULL
    448      */
    449             status_t addAudioDeviceCallback(
    450                     const sp<AudioSystem::AudioDeviceCallback>& callback);
    451 
    452     /* remove an AudioDeviceCallback.
    453      * Parameters:
    454      *  callback:  The callback interface
    455      * Returns NO_ERROR if successful.
    456      *         INVALID_OPERATION if the callback is not installed
    457      *         BAD_VALUE if the callback is NULL
    458      */
    459             status_t removeAudioDeviceCallback(
    460                     const sp<AudioSystem::AudioDeviceCallback>& callback);
    461 
    462             // AudioSystem::AudioDeviceCallback> virtuals
    463             virtual void onAudioDeviceUpdate(audio_io_handle_t audioIo,
    464                                              audio_port_handle_t deviceId);
    465 
    466 private:
    467     /* If nonContig is non-NULL, it is an output parameter that will be set to the number of
    468      * additional non-contiguous frames that are predicted to be available immediately,
    469      * if the client were to release the first frames and then call obtainBuffer() again.
    470      * This value is only a prediction, and needs to be confirmed.
    471      * It will be set to zero for an error return.
    472      * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(),
    473      * in case the requested amount of frames is in two or more non-contiguous regions.
    474      * FIXME requested and elapsed are both relative times.  Consider changing to absolute time.
    475      */
    476             status_t    obtainBuffer(Buffer* audioBuffer, const struct timespec *requested,
    477                                      struct timespec *elapsed = NULL, size_t *nonContig = NULL);
    478 public:
    479 
    480     /* Public API for TRANSFER_OBTAIN mode.
    481      * Release an emptied buffer of "audioBuffer->frameCount" frames for AudioFlinger to re-fill.
    482      *
    483      * Buffer fields:
    484      *  frameCount  currently ignored but recommend to set to actual number of frames consumed
    485      *  size        actual number of bytes consumed, must be multiple of frameSize
    486      *  raw         ignored
    487      */
    488             void        releaseBuffer(const Buffer* audioBuffer);
    489 
    490     /* As a convenience we provide a read() interface to the audio buffer.
    491      * Input parameter 'size' is in byte units.
    492      * This is implemented on top of obtainBuffer/releaseBuffer. For best
    493      * performance use callbacks. Returns actual number of bytes read >= 0,
    494      * or one of the following negative status codes:
    495      *      INVALID_OPERATION   AudioRecord is configured for streaming mode
    496      *      BAD_VALUE           size is invalid
    497      *      WOULD_BLOCK         when obtainBuffer() returns same, or
    498      *                          AudioRecord was stopped during the read
    499      *      or any other error code returned by IAudioRecord::start() or restoreRecord_l().
    500      * Default behavior is to only return when all data has been transferred. Set 'blocking' to
    501      * false for the method to return immediately without waiting to try multiple times to read
    502      * the full content of the buffer.
    503      */
    504             ssize_t     read(void* buffer, size_t size, bool blocking = true);
    505 
    506     /* Return the number of input frames lost in the audio driver since the last call of this
    507      * function.  Audio driver is expected to reset the value to 0 and restart counting upon
    508      * returning the current value by this function call.  Such loss typically occurs when the
    509      * user space process is blocked longer than the capacity of audio driver buffers.
    510      * Units: the number of input audio frames.
    511      * FIXME The side-effect of resetting the counter may be incompatible with multi-client.
    512      * Consider making it more like AudioTrack::getUnderrunFrames which doesn't have side effects.
    513      */
    514             uint32_t    getInputFramesLost() const;
    515 
    516     /* Get the flags */
    517             audio_input_flags_t getFlags() const { AutoMutex _l(mLock); return mFlags; }
    518 
    519 private:
    520     /* copying audio record objects is not allowed */
    521                         AudioRecord(const AudioRecord& other);
    522             AudioRecord& operator = (const AudioRecord& other);
    523 
    524     /* a small internal class to handle the callback */
    525     class AudioRecordThread : public Thread
    526     {
    527     public:
    528         AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false);
    529 
    530         // Do not call Thread::requestExitAndWait() without first calling requestExit().
    531         // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough.
    532         virtual void        requestExit();
    533 
    534                 void        pause();    // suspend thread from execution at next loop boundary
    535                 void        resume();   // allow thread to execute, if not requested to exit
    536                 void        wake();     // wake to handle changed notification conditions.
    537 
    538     private:
    539                 void        pauseInternal(nsecs_t ns = 0LL);
    540                                         // like pause(), but only used internally within thread
    541 
    542         friend class AudioRecord;
    543         virtual bool        threadLoop();
    544         AudioRecord&        mReceiver;
    545         virtual ~AudioRecordThread();
    546         Mutex               mMyLock;    // Thread::mLock is private
    547         Condition           mMyCond;    // Thread::mThreadExitedCondition is private
    548         bool                mPaused;    // whether thread is requested to pause at next loop entry
    549         bool                mPausedInt; // whether thread internally requests pause
    550         nsecs_t             mPausedNs;  // if mPausedInt then associated timeout, otherwise ignored
    551         bool                mIgnoreNextPausedInt;   // skip any internal pause and go immediately
    552                                         // to processAudioBuffer() as state may have changed
    553                                         // since pause time calculated.
    554     };
    555 
    556             // body of AudioRecordThread::threadLoop()
    557             // returns the maximum amount of time before we would like to run again, where:
    558             //      0           immediately
    559             //      > 0         no later than this many nanoseconds from now
    560             //      NS_WHENEVER still active but no particular deadline
    561             //      NS_INACTIVE inactive so don't run again until re-started
    562             //      NS_NEVER    never again
    563             static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3;
    564             nsecs_t processAudioBuffer();
    565 
    566             // caller must hold lock on mLock for all _l methods
    567 
    568             status_t openRecord_l(const Modulo<uint32_t> &epoch, const String16& opPackageName);
    569 
    570             // FIXME enum is faster than strcmp() for parameter 'from'
    571             status_t restoreRecord_l(const char *from);
    572 
    573             void     updateRoutedDeviceId_l();
    574 
    575     sp<AudioRecordThread>   mAudioRecordThread;
    576     mutable Mutex           mLock;
    577 
    578     // Current client state:  false = stopped, true = active.  Protected by mLock.  If more states
    579     // are added, consider changing this to enum State { ... } mState as in AudioTrack.
    580     bool                    mActive;
    581 
    582     // for client callback handler
    583     callback_t              mCbf;                   // callback handler for events, or NULL
    584     void*                   mUserData;
    585 
    586     // for notification APIs
    587     uint32_t                mNotificationFramesReq; // requested number of frames between each
    588                                                     // notification callback
    589                                                     // as specified in constructor or set()
    590     uint32_t                mNotificationFramesAct; // actual number of frames between each
    591                                                     // notification callback
    592     bool                    mRefreshRemaining;      // processAudioBuffer() should refresh
    593                                                     // mRemainingFrames and mRetryOnPartialBuffer
    594 
    595     // These are private to processAudioBuffer(), and are not protected by a lock
    596     uint32_t                mRemainingFrames;       // number of frames to request in obtainBuffer()
    597     bool                    mRetryOnPartialBuffer;  // sleep and retry after partial obtainBuffer()
    598     uint32_t                mObservedSequence;      // last observed value of mSequence
    599 
    600     Modulo<uint32_t>        mMarkerPosition;        // in wrapping (overflow) frame units
    601     bool                    mMarkerReached;
    602     Modulo<uint32_t>        mNewPosition;           // in frames
    603     uint32_t                mUpdatePeriod;          // in frames, zero means no EVENT_NEW_POS
    604 
    605     status_t                mStatus;
    606 
    607     String16                mOpPackageName;         // The package name used for app ops.
    608 
    609     size_t                  mFrameCount;            // corresponds to current IAudioRecord, value is
    610                                                     // reported back by AudioFlinger to the client
    611     size_t                  mReqFrameCount;         // frame count to request the first or next time
    612                                                     // a new IAudioRecord is needed, non-decreasing
    613 
    614     int64_t                 mFramesRead;            // total frames read. reset to zero after
    615                                                     // the start() following stop(). It is not
    616                                                     // changed after restoring the track.
    617     int64_t                 mFramesReadServerOffset; // An offset to server frames read due to
    618                                                     // restoring AudioRecord, or stop/start.
    619     // constant after constructor or set()
    620     uint32_t                mSampleRate;
    621     audio_format_t          mFormat;
    622     uint32_t                mChannelCount;
    623     size_t                  mFrameSize;         // app-level frame size == AudioFlinger frame size
    624     uint32_t                mLatency;           // in ms
    625     audio_channel_mask_t    mChannelMask;
    626 
    627     audio_input_flags_t     mFlags;                 // same as mOrigFlags, except for bits that may
    628                                                     // be denied by client or server, such as
    629                                                     // AUDIO_INPUT_FLAG_FAST.  mLock must be
    630                                                     // held to read or write those bits reliably.
    631     audio_input_flags_t     mOrigFlags;             // as specified in constructor or set(), const
    632 
    633     audio_session_t         mSessionId;
    634     transfer_type           mTransfer;
    635 
    636     // Next 5 fields may be changed if IAudioRecord is re-created, but always != 0
    637     // provided the initial set() was successful
    638     sp<IAudioRecord>        mAudioRecord;
    639     sp<IMemory>             mCblkMemory;
    640     audio_track_cblk_t*     mCblk;              // re-load after mLock.unlock()
    641     sp<IMemory>             mBufferMemory;
    642     audio_io_handle_t       mInput;             // returned by AudioSystem::getInput()
    643 
    644     int                     mPreviousPriority;  // before start()
    645     SchedPolicy             mPreviousSchedulingGroup;
    646     bool                    mAwaitBoost;    // thread should wait for priority boost before running
    647 
    648     // The proxy should only be referenced while a lock is held because the proxy isn't
    649     // multi-thread safe.
    650     // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock,
    651     // provided that the caller also holds an extra reference to the proxy and shared memory to keep
    652     // them around in case they are replaced during the obtainBuffer().
    653     sp<AudioRecordClientProxy> mProxy;
    654 
    655     bool                    mInOverrun;         // whether recorder is currently in overrun state
    656 
    657 private:
    658     class DeathNotifier : public IBinder::DeathRecipient {
    659     public:
    660         DeathNotifier(AudioRecord* audioRecord) : mAudioRecord(audioRecord) { }
    661     protected:
    662         virtual void        binderDied(const wp<IBinder>& who);
    663     private:
    664         const wp<AudioRecord> mAudioRecord;
    665     };
    666 
    667     sp<DeathNotifier>       mDeathNotifier;
    668     uint32_t                mSequence;              // incremented for each new IAudioRecord attempt
    669     uid_t                   mClientUid;
    670     pid_t                   mClientPid;
    671     audio_attributes_t      mAttributes;
    672 
    673     // For Device Selection API
    674     //  a value of AUDIO_PORT_HANDLE_NONE indicated default (AudioPolicyManager) routing.
    675     audio_port_handle_t     mSelectedDeviceId; // Device requested by the application.
    676     audio_port_handle_t     mRoutedDeviceId;   // Device actually selected by audio policy manager:
    677                                               // May not match the app selection depending on other
    678                                               // activity and connected devices
    679     wp<AudioSystem::AudioDeviceCallback> mDeviceCallback;
    680     audio_port_handle_t    mPortId;  // unique ID allocated by audio policy
    681 
    682 };
    683 
    684 }; // namespace android
    685 
    686 #endif // ANDROID_AUDIORECORD_H
    687