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