AudioRecord.h revision c28c03b0b819d705522929852ecdb5a8bb50b13b
170de1e442d30eceea6d71ef5403f06323eda7e55Craig Topper/* 2d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * Copyright (C) 2008 The Android Open Source Project 3d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * 4d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * Licensed under the Apache License, Version 2.0 (the "License"); 5d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * you may not use this file except in compliance with the License. 6d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * You may obtain a copy of the License at 7d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * 8d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * http://www.apache.org/licenses/LICENSE-2.0 9d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * 10d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * Unless required by applicable law or agreed to in writing, software 11d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * distributed under the License is distributed on an "AS IS" BASIS, 12d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * See the License for the specific language governing permissions and 14d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum * limitations under the License. 15d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum */ 16d239ff67f210094c205be7e57332948caecf6a24Tony Linthicum 17#ifndef AUDIORECORD_H_ 18#define AUDIORECORD_H_ 19 20#include <binder/IMemory.h> 21#include <cutils/sched_policy.h> 22#include <media/AudioSystem.h> 23#include <media/IAudioRecord.h> 24#include <system/audio.h> 25#include <utils/RefBase.h> 26#include <utils/Errors.h> 27#include <utils/threads.h> 28 29namespace android { 30 31class audio_track_cblk_t; 32 33// ---------------------------------------------------------------------------- 34 35class AudioRecord : virtual public RefBase 36{ 37public: 38 39 static const int DEFAULT_SAMPLE_RATE = 8000; 40 41 /* Events used by AudioRecord callback function (callback_t). 42 * Keep in sync with frameworks/base/media/java/android/media/AudioRecord.java NATIVE_EVENT_*. 43 */ 44 enum event_type { 45 EVENT_MORE_DATA = 0, // Request to read more data from PCM buffer. 46 EVENT_OVERRUN = 1, // PCM buffer overrun occurred. 47 EVENT_MARKER = 2, // Record head is at the specified marker position 48 // (See setMarkerPosition()). 49 EVENT_NEW_POS = 3, // Record head is at a new position 50 // (See setPositionUpdatePeriod()). 51 }; 52 53 /* Client should declare Buffer on the stack and pass address to obtainBuffer() 54 * and releaseBuffer(). See also callback_t for EVENT_MORE_DATA. 55 */ 56 57 class Buffer 58 { 59 public: 60 enum { 61 MUTE = 0x00000001 62 }; 63 uint32_t flags; 64 int channelCount; 65 audio_format_t format; 66 67 size_t frameCount; // number of sample frames corresponding to size; 68 // on input it is the number of frames available, 69 // on output is the number of frames actually drained 70 71 size_t size; // total size in bytes == frameCount * frameSize 72 union { 73 void* raw; 74 short* i16; // signed 16-bit 75 int8_t* i8; // unsigned 8-bit, offset by 0x80 76 }; 77 }; 78 79 /* As a convenience, if a callback is supplied, a handler thread 80 * is automatically created with the appropriate priority. This thread 81 * invokes the callback when a new buffer becomes ready or various conditions occur. 82 * Parameters: 83 * 84 * event: type of event notified (see enum AudioRecord::event_type). 85 * user: Pointer to context for use by the callback receiver. 86 * info: Pointer to optional parameter according to event type: 87 * - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read 88 * more bytes than indicated by 'size' field and update 'size' if fewer bytes are 89 * consumed. 90 * - EVENT_OVERRUN: unused. 91 * - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames. 92 * - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames. 93 */ 94 95 typedef void (*callback_t)(int event, void* user, void *info); 96 97 /* Returns the minimum frame count required for the successful creation of 98 * an AudioRecord object. 99 * Returned status (from utils/Errors.h) can be: 100 * - NO_ERROR: successful operation 101 * - NO_INIT: audio server or audio hardware not initialized 102 * - BAD_VALUE: unsupported configuration 103 */ 104 105 static status_t getMinFrameCount(int* frameCount, 106 uint32_t sampleRate, 107 audio_format_t format, 108 audio_channel_mask_t channelMask); 109 110 /* Constructs an uninitialized AudioRecord. No connection with 111 * AudioFlinger takes place. 112 */ 113 AudioRecord(); 114 115 /* Creates an AudioRecord object and registers it with AudioFlinger. 116 * Once created, the track needs to be started before it can be used. 117 * Unspecified values are set to the audio hardware's current 118 * values. 119 * 120 * Parameters: 121 * 122 * inputSource: Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT). 123 * sampleRate: Track sampling rate in Hz. 124 * format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed 125 * 16 bits per sample). 126 * channelMask: Channel mask. 127 * frameCount: Minimum size of track PCM buffer in frames. This defines the 128 * application's contribution to the 129 * latency of the track. The actual size selected by the AudioRecord could 130 * be larger if the requested size is not compatible with current audio HAL 131 * latency. Zero means to use a default value. 132 * cbf: Callback function. If not null, this function is called periodically 133 * to consume new PCM data. 134 * user: Context for use by the callback receiver. 135 * notificationFrames: The callback function is called each time notificationFrames PCM 136 * frames are ready in record track output buffer. 137 * sessionId: Not yet supported. 138 */ 139 140 AudioRecord(audio_source_t inputSource, 141 uint32_t sampleRate = 0, 142 audio_format_t format = AUDIO_FORMAT_DEFAULT, 143 audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO, 144 int frameCount = 0, 145 callback_t cbf = NULL, 146 void* user = NULL, 147 int notificationFrames = 0, 148 int sessionId = 0); 149 150 151 /* Terminates the AudioRecord and unregisters it from AudioFlinger. 152 * Also destroys all resources associated with the AudioRecord. 153 */ 154 ~AudioRecord(); 155 156 157 /* Initialize an uninitialized AudioRecord. 158 * Returned status (from utils/Errors.h) can be: 159 * - NO_ERROR: successful intialization 160 * - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use 161 * - BAD_VALUE: invalid parameter (channels, format, sampleRate...) 162 * - NO_INIT: audio server or audio hardware not initialized 163 * - PERMISSION_DENIED: recording is not allowed for the requesting process 164 */ 165 status_t set(audio_source_t inputSource = AUDIO_SOURCE_DEFAULT, 166 uint32_t sampleRate = 0, 167 audio_format_t format = AUDIO_FORMAT_DEFAULT, 168 audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO, 169 int frameCount = 0, 170 callback_t cbf = NULL, 171 void* user = NULL, 172 int notificationFrames = 0, 173 bool threadCanCallJava = false, 174 int sessionId = 0); 175 176 177 /* Result of constructing the AudioRecord. This must be checked 178 * before using any AudioRecord API (except for set()), because using 179 * an uninitialized AudioRecord produces undefined results. 180 * See set() method above for possible return codes. 181 */ 182 status_t initCheck() const; 183 184 /* Returns this track's estimated latency in milliseconds. 185 * This includes the latency due to AudioRecord buffer size, 186 * and audio hardware driver. 187 */ 188 uint32_t latency() const; 189 190 /* getters, see constructor and set() */ 191 192 audio_format_t format() const; 193 int channelCount() const; 194 uint32_t frameCount() const; 195 size_t frameSize() const; 196 audio_source_t inputSource() const; 197 198 199 /* After it's created the track is not active. Call start() to 200 * make it active. If set, the callback will start being called. 201 * If event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until 202 * the specified event occurs on the specified trigger session. 203 */ 204 status_t start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE, 205 int triggerSession = 0); 206 207 /* Stop a track. If set, the callback will cease being called and 208 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works 209 * and will drain buffers until the pool is exhausted. 210 */ 211 void stop(); 212 bool stopped() const; 213 214 /* Get sample rate for this record track in Hz. 215 */ 216 uint32_t getSampleRate() const; 217 218 /* Sets marker position. When record reaches the number of frames specified, 219 * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition 220 * with marker == 0 cancels marker notification callback. 221 * If the AudioRecord has been opened with no callback function associated, 222 * the operation will fail. 223 * 224 * Parameters: 225 * 226 * marker: marker position expressed in frames. 227 * 228 * Returned status (from utils/Errors.h) can be: 229 * - NO_ERROR: successful operation 230 * - INVALID_OPERATION: the AudioRecord has no callback installed. 231 */ 232 status_t setMarkerPosition(uint32_t marker); 233 status_t getMarkerPosition(uint32_t *marker) const; 234 235 236 /* Sets position update period. Every time the number of frames specified has been recorded, 237 * a callback with event type EVENT_NEW_POS is called. 238 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 239 * callback. 240 * If the AudioRecord has been opened with no callback function associated, 241 * the operation will fail. 242 * 243 * Parameters: 244 * 245 * updatePeriod: position update notification period expressed in frames. 246 * 247 * Returned status (from utils/Errors.h) can be: 248 * - NO_ERROR: successful operation 249 * - INVALID_OPERATION: the AudioRecord has no callback installed. 250 */ 251 status_t setPositionUpdatePeriod(uint32_t updatePeriod); 252 status_t getPositionUpdatePeriod(uint32_t *updatePeriod) const; 253 254 255 /* Gets record head position. The position is the total number of frames 256 * recorded since record start. 257 * 258 * Parameters: 259 * 260 * position: Address where to return record head position within AudioRecord buffer. 261 * 262 * Returned status (from utils/Errors.h) can be: 263 * - NO_ERROR: successful operation 264 * - BAD_VALUE: position is NULL 265 */ 266 status_t getPosition(uint32_t *position) const; 267 268 /* Returns a handle on the audio input used by this AudioRecord. 269 * 270 * Parameters: 271 * none. 272 * 273 * Returned value: 274 * handle on audio hardware input 275 */ 276 audio_io_handle_t getInput() const; 277 278 /* Returns the audio session ID associated with this AudioRecord. 279 * 280 * Parameters: 281 * none. 282 * 283 * Returned value: 284 * AudioRecord session ID. 285 */ 286 int getSessionId() const; 287 288 /* Obtains a buffer of "frameCount" frames. The buffer must be 289 * drained entirely, and then released with releaseBuffer(). 290 * If the track is stopped, obtainBuffer() returns 291 * STOPPED instead of NO_ERROR as long as there are buffers available, 292 * at which point NO_MORE_BUFFERS is returned. 293 * Buffers will be returned until the pool 294 * is exhausted, at which point obtainBuffer() will either block 295 * or return WOULD_BLOCK depending on the value of the "blocking" 296 * parameter. 297 * 298 * Interpretation of waitCount: 299 * +n limits wait time to n * WAIT_PERIOD_MS, 300 * -1 causes an (almost) infinite wait time, 301 * 0 non-blocking. 302 */ 303 304 enum { 305 NO_MORE_BUFFERS = 0x80000001, // same name in AudioFlinger.h, ok to be different value 306 STOPPED = 1 307 }; 308 309 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount); 310 311 /* Release an emptied buffer of "frameCount" frames for AudioFlinger to re-fill. */ 312 void releaseBuffer(Buffer* audioBuffer); 313 314 315 /* As a convenience we provide a read() interface to the audio buffer. 316 * This is implemented on top of obtainBuffer/releaseBuffer. 317 */ 318 ssize_t read(void* buffer, size_t size); 319 320 /* Return the number of input frames lost in the audio driver since the last call of this 321 * function. Audio driver is expected to reset the value to 0 and restart counting upon 322 * returning the current value by this function call. Such loss typically occurs when the 323 * user space process is blocked longer than the capacity of audio driver buffers. 324 * Units: the number of input audio frames. 325 */ 326 unsigned int getInputFramesLost() const; 327 328private: 329 /* copying audio record objects is not allowed */ 330 AudioRecord(const AudioRecord& other); 331 AudioRecord& operator = (const AudioRecord& other); 332 333 /* a small internal class to handle the callback */ 334 class AudioRecordThread : public Thread 335 { 336 public: 337 AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false); 338 339 // Do not call Thread::requestExitAndWait() without first calling requestExit(). 340 // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough. 341 virtual void requestExit(); 342 343 void pause(); // suspend thread from execution at next loop boundary 344 void resume(); // allow thread to execute, if not requested to exit 345 346 private: 347 friend class AudioRecord; 348 virtual bool threadLoop(); 349 AudioRecord& mReceiver; 350 virtual ~AudioRecordThread(); 351 Mutex mMyLock; // Thread::mLock is private 352 Condition mMyCond; // Thread::mThreadExitedCondition is private 353 bool mPaused; // whether thread is currently paused 354 }; 355 356 // body of AudioRecordThread::threadLoop() 357 bool processAudioBuffer(const sp<AudioRecordThread>& thread); 358 359 status_t openRecord_l(uint32_t sampleRate, 360 audio_format_t format, 361 audio_channel_mask_t channelMask, 362 int frameCount, 363 audio_io_handle_t input); 364 audio_io_handle_t getInput_l(); 365 status_t restoreRecord_l(audio_track_cblk_t*& cblk); 366 367 sp<AudioRecordThread> mAudioRecordThread; 368 mutable Mutex mLock; 369 370 bool mActive; // protected by mLock 371 372 // for client callback handler 373 callback_t mCbf; // callback handler for events, or NULL 374 void* mUserData; 375 376 // for notification APIs 377 uint32_t mNotificationFrames; 378 uint32_t mRemainingFrames; 379 uint32_t mMarkerPosition; // in frames 380 bool mMarkerReached; 381 uint32_t mNewPosition; // in frames 382 uint32_t mUpdatePeriod; // in ms 383 384 // constant after constructor or set() 385 uint32_t mFrameCount; 386 audio_format_t mFormat; 387 uint8_t mChannelCount; 388 audio_source_t mInputSource; 389 status_t mStatus; 390 uint32_t mLatency; 391 audio_channel_mask_t mChannelMask; 392 audio_io_handle_t mInput; // returned by AudioSystem::getInput() 393 int mSessionId; 394 395 // may be changed if IAudioRecord object is re-created 396 sp<IAudioRecord> mAudioRecord; 397 sp<IMemory> mCblkMemory; 398 audio_track_cblk_t* mCblk; 399 400 int mPreviousPriority; // before start() 401 SchedPolicy mPreviousSchedulingGroup; 402}; 403 404}; // namespace android 405 406#endif /*AUDIORECORD_H_*/ 407