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