AudioRecord.h revision f0f33c4acd231fa95deb9eeef2c46b0129e64463
1/* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#ifndef ANDROID_AUDIORECORD_H 18#define ANDROID_AUDIORECORD_H 19 20#include <cutils/sched_policy.h> 21#include <media/AudioSystem.h> 22#include <media/IAudioRecord.h> 23#include <utils/threads.h> 24 25namespace android { 26 27// ---------------------------------------------------------------------------- 28 29class audio_track_cblk_t; 30class AudioRecordClientProxy; 31 32// ---------------------------------------------------------------------------- 33 34class AudioRecord : public RefBase 35{ 36public: 37 38 /* Events used by AudioRecord callback function (callback_t). 39 * Keep in sync with frameworks/base/media/java/android/media/AudioRecord.java NATIVE_EVENT_*. 40 */ 41 enum event_type { 42 EVENT_MORE_DATA = 0, // Request to read more data from PCM buffer. 43 EVENT_OVERRUN = 1, // PCM buffer overrun occurred. 44 EVENT_MARKER = 2, // Record head is at the specified marker position 45 // (See setMarkerPosition()). 46 EVENT_NEW_POS = 3, // Record head is at a new position 47 // (See setPositionUpdatePeriod()). 48 EVENT_NEW_IAUDIORECORD = 4, // IAudioRecord was re-created, either due to re-routing and 49 // voluntary invalidation by mediaserver, or mediaserver crash. 50 }; 51 52 /* Client should declare Buffer on the stack and pass address to obtainBuffer() 53 * and releaseBuffer(). See also callback_t for EVENT_MORE_DATA. 54 */ 55 56 class Buffer 57 { 58 public: 59 // FIXME use m prefix 60 size_t frameCount; // number of sample frames corresponding to size; 61 // on input it is the number of frames available, 62 // on output is the number of frames actually drained 63 64 size_t size; // input/output in bytes == frameCount * frameSize 65 // FIXME this is redundant with respect to frameCount, 66 // and TRANSFER_OBTAIN mode is broken for 8-bit data 67 // since we don't define the frame format 68 69 union { 70 void* raw; 71 short* i16; // signed 16-bit 72 int8_t* i8; // unsigned 8-bit, offset by 0x80 73 }; 74 }; 75 76 /* As a convenience, if a callback is supplied, a handler thread 77 * is automatically created with the appropriate priority. This thread 78 * invokes the callback when a new buffer becomes ready or various conditions occur. 79 * Parameters: 80 * 81 * event: type of event notified (see enum AudioRecord::event_type). 82 * user: Pointer to context for use by the callback receiver. 83 * info: Pointer to optional parameter according to event type: 84 * - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read 85 * more bytes than indicated by 'size' field and update 'size' if fewer bytes are 86 * consumed. 87 * - EVENT_OVERRUN: unused. 88 * - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames. 89 * - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames. 90 * - EVENT_NEW_IAUDIORECORD: unused. 91 */ 92 93 typedef void (*callback_t)(int event, void* user, void *info); 94 95 /* Returns the minimum frame count required for the successful creation of 96 * an AudioRecord object. 97 * Returned status (from utils/Errors.h) can be: 98 * - NO_ERROR: successful operation 99 * - NO_INIT: audio server or audio hardware not initialized 100 * - BAD_VALUE: unsupported configuration 101 */ 102 103 static status_t getMinFrameCount(size_t* frameCount, 104 uint32_t sampleRate, 105 audio_format_t format, 106 audio_channel_mask_t channelMask); 107 108 /* How data is transferred from AudioRecord 109 */ 110 enum transfer_type { 111 TRANSFER_DEFAULT, // not specified explicitly; determine from other parameters 112 TRANSFER_CALLBACK, // callback EVENT_MORE_DATA 113 TRANSFER_OBTAIN, // FIXME deprecated: call obtainBuffer() and releaseBuffer() 114 TRANSFER_SYNC, // synchronous read() 115 }; 116 117 /* Constructs an uninitialized AudioRecord. No connection with 118 * AudioFlinger takes place. Use set() after this. 119 */ 120 AudioRecord(); 121 122 /* Creates an AudioRecord object and registers it with AudioFlinger. 123 * Once created, the track needs to be started before it can be used. 124 * Unspecified values are set to appropriate default values. 125 * 126 * Parameters: 127 * 128 * inputSource: Select the audio input to record from (e.g. AUDIO_SOURCE_DEFAULT). 129 * sampleRate: Data sink sampling rate in Hz. 130 * format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed 131 * 16 bits per sample). 132 * channelMask: Channel mask, such that audio_is_input_channel(channelMask) is true. 133 * frameCount: Minimum size of track PCM buffer in frames. This defines the 134 * application's contribution to the 135 * latency of the track. The actual size selected by the AudioRecord could 136 * be larger if the requested size is not compatible with current audio HAL 137 * latency. Zero means to use a default value. 138 * cbf: Callback function. If not null, this function is called periodically 139 * to consume new PCM data and inform of marker, position updates, etc. 140 * user: Context for use by the callback receiver. 141 * notificationFrames: The callback function is called each time notificationFrames PCM 142 * frames are ready in record track output buffer. 143 * sessionId: Not yet supported. 144 * transferType: How data is transferred from AudioRecord. 145 * threadCanCallJava: Not present in parameter list, and so is fixed at false. 146 */ 147 148 AudioRecord(audio_source_t inputSource, 149 uint32_t sampleRate, 150 audio_format_t format, 151 audio_channel_mask_t channelMask, 152 int frameCount = 0, 153 callback_t cbf = NULL, 154 void* user = NULL, 155 int notificationFrames = 0, 156 int sessionId = 0, 157 transfer_type transferType = TRANSFER_DEFAULT); 158 159 /* Terminates the AudioRecord and unregisters it from AudioFlinger. 160 * Also destroys all resources associated with the AudioRecord. 161 */ 162protected: 163 virtual ~AudioRecord(); 164public: 165 166 /* Initialize an AudioRecord that was created using the AudioRecord() constructor. 167 * Don't call set() more than once, or after an AudioRecord() constructor that takes parameters. 168 * Returned status (from utils/Errors.h) can be: 169 * - NO_ERROR: successful intialization 170 * - INVALID_OPERATION: AudioRecord is already initialized or record device is already in use 171 * - BAD_VALUE: invalid parameter (channels, format, sampleRate...) 172 * - NO_INIT: audio server or audio hardware not initialized 173 * - PERMISSION_DENIED: recording is not allowed for the requesting process 174 * 175 * Parameters not listed in the AudioRecord constructors above: 176 * 177 * threadCanCallJava: Whether callbacks are made from an attached thread and thus can call JNI. 178 */ 179 status_t set(audio_source_t inputSource, 180 uint32_t sampleRate, 181 audio_format_t format, 182 audio_channel_mask_t channelMask, 183 int frameCount = 0, 184 callback_t cbf = NULL, 185 void* user = NULL, 186 int notificationFrames = 0, 187 bool threadCanCallJava = false, 188 int sessionId = 0, 189 transfer_type transferType = TRANSFER_DEFAULT); 190 191 /* Result of constructing the AudioRecord. This must be checked 192 * before using any AudioRecord API (except for set()), because using 193 * an uninitialized AudioRecord produces undefined results. 194 * See set() method above for possible return codes. 195 */ 196 status_t initCheck() const { return mStatus; } 197 198 /* Returns this track's estimated latency in milliseconds. 199 * This includes the latency due to AudioRecord buffer size, 200 * and audio hardware driver. 201 */ 202 uint32_t latency() const { return mLatency; } 203 204 /* getters, see constructor and set() */ 205 206 audio_format_t format() const { return mFormat; } 207 uint32_t channelCount() const { return mChannelCount; } 208 size_t frameCount() const { return mFrameCount; } 209 size_t frameSize() const { return mFrameSize; } 210 audio_source_t inputSource() const { return mInputSource; } 211 212 /* After it's created the track is not active. Call start() to 213 * make it active. If set, the callback will start being called. 214 * If event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until 215 * the specified event occurs on the specified trigger session. 216 */ 217 status_t start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE, 218 int triggerSession = 0); 219 220 /* Stop a track. If set, the callback will cease being called. Note that obtainBuffer() still 221 * works and will drain buffers until the pool is exhausted, and then will return WOULD_BLOCK. 222 */ 223 void stop(); 224 bool stopped() const; 225 226 /* Return the sink sample rate for this record track in Hz. 227 * Unlike AudioTrack, the sample rate is const after initialization, so doesn't need a lock. 228 */ 229 uint32_t getSampleRate() const { return mSampleRate; } 230 231 /* Sets marker position. When record reaches the number of frames specified, 232 * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition 233 * with marker == 0 cancels marker notification callback. 234 * To set a marker at a position which would compute as 0, 235 * a workaround is to the set the marker at a nearby position such as ~0 or 1. 236 * If the AudioRecord has been opened with no callback function associated, 237 * the operation will fail. 238 * 239 * Parameters: 240 * 241 * marker: marker position expressed in wrapping (overflow) frame units, 242 * like the return value of getPosition(). 243 * 244 * Returned status (from utils/Errors.h) can be: 245 * - NO_ERROR: successful operation 246 * - INVALID_OPERATION: the AudioRecord has no callback installed. 247 */ 248 status_t setMarkerPosition(uint32_t marker); 249 status_t getMarkerPosition(uint32_t *marker) const; 250 251 /* Sets position update period. Every time the number of frames specified has been recorded, 252 * a callback with event type EVENT_NEW_POS is called. 253 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 254 * callback. 255 * If the AudioRecord has been opened with no callback function associated, 256 * the operation will fail. 257 * Extremely small values may be rounded up to a value the implementation can support. 258 * 259 * Parameters: 260 * 261 * updatePeriod: position update notification period expressed in frames. 262 * 263 * Returned status (from utils/Errors.h) can be: 264 * - NO_ERROR: successful operation 265 * - INVALID_OPERATION: the AudioRecord has no callback installed. 266 */ 267 status_t setPositionUpdatePeriod(uint32_t updatePeriod); 268 status_t getPositionUpdatePeriod(uint32_t *updatePeriod) const; 269 270 /* Return the total number of frames recorded since recording started. 271 * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz. 272 * It is reset to zero by stop(). 273 * 274 * Parameters: 275 * 276 * position: Address where to return record head position. 277 * 278 * Returned status (from utils/Errors.h) can be: 279 * - NO_ERROR: successful operation 280 * - BAD_VALUE: position is NULL 281 */ 282 status_t getPosition(uint32_t *position) const; 283 284 /* Returns a handle on the audio input used by this AudioRecord. 285 * 286 * Parameters: 287 * none. 288 * 289 * Returned value: 290 * handle on audio hardware input 291 */ 292 audio_io_handle_t getInput() const; 293 294 /* Returns the audio session ID associated with this AudioRecord. 295 * 296 * Parameters: 297 * none. 298 * 299 * Returned value: 300 * AudioRecord session ID. 301 * 302 * No lock needed because session ID doesn't change after first set(). 303 */ 304 int getSessionId() const { return mSessionId; } 305 306 /* Obtains a buffer of up to "audioBuffer->frameCount" full frames. 307 * After draining these frames of data, the caller should release them with releaseBuffer(). 308 * If the track buffer is not empty, obtainBuffer() returns as many contiguous 309 * full frames as are available immediately. 310 * If the track buffer is empty and track is stopped, obtainBuffer() returns WOULD_BLOCK 311 * regardless of the value of waitCount. 312 * If the track buffer is empty and track is not stopped, obtainBuffer() blocks with a 313 * maximum timeout based on waitCount; see chart below. 314 * Buffers will be returned until the pool 315 * is exhausted, at which point obtainBuffer() will either block 316 * or return WOULD_BLOCK depending on the value of the "waitCount" 317 * parameter. 318 * 319 * obtainBuffer() and releaseBuffer() are deprecated for direct use by applications, 320 * which should use read() or callback EVENT_MORE_DATA instead. 321 * 322 * Interpretation of waitCount: 323 * +n limits wait time to n * WAIT_PERIOD_MS, 324 * -1 causes an (almost) infinite wait time, 325 * 0 non-blocking. 326 * 327 * Buffer fields 328 * On entry: 329 * frameCount number of frames requested 330 * After error return: 331 * frameCount 0 332 * size 0 333 * raw undefined 334 * After successful return: 335 * frameCount actual number of frames available, <= number requested 336 * size actual number of bytes available 337 * raw pointer to the buffer 338 */ 339 340 /* FIXME Deprecated public API for TRANSFER_OBTAIN mode */ 341 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount) 342 __attribute__((__deprecated__)); 343 344private: 345 /* New internal API. 346 * If nonContig is non-NULL, it is an output parameter that will be set to the number of 347 * additional non-contiguous frames that are available immediately. 348 * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(), 349 * in case the requested amount of frames is in two or more non-contiguous regions. 350 * FIXME requested and elapsed are both relative times. Consider changing to absolute time. 351 */ 352 status_t obtainBuffer(Buffer* audioBuffer, const struct timespec *requested, 353 struct timespec *elapsed = NULL, size_t *nonContig = NULL); 354public: 355 356 /* Release an emptied buffer of "audioBuffer->frameCount" frames for AudioFlinger to re-fill. */ 357 // FIXME make private when obtainBuffer() for TRANSFER_OBTAIN is removed 358 void releaseBuffer(Buffer* audioBuffer); 359 360 /* As a convenience we provide a read() interface to the audio buffer. 361 * Input parameter 'size' is in byte units. 362 * This is implemented on top of obtainBuffer/releaseBuffer. For best 363 * performance use callbacks. Returns actual number of bytes read >= 0, 364 * or a negative status code. 365 */ 366 ssize_t read(void* buffer, size_t size); 367 368 /* Return the number of input frames lost in the audio driver since the last call of this 369 * function. Audio driver is expected to reset the value to 0 and restart counting upon 370 * returning the current value by this function call. Such loss typically occurs when the 371 * user space process is blocked longer than the capacity of audio driver buffers. 372 * Units: the number of input audio frames. 373 */ 374 unsigned int getInputFramesLost() const; 375 376private: 377 /* copying audio record objects is not allowed */ 378 AudioRecord(const AudioRecord& other); 379 AudioRecord& operator = (const AudioRecord& other); 380 381 /* a small internal class to handle the callback */ 382 class AudioRecordThread : public Thread 383 { 384 public: 385 AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false); 386 387 // Do not call Thread::requestExitAndWait() without first calling requestExit(). 388 // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough. 389 virtual void requestExit(); 390 391 void pause(); // suspend thread from execution at next loop boundary 392 void resume(); // allow thread to execute, if not requested to exit 393 void pauseConditional(); 394 // like pause(), but only if prior resume() wasn't latched 395 396 private: 397 friend class AudioRecord; 398 virtual bool threadLoop(); 399 AudioRecord& mReceiver; 400 virtual ~AudioRecordThread(); 401 Mutex mMyLock; // Thread::mLock is private 402 Condition mMyCond; // Thread::mThreadExitedCondition is private 403 bool mPaused; // whether thread is currently paused 404 bool mResumeLatch; // whether next pauseConditional() will be a nop 405 }; 406 407 // body of AudioRecordThread::threadLoop() 408 // returns the maximum amount of time before we would like to run again, where: 409 // 0 immediately 410 // > 0 no later than this many nanoseconds from now 411 // NS_WHENEVER still active but no particular deadline 412 // NS_INACTIVE inactive so don't run again until re-started 413 // NS_NEVER never again 414 static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3; 415 nsecs_t processAudioBuffer(const sp<AudioRecordThread>& thread); 416 417 // caller must hold lock on mLock for all _l methods 418 status_t openRecord_l(uint32_t sampleRate, 419 audio_format_t format, 420 size_t frameCount, 421 audio_io_handle_t input, 422 size_t epoch); 423 424 audio_io_handle_t getInput_l(); 425 426 // FIXME enum is faster than strcmp() for parameter 'from' 427 status_t restoreRecord_l(const char *from); 428 429 sp<AudioRecordThread> mAudioRecordThread; 430 mutable Mutex mLock; 431 432 // Current client state: false = stopped, true = active. Protected by mLock. If more states 433 // are added, consider changing this to enum State { ... } mState as in AudioTrack. 434 bool mActive; 435 436 // for client callback handler 437 callback_t mCbf; // callback handler for events, or NULL 438 void* mUserData; // for client callback handler 439 440 // for notification APIs 441 uint32_t mNotificationFrames; // frames between each notification callback 442 bool mRefreshRemaining; // processAudioBuffer() should refresh next 2 443 444 // These are private to processAudioBuffer(), and are not protected by a lock 445 uint32_t mRemainingFrames; // number of frames to request in obtainBuffer() 446 bool mRetryOnPartialBuffer; // sleep and retry after partial obtainBuffer() 447 int mObservedSequence; // last observed value of mSequence 448 449 uint32_t mMarkerPosition; // in wrapping (overflow) frame units 450 bool mMarkerReached; 451 uint32_t mNewPosition; // in frames 452 uint32_t mUpdatePeriod; // in frames, zero means no EVENT_NEW_POS 453 454 status_t mStatus; 455 456 // constant after constructor or set() 457 uint32_t mSampleRate; 458 size_t mFrameCount; 459 audio_format_t mFormat; 460 uint32_t mChannelCount; 461 size_t mFrameSize; // app-level frame size == AudioFlinger frame size 462 audio_source_t mInputSource; 463 uint32_t mLatency; // in ms 464 audio_channel_mask_t mChannelMask; 465 int mSessionId; 466 transfer_type mTransfer; 467 468 audio_io_handle_t mInput; // returned by AudioSystem::getInput() 469 470 // may be changed if IAudioRecord object is re-created 471 sp<IAudioRecord> mAudioRecord; 472 sp<IMemory> mCblkMemory; 473 audio_track_cblk_t* mCblk; // re-load after mLock.unlock() 474 475 int mPreviousPriority; // before start() 476 SchedPolicy mPreviousSchedulingGroup; 477 478 // The proxy should only be referenced while a lock is held because the proxy isn't 479 // multi-thread safe. 480 // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock, 481 // provided that the caller also holds an extra reference to the proxy and shared memory to keep 482 sp<AudioRecordClientProxy> mProxy; 483 484 bool mInOverrun; // whether recorder is currently in overrun state 485 486private: 487 class DeathNotifier : public IBinder::DeathRecipient { 488 public: 489 DeathNotifier(AudioRecord* audioRecord) : mAudioRecord(audioRecord) { } 490 protected: 491 virtual void binderDied(const wp<IBinder>& who); 492 private: 493 const wp<AudioRecord> mAudioRecord; 494 }; 495 496 sp<DeathNotifier> mDeathNotifier; 497 uint32_t mSequence; // incremented for each new IAudioRecord attempt 498}; 499 500}; // namespace android 501 502#endif // ANDROID_AUDIORECORD_H 503