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