AudioTrack.h revision 7b5eb023f8d87cca6d830ae6c11c6aadbe02aca8
1/* 2 * Copyright (C) 2007 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_AUDIOTRACK_H 18#define ANDROID_AUDIOTRACK_H 19 20#include <stdint.h> 21#include <sys/types.h> 22 23#include <media/IAudioFlinger.h> 24#include <media/IAudioTrack.h> 25#include <media/AudioSystem.h> 26 27#include <utils/RefBase.h> 28#include <utils/Errors.h> 29#include <utils/IInterface.h> 30#include <utils/IMemory.h> 31#include <utils/threads.h> 32 33 34namespace android { 35 36// ---------------------------------------------------------------------------- 37 38class audio_track_cblk_t; 39 40// ---------------------------------------------------------------------------- 41 42class AudioTrack 43{ 44public: 45 46 enum stream_type { 47 DEFAULT =-1, 48 VOICE_CALL = 0, 49 SYSTEM = 1, 50 RING = 2, 51 MUSIC = 3, 52 ALARM = 4, 53 NOTIFICATION = 5, 54 NUM_STREAM_TYPES 55 }; 56 57 enum channel_index { 58 MONO = 0, 59 LEFT = 0, 60 RIGHT = 1 61 }; 62 63 /* Events used by AudioTrack callback function (audio_track_cblk_t). 64 */ 65 enum event_type { 66 EVENT_MORE_DATA = 0, // Request to write more data to PCM buffer. 67 EVENT_UNDERRUN = 1, // PCM buffer underrun occured. 68 EVENT_LOOP_END = 2, // Sample loop end was reached; playback restarted from loop start if loop count was not 0. 69 EVENT_MARKER = 3, // Playback head is at the specified marker position (See setMarkerPosition()). 70 EVENT_NEW_POS = 4, // Playback head is at a new position (See setPositionUpdatePeriod()). 71 EVENT_BUFFER_END = 5 // Playback head is at the end of the buffer. 72 }; 73 74 /* Create Buffer on the stack and pass it to obtainBuffer() 75 * and releaseBuffer(). 76 */ 77 78 class Buffer 79 { 80 public: 81 enum { 82 MUTE = 0x00000001 83 }; 84 uint32_t flags; 85 int channelCount; 86 int format; 87 size_t frameCount; 88 size_t size; 89 union { 90 void* raw; 91 short* i16; 92 int8_t* i8; 93 }; 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 availlable or an underrun condition occurs. 100 * Parameters: 101 * 102 * event: type of event notified (see enum AudioTrack::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 AudioTrack::Buffer struct. The callback must not write 106 * more bytes than indicated by 'size' field and update 'size' if less bytes are 107 * written. 108 * - EVENT_UNDERRUN: unused. 109 * - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining. 110 * - EVENT_MARKER: pointer to an uin32_t containing the marker position in frames. 111 * - EVENT_NEW_POS: pointer to an uin32_t containing the new position in frames. 112 * - EVENT_BUFFER_END: unused. 113 */ 114 115 typedef void (*callback_t)(int event, void* user, void *info); 116 117 /* Constructs an uninitialized AudioTrack. No connection with 118 * AudioFlinger takes place. 119 */ 120 AudioTrack(); 121 122 /* Creates an audio track 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 the audio hardware's current 125 * values. 126 * 127 * Parameters: 128 * 129 * streamType: Select the type of audio stream this track is attached to 130 * (e.g. AudioTrack::MUSIC). 131 * sampleRate: Track sampling rate in Hz. 132 * format: PCM sample format (e.g AudioSystem::PCM_16_BIT for signed 133 * 16 bits per sample). 134 * channelCount: Number of PCM channels (e.g 2 for stereo). 135 * frameCount: Total size of track PCM buffer in frames. This defines the 136 * latency of the track. 137 * flags: Reserved for future use. 138 * cbf: Callback function. If not null, this function is called periodically 139 * to request new PCM data. 140 * notificationFrames: The callback function is called each time notificationFrames PCM 141 * frames have been comsumed from track input buffer. 142 * user Context for use by the callback receiver. 143 */ 144 145 AudioTrack( int streamType, 146 uint32_t sampleRate = 0, 147 int format = 0, 148 int channelCount = 0, 149 int frameCount = 0, 150 uint32_t flags = 0, 151 callback_t cbf = 0, 152 void* user = 0, 153 int notificationFrames = 0); 154 155 /* Creates an audio track and registers it with AudioFlinger. With this constructor, 156 * The PCM data to be rendered by AudioTrack is passed in a shared memory buffer 157 * identified by the argument sharedBuffer. This prototype is for static buffer playback. 158 * PCM data must be present into memory before the AudioTrack is started. 159 * The Write() and Flush() methods are not supported in this case. 160 * It is recommented to pass a callback function to be notified of playback end by an 161 * EVENT_UNDERRUN event. 162 */ 163 164 AudioTrack( int streamType, 165 uint32_t sampleRate = 0, 166 int format = 0, 167 int channelCount = 0, 168 const sp<IMemory>& sharedBuffer = 0, 169 uint32_t flags = 0, 170 callback_t cbf = 0, 171 void* user = 0, 172 int notificationFrames = 0); 173 174 /* Terminates the AudioTrack and unregisters it from AudioFlinger. 175 * Also destroys all resources assotiated with the AudioTrack. 176 */ 177 ~AudioTrack(); 178 179 180 /* Initialize an uninitialized AudioTrack. 181 * Returned status (from utils/Errors.h) can be: 182 * - NO_ERROR: successful intialization 183 * - INVALID_OPERATION: AudioTrack is already intitialized 184 * - BAD_VALUE: invalid parameter (channelCount, format, sampleRate...) 185 * - NO_INIT: audio server or audio hardware not initialized 186 * */ 187 status_t set(int streamType =-1, 188 uint32_t sampleRate = 0, 189 int format = 0, 190 int channelCount = 0, 191 int frameCount = 0, 192 uint32_t flags = 0, 193 callback_t cbf = 0, 194 void* user = 0, 195 int notificationFrames = 0, 196 const sp<IMemory>& sharedBuffer = 0, 197 bool threadCanCallJava = false); 198 199 200 /* Result of constructing the AudioTrack. This must be checked 201 * before using any AudioTrack API (except for set()), using 202 * an uninitialized AudioTrack produces undefined results. 203 * See set() method above for possible return codes. 204 */ 205 status_t initCheck() const; 206 207 /* Returns this track's latency in milliseconds. 208 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any) 209 * and audio hardware driver. 210 */ 211 uint32_t latency() const; 212 213 /* getters, see constructor */ 214 215 int streamType() const; 216 uint32_t sampleRate() const; 217 int format() const; 218 int channelCount() const; 219 uint32_t frameCount() const; 220 int frameSize() const; 221 sp<IMemory>& sharedBuffer(); 222 223 224 /* After it's created the track is not active. Call start() to 225 * make it active. If set, the callback will start being called. 226 */ 227 void start(); 228 229 /* Stop a track. If set, the callback will cease being called and 230 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works 231 * and will fill up buffers until the pool is exhausted. 232 */ 233 void stop(); 234 bool stopped() const; 235 236 /* flush a stopped track. All pending buffers are discarded. 237 * This function has no effect if the track is not stoped. 238 */ 239 void flush(); 240 241 /* Pause a track. If set, the callback will cease being called and 242 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works 243 * and will fill up buffers until the pool is exhausted. 244 */ 245 void pause(); 246 247 /* mute or unmutes this track. 248 * While mutted, the callback, if set, is still called. 249 */ 250 void mute(bool); 251 bool muted() const; 252 253 254 /* set volume for this track, mostly used for games' sound effects 255 */ 256 void setVolume(float left, float right); 257 void getVolume(float* left, float* right); 258 259 /* set sample rate for this track, mostly used for games' sound effects 260 */ 261 void setSampleRate(int sampleRate); 262 uint32_t getSampleRate(); 263 264 /* Enables looping and sets the start and end points of looping. 265 * 266 * Parameters: 267 * 268 * loopStart: loop start expressed as the number of PCM frames played since AudioTrack start. 269 * loopEnd: loop end expressed as the number of PCM frames played since AudioTrack start. 270 * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any pending or 271 * active loop. loopCount = -1 means infinite looping. 272 * 273 * For proper operation the following condition must be respected: 274 * (loopEnd-loopStart) <= framecount() 275 */ 276 status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount); 277 status_t getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount); 278 279 280 /* Sets marker position. When playback reaches the number of frames specified, a callback with event 281 * type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker notification 282 * callback. 283 * If the AudioTrack has been opened with no callback function associated, the operation will fail. 284 * 285 * Parameters: 286 * 287 * marker: marker position expressed in frames. 288 * 289 * Returned status (from utils/Errors.h) can be: 290 * - NO_ERROR: successful operation 291 * - INVALID_OPERATION: the AudioTrack has no callback installed. 292 */ 293 status_t setMarkerPosition(uint32_t marker); 294 status_t getMarkerPosition(uint32_t *marker); 295 296 297 /* Sets position update period. Every time the number of frames specified has been played, 298 * a callback with event type EVENT_NEW_POS is called. 299 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 300 * callback. 301 * If the AudioTrack has been opened with no callback function associated, the operation will fail. 302 * 303 * Parameters: 304 * 305 * updatePeriod: position update notification period expressed in frames. 306 * 307 * Returned status (from utils/Errors.h) can be: 308 * - NO_ERROR: successful operation 309 * - INVALID_OPERATION: the AudioTrack has no callback installed. 310 */ 311 status_t setPositionUpdatePeriod(uint32_t updatePeriod); 312 status_t getPositionUpdatePeriod(uint32_t *updatePeriod); 313 314 315 /* Sets playback head position within AudioTrack buffer. The new position is specified 316 * in number of frames. 317 * This method must be called with the AudioTrack in paused or stopped state. 318 * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames. 319 * Therefore using this method makes sense only when playing a "static" audio buffer 320 * as opposed to streaming. 321 * The getPosition() method on the other hand returns the total number of frames played since 322 * playback start. 323 * 324 * Parameters: 325 * 326 * position: New playback head position within AudioTrack buffer. 327 * 328 * Returned status (from utils/Errors.h) can be: 329 * - NO_ERROR: successful operation 330 * - INVALID_OPERATION: the AudioTrack is not stopped. 331 * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer 332 */ 333 status_t setPosition(uint32_t position); 334 status_t getPosition(uint32_t *position); 335 336 /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids 337 * rewriting the buffer before restarting playback after a stop. 338 * This method must be called with the AudioTrack in paused or stopped state. 339 * 340 * Returned status (from utils/Errors.h) can be: 341 * - NO_ERROR: successful operation 342 * - INVALID_OPERATION: the AudioTrack is not stopped. 343 */ 344 status_t reload(); 345 346 /* obtains a buffer of "frameCount" frames. The buffer must be 347 * filled entirely. If the track is stopped, obtainBuffer() returns 348 * STOPPED instead of NO_ERROR as long as there are buffers availlable, 349 * at which point NO_MORE_BUFFERS is returned. 350 * Buffers will be returned until the pool (buffercount()) 351 * is exhausted, at which point obtainBuffer() will either block 352 * or return WOULD_BLOCK depending on the value of the "blocking" 353 * parameter. 354 */ 355 356 enum { 357 NO_MORE_BUFFERS = 0x80000001, 358 STOPPED = 1 359 }; 360 361 status_t obtainBuffer(Buffer* audioBuffer, bool blocking); 362 void releaseBuffer(Buffer* audioBuffer); 363 364 365 /* As a convenience we provide a write() interface to the audio buffer. 366 * This is implemented on top of lockBuffer/unlockBuffer. For best 367 * performance 368 * 369 */ 370 ssize_t write(const void* buffer, size_t size); 371 372 /* 373 * Dumps the state of an audio track. 374 */ 375 status_t dump(int fd, const Vector<String16>& args) const; 376 377private: 378 /* copying audio tracks is not allowed */ 379 AudioTrack(const AudioTrack& other); 380 AudioTrack& operator = (const AudioTrack& other); 381 382 /* a small internal class to handle the callback */ 383 class AudioTrackThread : public Thread 384 { 385 public: 386 AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false); 387 private: 388 friend class AudioTrack; 389 virtual bool threadLoop(); 390 virtual status_t readyToRun(); 391 virtual void onFirstRef(); 392 AudioTrack& mReceiver; 393 Mutex mLock; 394 }; 395 396 bool processAudioBuffer(const sp<AudioTrackThread>& thread); 397 398 sp<IAudioFlinger> mAudioFlinger; 399 sp<IAudioTrack> mAudioTrack; 400 sp<IMemory> mCblkMemory; 401 sp<AudioTrackThread> mAudioTrackThread; 402 403 float mVolume[2]; 404 uint32_t mSampleRate; 405 uint32_t mFrameCount; 406 407 audio_track_cblk_t* mCblk; 408 uint8_t mStreamType; 409 uint8_t mFormat; 410 uint8_t mChannelCount; 411 uint8_t mMuted; 412 status_t mStatus; 413 uint32_t mLatency; 414 415 volatile int32_t mActive; 416 417 callback_t mCbf; 418 void* mUserData; 419 uint32_t mNotificationFrames; 420 sp<IMemory> mSharedBuffer; 421 int mLoopCount; 422 uint32_t mRemainingFrames; 423 uint32_t mMarkerPosition; 424 uint32_t mNewPosition; 425 uint32_t mUpdatePeriod; 426}; 427 428 429}; // namespace android 430 431#endif // ANDROID_AUDIOTRACK_H 432