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