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 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 29 namespace android { 30 31 class audio_track_cblk_t; 32 33 // ---------------------------------------------------------------------------- 34 35 class AudioRecord : virtual public RefBase 36 { 37 public: 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 occured. 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 /* Create Buffer on the stack and pass it to obtainBuffer() 54 * and releaseBuffer(). 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 size_t frameCount; 67 size_t size; // total size in bytes == frameCount * frameSize 68 union { 69 void* raw; 70 short* i16; 71 int8_t* i8; 72 }; 73 }; 74 75 /* As a convenience, if a callback is supplied, a handler thread 76 * is automatically created with the appropriate priority. This thread 77 * invokes the callback when a new buffer becomes ready or an overrun condition occurs. 78 * Parameters: 79 * 80 * event: type of event notified (see enum AudioRecord::event_type). 81 * user: Pointer to context for use by the callback receiver. 82 * info: Pointer to optional parameter according to event type: 83 * - EVENT_MORE_DATA: pointer to AudioRecord::Buffer struct. The callback must not read 84 * more bytes than indicated by 'size' field and update 'size' if less bytes are 85 * read. 86 * - EVENT_OVERRUN: unused. 87 * - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames. 88 * - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames. 89 */ 90 91 typedef void (*callback_t)(int event, void* user, void *info); 92 93 /* Returns the minimum frame count required for the successful creation of 94 * an AudioRecord object. 95 * Returned status (from utils/Errors.h) can be: 96 * - NO_ERROR: successful operation 97 * - NO_INIT: audio server or audio hardware not initialized 98 * - BAD_VALUE: unsupported configuration 99 */ 100 101 static status_t getMinFrameCount(int* frameCount, 102 uint32_t sampleRate, 103 audio_format_t format, 104 audio_channel_mask_t channelMask); 105 106 /* Constructs an uninitialized AudioRecord. No connection with 107 * AudioFlinger takes place. 108 */ 109 AudioRecord(); 110 111 /* Creates an AudioRecord track and registers it with AudioFlinger. 112 * Once created, the track needs to be started before it can be used. 113 * Unspecified values are set to the audio hardware's current 114 * values. 115 * 116 * Parameters: 117 * 118 * inputSource: Select the audio input to record to (e.g. AUDIO_SOURCE_DEFAULT). 119 * sampleRate: Track sampling rate in Hz. 120 * format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed 121 * 16 bits per sample). 122 * channelMask: Channel mask. 123 * frameCount: Total size of track PCM buffer in frames. This defines the 124 * latency of the track. 125 * cbf: Callback function. If not null, this function is called periodically 126 * to provide new PCM data. 127 * user: Context for use by the callback receiver. 128 * notificationFrames: The callback function is called each time notificationFrames PCM 129 * frames are ready in record track output buffer. 130 * sessionId: Not yet supported. 131 */ 132 133 AudioRecord(audio_source_t inputSource, 134 uint32_t sampleRate = 0, 135 audio_format_t format = AUDIO_FORMAT_DEFAULT, 136 audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO, 137 int frameCount = 0, 138 callback_t cbf = NULL, 139 void* user = NULL, 140 int notificationFrames = 0, 141 int sessionId = 0); 142 143 144 /* Terminates the AudioRecord and unregisters it from AudioFlinger. 145 * Also destroys all resources associated with the AudioRecord. 146 */ 147 ~AudioRecord(); 148 149 150 /* Initialize an uninitialized AudioRecord. 151 * Returned status (from utils/Errors.h) can be: 152 * - NO_ERROR: successful intialization 153 * - INVALID_OPERATION: AudioRecord is already intitialized or record device is already in use 154 * - BAD_VALUE: invalid parameter (channels, format, sampleRate...) 155 * - NO_INIT: audio server or audio hardware not initialized 156 * - PERMISSION_DENIED: recording is not allowed for the requesting process 157 * */ 158 status_t set(audio_source_t inputSource = AUDIO_SOURCE_DEFAULT, 159 uint32_t sampleRate = 0, 160 audio_format_t format = AUDIO_FORMAT_DEFAULT, 161 audio_channel_mask_t channelMask = AUDIO_CHANNEL_IN_MONO, 162 int frameCount = 0, 163 callback_t cbf = NULL, 164 void* user = NULL, 165 int notificationFrames = 0, 166 bool threadCanCallJava = false, 167 int sessionId = 0); 168 169 170 /* Result of constructing the AudioRecord. This must be checked 171 * before using any AudioRecord API (except for set()), using 172 * an uninitialized AudioRecord produces undefined results. 173 * See set() method above for possible return codes. 174 */ 175 status_t initCheck() const; 176 177 /* Returns this track's latency in milliseconds. 178 * This includes the latency due to AudioRecord buffer size 179 * and audio hardware driver. 180 */ 181 uint32_t latency() const; 182 183 /* getters, see constructor and set() */ 184 185 audio_format_t format() const; 186 int channelCount() const; 187 uint32_t frameCount() const; 188 size_t frameSize() const; 189 audio_source_t inputSource() const; 190 191 192 /* After it's created the track is not active. Call start() to 193 * make it active. If set, the callback will start being called. 194 * if event is not AudioSystem::SYNC_EVENT_NONE, the capture start will be delayed until 195 * the specified event occurs on the specified trigger session. 196 */ 197 status_t start(AudioSystem::sync_event_t event = AudioSystem::SYNC_EVENT_NONE, 198 int triggerSession = 0); 199 200 /* Stop a track. If set, the callback will cease being called and 201 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works 202 * and will fill up buffers until the pool is exhausted. 203 */ 204 void stop(); 205 bool stopped() const; 206 207 /* get sample rate for this record track 208 */ 209 uint32_t getSampleRate() const; 210 211 /* Sets marker position. When record reaches the number of frames specified, 212 * a callback with event type EVENT_MARKER is called. Calling setMarkerPosition 213 * with marker == 0 cancels marker notification callback. 214 * If the AudioRecord has been opened with no callback function associated, 215 * the operation will fail. 216 * 217 * Parameters: 218 * 219 * marker: marker position expressed in frames. 220 * 221 * Returned status (from utils/Errors.h) can be: 222 * - NO_ERROR: successful operation 223 * - INVALID_OPERATION: the AudioRecord has no callback installed. 224 */ 225 status_t setMarkerPosition(uint32_t marker); 226 status_t getMarkerPosition(uint32_t *marker) const; 227 228 229 /* Sets position update period. Every time the number of frames specified has been recorded, 230 * a callback with event type EVENT_NEW_POS is called. 231 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 232 * callback. 233 * If the AudioRecord has been opened with no callback function associated, 234 * the operation will fail. 235 * 236 * Parameters: 237 * 238 * updatePeriod: position update notification period expressed in frames. 239 * 240 * Returned status (from utils/Errors.h) can be: 241 * - NO_ERROR: successful operation 242 * - INVALID_OPERATION: the AudioRecord has no callback installed. 243 */ 244 status_t setPositionUpdatePeriod(uint32_t updatePeriod); 245 status_t getPositionUpdatePeriod(uint32_t *updatePeriod) const; 246 247 248 /* Gets record head position. The position is the total number of frames 249 * recorded since record start. 250 * 251 * Parameters: 252 * 253 * position: Address where to return record head position within AudioRecord buffer. 254 * 255 * Returned status (from utils/Errors.h) can be: 256 * - NO_ERROR: successful operation 257 * - BAD_VALUE: position is NULL 258 */ 259 status_t getPosition(uint32_t *position) const; 260 261 /* returns a handle on the audio input used by this AudioRecord. 262 * 263 * Parameters: 264 * none. 265 * 266 * Returned value: 267 * handle on audio hardware input 268 */ 269 audio_io_handle_t getInput() const; 270 271 /* returns the audio session ID associated with this AudioRecord. 272 * 273 * Parameters: 274 * none. 275 * 276 * Returned value: 277 * AudioRecord session ID. 278 */ 279 int getSessionId() const; 280 281 /* obtains a buffer of "frameCount" frames. The buffer must be 282 * filled entirely. If the track is stopped, obtainBuffer() returns 283 * STOPPED instead of NO_ERROR as long as there are buffers available, 284 * at which point NO_MORE_BUFFERS is returned. 285 * Buffers will be returned until the pool (buffercount()) 286 * is exhausted, at which point obtainBuffer() will either block 287 * or return WOULD_BLOCK depending on the value of the "blocking" 288 * parameter. 289 */ 290 291 enum { 292 NO_MORE_BUFFERS = 0x80000001, 293 STOPPED = 1 294 }; 295 296 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount); 297 void releaseBuffer(Buffer* audioBuffer); 298 299 300 /* As a convenience we provide a read() interface to the audio buffer. 301 * This is implemented on top of obtainBuffer/releaseBuffer. 302 */ 303 ssize_t read(void* buffer, size_t size); 304 305 /* Return the amount of input frames lost in the audio driver since the last call of this 306 * function. Audio driver is expected to reset the value to 0 and restart counting upon 307 * returning the current value by this function call. Such loss typically occurs when the 308 * user space process is blocked longer than the capacity of audio driver buffers. 309 * Unit: the number of input audio frames 310 */ 311 unsigned int getInputFramesLost() const; 312 313 private: 314 /* copying audio tracks is not allowed */ 315 AudioRecord(const AudioRecord& other); 316 AudioRecord& operator = (const AudioRecord& other); 317 318 /* a small internal class to handle the callback */ 319 class AudioRecordThread : public Thread 320 { 321 public: 322 AudioRecordThread(AudioRecord& receiver, bool bCanCallJava = false); 323 324 // Do not call Thread::requestExitAndWait() without first calling requestExit(). 325 // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough. 326 virtual void requestExit(); 327 328 void pause(); // suspend thread from execution at next loop boundary 329 void resume(); // allow thread to execute, if not requested to exit 330 331 private: 332 friend class AudioRecord; 333 virtual bool threadLoop(); 334 AudioRecord& mReceiver; 335 virtual ~AudioRecordThread(); 336 Mutex mMyLock; // Thread::mLock is private 337 Condition mMyCond; // Thread::mThreadExitedCondition is private 338 bool mPaused; // whether thread is currently paused 339 }; 340 341 // body of AudioRecordThread::threadLoop() 342 bool processAudioBuffer(const sp<AudioRecordThread>& thread); 343 344 status_t openRecord_l(uint32_t sampleRate, 345 audio_format_t format, 346 audio_channel_mask_t channelMask, 347 int frameCount, 348 audio_io_handle_t input); 349 audio_io_handle_t getInput_l(); 350 status_t restoreRecord_l(audio_track_cblk_t*& cblk); 351 352 sp<AudioRecordThread> mAudioRecordThread; 353 mutable Mutex mLock; 354 355 bool mActive; // protected by mLock 356 357 // for client callback handler 358 callback_t mCbf; 359 void* mUserData; 360 361 // for notification APIs 362 uint32_t mNotificationFrames; 363 uint32_t mRemainingFrames; 364 uint32_t mMarkerPosition; // in frames 365 bool mMarkerReached; 366 uint32_t mNewPosition; // in frames 367 uint32_t mUpdatePeriod; // in ms 368 369 // constant after constructor or set() 370 uint32_t mFrameCount; 371 audio_format_t mFormat; 372 uint8_t mChannelCount; 373 audio_source_t mInputSource; 374 status_t mStatus; 375 uint32_t mLatency; 376 audio_channel_mask_t mChannelMask; 377 audio_io_handle_t mInput; // returned by AudioSystem::getInput() 378 int mSessionId; 379 380 // may be changed if IAudioRecord object is re-created 381 sp<IAudioRecord> mAudioRecord; 382 sp<IMemory> mCblkMemory; 383 audio_track_cblk_t* mCblk; 384 385 int mPreviousPriority; // before start() 386 SchedPolicy mPreviousSchedulingGroup; 387 }; 388 389 }; // namespace android 390 391 #endif /*AUDIORECORD_H_*/ 392