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