AudioTrack.h revision fff6d715a8db0daf08a50634f242c40268de3d49
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 33namespace android { 34 35// ---------------------------------------------------------------------------- 36 37class audio_track_cblk_t; 38 39// ---------------------------------------------------------------------------- 40 41class AudioTrack : virtual public RefBase 42{ 43public: 44 enum channel_index { 45 MONO = 0, 46 LEFT = 0, 47 RIGHT = 1 48 }; 49 50 /* Events used by AudioTrack callback function (audio_track_cblk_t). 51 */ 52 enum event_type { 53 EVENT_MORE_DATA = 0, // Request to write more data to PCM buffer. 54 EVENT_UNDERRUN = 1, // PCM buffer underrun occured. 55 EVENT_LOOP_END = 2, // Sample loop end was reached; playback restarted from loop start if loop count was not 0. 56 EVENT_MARKER = 3, // Playback head is at the specified marker position (See setMarkerPosition()). 57 EVENT_NEW_POS = 4, // Playback head is at a new position (See setPositionUpdatePeriod()). 58 EVENT_BUFFER_END = 5 // Playback head is at the end of the buffer. 59 }; 60 61 /* Create Buffer on the stack and pass it to obtainBuffer() 62 * and releaseBuffer(). 63 */ 64 65 class Buffer 66 { 67 public: 68 enum { 69 MUTE = 0x00000001 70 }; 71 uint32_t flags; 72 audio_format_t format; // but AUDIO_FORMAT_PCM_8_BIT -> AUDIO_FORMAT_PCM_16_BIT 73 // accessed directly by WebKit ANP callback 74 int channelCount; // will be removed in the future, do not use 75 size_t frameCount; 76 size_t size; 77 union { 78 void* raw; 79 short* i16; // signed 16-bit 80 int8_t* i8; // unsigned 8-bit, offset by 0x80 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 available 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 uint32_t containing the marker position in frames. 99 * - EVENT_NEW_POS: pointer to an uint32_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 /* Returns the minimum frame count required for the successful creation of 106 * an AudioTrack object. 107 * Returned status (from utils/Errors.h) can be: 108 * - NO_ERROR: successful operation 109 * - NO_INIT: audio server or audio hardware not initialized 110 */ 111 112 static status_t getMinFrameCount(int* frameCount, 113 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT, 114 uint32_t sampleRate = 0); 115 116 /* Constructs an uninitialized AudioTrack. No connection with 117 * AudioFlinger takes place. 118 */ 119 AudioTrack(); 120 121 /* Creates an audio track and registers it with AudioFlinger. 122 * Once created, the track needs to be started before it can be used. 123 * Unspecified values are set to the audio hardware's current 124 * values. 125 * 126 * Parameters: 127 * 128 * streamType: Select the type of audio stream this track is attached to 129 * (e.g. AUDIO_STREAM_MUSIC). 130 * sampleRate: Track sampling rate in Hz. 131 * format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed 132 * 16 bits per sample). 133 * channelMask: Channel mask: see audio_channels_t. 134 * frameCount: Total size of track PCM buffer in frames. This defines the 135 * latency of the track. 136 * flags: Reserved for future use. 137 * cbf: Callback function. If not null, this function is called periodically 138 * to request new PCM data. 139 * user: Context for use by the callback receiver. 140 * notificationFrames: The callback function is called each time notificationFrames PCM 141 * frames have been consumed from track input buffer. 142 * sessionId: Specific session ID, or zero to use default. 143 */ 144 145 AudioTrack( audio_stream_type_t streamType, 146 uint32_t sampleRate = 0, 147 audio_format_t format = AUDIO_FORMAT_DEFAULT, 148 int channelMask = 0, 149 int frameCount = 0, 150 uint32_t flags = 0, 151 callback_t cbf = 0, 152 void* user = 0, 153 int notificationFrames = 0, 154 int sessionId = 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 in memory before the AudioTrack is started. 160 * The write() and flush() methods are not supported in this case. 161 * It is recommended to pass a callback function to be notified of playback end by an 162 * EVENT_UNDERRUN event. 163 */ 164 165 AudioTrack( audio_stream_type_t streamType, 166 uint32_t sampleRate = 0, 167 audio_format_t format = AUDIO_FORMAT_DEFAULT, 168 int channelMask = 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 int sessionId = 0); 175 176 /* Terminates the AudioTrack and unregisters it from AudioFlinger. 177 * Also destroys all resources associated with the AudioTrack. 178 */ 179 ~AudioTrack(); 180 181 182 /* Initialize an uninitialized AudioTrack. 183 * Returned status (from utils/Errors.h) can be: 184 * - NO_ERROR: successful initialization 185 * - INVALID_OPERATION: AudioTrack is already initialized 186 * - BAD_VALUE: invalid parameter (channels, format, sampleRate...) 187 * - NO_INIT: audio server or audio hardware not initialized 188 * */ 189 status_t set(audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT, 190 uint32_t sampleRate = 0, 191 audio_format_t format = AUDIO_FORMAT_DEFAULT, 192 int channelMask = 0, 193 int frameCount = 0, 194 uint32_t flags = 0, 195 callback_t cbf = 0, 196 void* user = 0, 197 int notificationFrames = 0, 198 const sp<IMemory>& sharedBuffer = 0, 199 bool threadCanCallJava = false, 200 int sessionId = 0); 201 202 203 /* Result of constructing the AudioTrack. This must be checked 204 * before using any AudioTrack API (except for set()), because using 205 * an uninitialized AudioTrack produces undefined results. 206 * See set() method above for possible return codes. 207 */ 208 status_t initCheck() const; 209 210 /* Returns this track's estimated latency in milliseconds. 211 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any) 212 * and audio hardware driver. 213 */ 214 uint32_t latency() const; 215 216 /* getters, see constructor */ 217 218 audio_stream_type_t streamType() const; 219 audio_format_t format() const; 220 int channelCount() const; 221 uint32_t frameCount() const; 222 int frameSize() const; 223 sp<IMemory>& sharedBuffer(); 224 225 226 /* After it's created the track is not active. Call start() to 227 * make it active. If set, the callback will start being called. 228 */ 229 void start(); 230 231 /* Stop a track. If set, the callback will cease being called and 232 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works 233 * and will fill up buffers until the pool is exhausted. 234 */ 235 void stop(); 236 bool stopped() const; 237 238 /* Flush a stopped track. All pending buffers are discarded. 239 * This function has no effect if the track is not stopped. 240 */ 241 void flush(); 242 243 /* Pause a track. If set, the callback will cease being called and 244 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works 245 * and will fill up buffers until the pool is exhausted. 246 */ 247 void pause(); 248 249 /* Mute or unmute this track. 250 * While muted, the callback, if set, is still called. 251 */ 252 void mute(bool); 253 bool muted() const; 254 255 /* Set volume for this track, mostly used for games' sound effects 256 * left and right volumes. Levels must be >= 0.0 and <= 1.0. 257 */ 258 status_t setVolume(float left, float right); 259 void getVolume(float* left, float* right); 260 261 /* Set the send level for this track. An auxiliary effect should be attached 262 * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0. 263 */ 264 status_t setAuxEffectSendLevel(float level); 265 void getAuxEffectSendLevel(float* level); 266 267 /* Set sample rate for this track, mostly used for games' sound effects 268 */ 269 status_t setSampleRate(int sampleRate); 270 uint32_t getSampleRate(); 271 272 /* Enables looping and sets the start and end points of looping. 273 * 274 * Parameters: 275 * 276 * loopStart: loop start expressed as the number of PCM frames played since AudioTrack start. 277 * loopEnd: loop end expressed as the number of PCM frames played since AudioTrack start. 278 * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any 279 * pending or active loop. loopCount = -1 means infinite looping. 280 * 281 * For proper operation the following condition must be respected: 282 * (loopEnd-loopStart) <= framecount() 283 */ 284 status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount); 285 status_t getLoop(uint32_t *loopStart, uint32_t *loopEnd, int *loopCount); 286 287 /* Sets marker position. When playback reaches the number of frames specified, a callback with 288 * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker 289 * notification callback. 290 * If the AudioTrack has been opened with no callback function associated, the operation will fail. 291 * 292 * Parameters: 293 * 294 * marker: marker position expressed in frames. 295 * 296 * Returned status (from utils/Errors.h) can be: 297 * - NO_ERROR: successful operation 298 * - INVALID_OPERATION: the AudioTrack has no callback installed. 299 */ 300 status_t setMarkerPosition(uint32_t marker); 301 status_t getMarkerPosition(uint32_t *marker); 302 303 304 /* Sets position update period. Every time the number of frames specified has been played, 305 * a callback with event type EVENT_NEW_POS is called. 306 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 307 * callback. 308 * If the AudioTrack has been opened with no callback function associated, the operation will fail. 309 * 310 * Parameters: 311 * 312 * updatePeriod: position update notification period expressed in frames. 313 * 314 * Returned status (from utils/Errors.h) can be: 315 * - NO_ERROR: successful operation 316 * - INVALID_OPERATION: the AudioTrack has no callback installed. 317 */ 318 status_t setPositionUpdatePeriod(uint32_t updatePeriod); 319 status_t getPositionUpdatePeriod(uint32_t *updatePeriod); 320 321 /* Sets playback head position within AudioTrack buffer. The new position is specified 322 * in number of frames. 323 * This method must be called with the AudioTrack in paused or stopped state. 324 * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames. 325 * Therefore using this method makes sense only when playing a "static" audio buffer 326 * as opposed to streaming. 327 * The getPosition() method on the other hand returns the total number of frames played since 328 * playback start. 329 * 330 * Parameters: 331 * 332 * position: New playback head position within AudioTrack buffer. 333 * 334 * Returned status (from utils/Errors.h) can be: 335 * - NO_ERROR: successful operation 336 * - INVALID_OPERATION: the AudioTrack is not stopped. 337 * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack buffer 338 */ 339 status_t setPosition(uint32_t position); 340 status_t getPosition(uint32_t *position); 341 342 /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids 343 * rewriting the buffer before restarting playback after a stop. 344 * This method must be called with the AudioTrack in paused or stopped state. 345 * 346 * Returned status (from utils/Errors.h) can be: 347 * - NO_ERROR: successful operation 348 * - INVALID_OPERATION: the AudioTrack is not stopped. 349 */ 350 status_t reload(); 351 352 /* Returns a handle on the audio output used by this AudioTrack. 353 * 354 * Parameters: 355 * none. 356 * 357 * Returned value: 358 * handle on audio hardware output 359 */ 360 audio_io_handle_t getOutput(); 361 362 /* Returns the unique session ID associated with this track. 363 * 364 * Parameters: 365 * none. 366 * 367 * Returned value: 368 * AudioTrack session ID. 369 */ 370 int getSessionId(); 371 372 /* Attach track auxiliary output to specified effect. Use effectId = 0 373 * to detach track from effect. 374 * 375 * Parameters: 376 * 377 * effectId: effectId obtained from AudioEffect::id(). 378 * 379 * Returned status (from utils/Errors.h) can be: 380 * - NO_ERROR: successful operation 381 * - INVALID_OPERATION: the effect is not an auxiliary effect. 382 * - BAD_VALUE: The specified effect ID is invalid 383 */ 384 status_t attachAuxEffect(int effectId); 385 386 /* Obtains a buffer of "frameCount" frames. The buffer must be 387 * filled entirely. If the track is stopped, obtainBuffer() returns 388 * STOPPED instead of NO_ERROR as long as there are buffers available, 389 * at which point NO_MORE_BUFFERS is returned. 390 * Buffers will be returned until the pool (buffercount()) 391 * is exhausted, at which point obtainBuffer() will either block 392 * or return WOULD_BLOCK depending on the value of the "blocking" 393 * parameter. 394 */ 395 396 enum { 397 NO_MORE_BUFFERS = 0x80000001, 398 STOPPED = 1 399 }; 400 401 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount); 402 void releaseBuffer(Buffer* audioBuffer); 403 404 /* As a convenience we provide a write() interface to the audio buffer. 405 * This is implemented on top of lockBuffer/unlockBuffer. For best 406 * performance use callbacks. Return actual number of bytes written. 407 * 408 */ 409 ssize_t write(const void* buffer, size_t size); 410 411 /* 412 * Dumps the state of an audio track. 413 */ 414 status_t dump(int fd, const Vector<String16>& args) const; 415 416private: 417 /* copying audio tracks is not allowed */ 418 AudioTrack(const AudioTrack& other); 419 AudioTrack& operator = (const AudioTrack& other); 420 421 /* a small internal class to handle the callback */ 422 class AudioTrackThread : public Thread 423 { 424 public: 425 AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false); 426 private: 427 friend class AudioTrack; 428 virtual bool threadLoop(); 429 virtual status_t readyToRun(); 430 virtual void onFirstRef(); 431 AudioTrack& mReceiver; 432 Mutex mLock; 433 }; 434 435 bool processAudioBuffer(const sp<AudioTrackThread>& thread); 436 status_t createTrack_l(audio_stream_type_t streamType, 437 uint32_t sampleRate, 438 audio_format_t format, 439 uint32_t channelMask, 440 int frameCount, 441 uint32_t flags, 442 const sp<IMemory>& sharedBuffer, 443 audio_io_handle_t output, 444 bool enforceFrameCount); 445 void flush_l(); 446 status_t setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount); 447 audio_io_handle_t getOutput_l(); 448 status_t restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart); 449 bool stopped_l() const { return !mActive; } 450 451 sp<IAudioTrack> mAudioTrack; 452 sp<IMemory> mCblkMemory; 453 sp<AudioTrackThread> mAudioTrackThread; 454 455 float mVolume[2]; 456 float mSendLevel; 457 uint32_t mFrameCount; 458 459 audio_track_cblk_t* mCblk; 460 audio_format_t mFormat; 461 audio_stream_type_t mStreamType; 462 uint8_t mChannelCount; 463 uint8_t mMuted; 464 uint8_t mReserved; 465 uint32_t mChannelMask; 466 status_t mStatus; 467 uint32_t mLatency; 468 469 bool mActive; // protected by mLock 470 471 callback_t mCbf; 472 void* mUserData; 473 uint32_t mNotificationFramesReq; // requested number of frames between each notification callback 474 uint32_t mNotificationFramesAct; // actual number of frames between each notification callback 475 sp<IMemory> mSharedBuffer; 476 int mLoopCount; 477 uint32_t mRemainingFrames; 478 uint32_t mMarkerPosition; 479 bool mMarkerReached; 480 uint32_t mNewPosition; 481 uint32_t mUpdatePeriod; 482 bool mFlushed; // FIXME will be made obsolete by making flush() synchronous 483 uint32_t mFlags; 484 int mSessionId; 485 int mAuxEffectId; 486 mutable Mutex mLock; 487 status_t mRestoreStatus; 488 int mPreviousPriority; // before start() 489 int mPreviousSchedulingGroup; 490}; 491 492 493}; // namespace android 494 495#endif // ANDROID_AUDIOTRACK_H 496