AudioTrack.h revision ad2f6dbe14e601ae69f3697bc17106f9fd7d59d6
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 <cutils/sched_policy.h> 32#include <utils/threads.h> 33 34namespace android { 35 36// ---------------------------------------------------------------------------- 37 38class audio_track_cblk_t; 39 40// ---------------------------------------------------------------------------- 41 42class AudioTrack : virtual public RefBase 43{ 44public: 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 * Keep in sync with frameworks/base/media/java/android/media/AudioTrack.java NATIVE_EVENT_*. 53 */ 54 enum event_type { 55 EVENT_MORE_DATA = 0, // Request to write more data to PCM buffer. 56 EVENT_UNDERRUN = 1, // PCM buffer underrun occurred. 57 EVENT_LOOP_END = 2, // Sample loop end was reached; playback restarted from 58 // loop start if loop count was not 0. 59 EVENT_MARKER = 3, // Playback head is at the specified marker position 60 // (See setMarkerPosition()). 61 EVENT_NEW_POS = 4, // Playback head is at a new position 62 // (See setPositionUpdatePeriod()). 63 EVENT_BUFFER_END = 5 // Playback head is at the end of the buffer. 64 }; 65 66 /* Client should declare Buffer on the stack and pass address to obtainBuffer() 67 * and releaseBuffer(). See also callback_t for EVENT_MORE_DATA. 68 */ 69 70 class Buffer 71 { 72 public: 73 enum { 74 MUTE = 0x00000001 75 }; 76 uint32_t flags; // 0 or MUTE 77 audio_format_t format; // but AUDIO_FORMAT_PCM_8_BIT -> AUDIO_FORMAT_PCM_16_BIT 78 // accessed directly by WebKit ANP callback 79 int channelCount; // will be removed in the future, do not use 80 81 size_t frameCount; // number of sample frames corresponding to size; 82 // on input it is the number of frames desired, 83 // on output is the number of frames actually filled 84 85 size_t size; // input/output in byte units 86 union { 87 void* raw; 88 short* i16; // signed 16-bit 89 int8_t* i8; // unsigned 8-bit, offset by 0x80 90 }; 91 }; 92 93 94 /* As a convenience, if a callback is supplied, a handler thread 95 * is automatically created with the appropriate priority. This thread 96 * invokes the callback when a new buffer becomes available or various conditions occur. 97 * Parameters: 98 * 99 * event: type of event notified (see enum AudioTrack::event_type). 100 * user: Pointer to context for use by the callback receiver. 101 * info: Pointer to optional parameter according to event type: 102 * - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write 103 * more bytes than indicated by 'size' field and update 'size' if fewer bytes are 104 * written. 105 * - EVENT_UNDERRUN: unused. 106 * - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining. 107 * - EVENT_MARKER: pointer to an uint32_t containing the marker position in frames. 108 * - EVENT_NEW_POS: pointer to an uint32_t containing the new position in frames. 109 * - EVENT_BUFFER_END: unused. 110 */ 111 112 typedef void (*callback_t)(int event, void* user, void *info); 113 114 /* Returns the minimum frame count required for the successful creation of 115 * an AudioTrack object. 116 * Returned status (from utils/Errors.h) can be: 117 * - NO_ERROR: successful operation 118 * - NO_INIT: audio server or audio hardware not initialized 119 */ 120 121 static status_t getMinFrameCount(int* frameCount, 122 audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT, 123 uint32_t sampleRate = 0); 124 125 /* Constructs an uninitialized AudioTrack. No connection with 126 * AudioFlinger takes place. 127 */ 128 AudioTrack(); 129 130 /* Creates an AudioTrack object and registers it with AudioFlinger. 131 * Once created, the track needs to be started before it can be used. 132 * Unspecified values are set to the audio hardware's current 133 * values. 134 * 135 * Parameters: 136 * 137 * streamType: Select the type of audio stream this track is attached to 138 * (e.g. AUDIO_STREAM_MUSIC). 139 * sampleRate: Track sampling rate in Hz. 140 * format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed 141 * 16 bits per sample). 142 * channelMask: Channel mask. 143 * frameCount: Minimum size of track PCM buffer in frames. This defines the 144 * application's contribution to the 145 * latency of the track. The actual size selected by the AudioTrack could be 146 * larger if the requested size is not compatible with current audio HAL 147 * latency. Zero means to use a default value. 148 * flags: See comments on audio_output_flags_t in <system/audio.h>. 149 * cbf: Callback function. If not null, this function is called periodically 150 * to provide new PCM data. 151 * user: Context for use by the callback receiver. 152 * notificationFrames: The callback function is called each time notificationFrames PCM 153 * frames have been consumed from track input buffer. 154 * sessionId: Specific session ID, or zero to use default. 155 * threadCanCallJava: Whether callbacks are made from an attached thread and thus can call JNI. 156 * If not present in parameter list, then fixed at false. 157 */ 158 159 AudioTrack( audio_stream_type_t streamType, 160 uint32_t sampleRate = 0, 161 audio_format_t format = AUDIO_FORMAT_DEFAULT, 162 audio_channel_mask_t channelMask = 0, 163 int frameCount = 0, 164 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 165 callback_t cbf = NULL, 166 void* user = NULL, 167 int notificationFrames = 0, 168 int sessionId = 0); 169 170 // DEPRECATED 171 explicit AudioTrack( int streamType, 172 uint32_t sampleRate = 0, 173 int format = AUDIO_FORMAT_DEFAULT, 174 int channelMask = 0, 175 int frameCount = 0, 176 uint32_t flags = (uint32_t) AUDIO_OUTPUT_FLAG_NONE, 177 callback_t cbf = 0, 178 void* user = 0, 179 int notificationFrames = 0, 180 int sessionId = 0); 181 182 /* Creates an audio track and registers it with AudioFlinger. With this constructor, 183 * the PCM data to be rendered by AudioTrack is passed in a shared memory buffer 184 * identified by the argument sharedBuffer. This prototype is for static buffer playback. 185 * PCM data must be present in memory before the AudioTrack is started. 186 * The write() and flush() methods are not supported in this case. 187 * It is recommended to pass a callback function to be notified of playback end by an 188 * EVENT_UNDERRUN event. 189 */ 190 191 AudioTrack( audio_stream_type_t streamType, 192 uint32_t sampleRate = 0, 193 audio_format_t format = AUDIO_FORMAT_DEFAULT, 194 audio_channel_mask_t channelMask = 0, 195 const sp<IMemory>& sharedBuffer = 0, 196 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 197 callback_t cbf = NULL, 198 void* user = NULL, 199 int notificationFrames = 0, 200 int sessionId = 0); 201 202 /* Terminates the AudioTrack and unregisters it from AudioFlinger. 203 * Also destroys all resources associated with the AudioTrack. 204 */ 205 ~AudioTrack(); 206 207 208 /* Initialize an uninitialized AudioTrack. 209 * Returned status (from utils/Errors.h) can be: 210 * - NO_ERROR: successful initialization 211 * - INVALID_OPERATION: AudioTrack is already initialized 212 * - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...) 213 * - NO_INIT: audio server or audio hardware not initialized 214 */ 215 status_t set(audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT, 216 uint32_t sampleRate = 0, 217 audio_format_t format = AUDIO_FORMAT_DEFAULT, 218 audio_channel_mask_t channelMask = 0, 219 int frameCount = 0, 220 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 221 callback_t cbf = NULL, 222 void* user = NULL, 223 int notificationFrames = 0, 224 const sp<IMemory>& sharedBuffer = 0, 225 bool threadCanCallJava = false, 226 int sessionId = 0); 227 228 229 /* Result of constructing the AudioTrack. This must be checked 230 * before using any AudioTrack API (except for set()), because using 231 * an uninitialized AudioTrack produces undefined results. 232 * See set() method above for possible return codes. 233 */ 234 status_t initCheck() const; 235 236 /* Returns this track's estimated latency in milliseconds. 237 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any) 238 * and audio hardware driver. 239 */ 240 uint32_t latency() const; 241 242 /* getters, see constructors and set() */ 243 244 audio_stream_type_t streamType() const; 245 audio_format_t format() const; 246 int channelCount() const; 247 uint32_t frameCount() const; 248 249 /* Return channelCount * (bit depth per channel / 8). 250 * channelCount is determined from channelMask, and bit depth comes from format. 251 */ 252 size_t frameSize() const; 253 254 sp<IMemory>& sharedBuffer(); 255 256 257 /* After it's created the track is not active. Call start() to 258 * make it active. If set, the callback will start being called. 259 */ 260 void start(); 261 262 /* Stop a track. If set, the callback will cease being called and 263 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works 264 * and will fill up buffers until the pool is exhausted. 265 */ 266 void stop(); 267 bool stopped() const; 268 269 /* Flush a stopped track. All pending buffers are discarded. 270 * This function has no effect if the track is not stopped. 271 */ 272 void flush(); 273 274 /* Pause a track. If set, the callback will cease being called and 275 * obtainBuffer returns STOPPED. Note that obtainBuffer() still works 276 * and will fill up buffers until the pool is exhausted. 277 */ 278 void pause(); 279 280 /* Mute or unmute this track. 281 * While muted, the callback, if set, is still called. 282 */ 283 void mute(bool); 284 bool muted() const; 285 286 /* Set volume for this track, mostly used for games' sound effects 287 * left and right volumes. Levels must be >= 0.0 and <= 1.0. 288 */ 289 status_t setVolume(float left, float right); 290 void getVolume(float* left, float* right) const; 291 292 /* Set the send level for this track. An auxiliary effect should be attached 293 * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0. 294 */ 295 status_t setAuxEffectSendLevel(float level); 296 void getAuxEffectSendLevel(float* level) const; 297 298 /* Set sample rate for this track in Hz, mostly used for games' sound effects 299 */ 300 status_t setSampleRate(int sampleRate); 301 uint32_t getSampleRate() const; 302 303 /* Enables looping and sets the start and end points of looping. 304 * 305 * Parameters: 306 * 307 * loopStart: loop start expressed as the number of PCM frames played since AudioTrack start. 308 * loopEnd: loop end expressed as the number of PCM frames played since AudioTrack start. 309 * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any 310 * pending or active loop. loopCount = -1 means infinite looping. 311 * 312 * For proper operation the following condition must be respected: 313 * (loopEnd-loopStart) <= framecount() 314 */ 315 status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount); 316 317 /* Sets marker position. When playback reaches the number of frames specified, a callback with 318 * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker 319 * notification callback. 320 * If the AudioTrack has been opened with no callback function associated, the operation will 321 * fail. 322 * 323 * Parameters: 324 * 325 * marker: marker position expressed in frames. 326 * 327 * Returned status (from utils/Errors.h) can be: 328 * - NO_ERROR: successful operation 329 * - INVALID_OPERATION: the AudioTrack has no callback installed. 330 */ 331 status_t setMarkerPosition(uint32_t marker); 332 status_t getMarkerPosition(uint32_t *marker) const; 333 334 335 /* Sets position update period. Every time the number of frames specified has been played, 336 * a callback with event type EVENT_NEW_POS is called. 337 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 338 * callback. 339 * If the AudioTrack has been opened with no callback function associated, the operation will 340 * fail. 341 * 342 * Parameters: 343 * 344 * updatePeriod: position update notification period expressed in frames. 345 * 346 * Returned status (from utils/Errors.h) can be: 347 * - NO_ERROR: successful operation 348 * - INVALID_OPERATION: the AudioTrack has no callback installed. 349 */ 350 status_t setPositionUpdatePeriod(uint32_t updatePeriod); 351 status_t getPositionUpdatePeriod(uint32_t *updatePeriod) const; 352 353 /* Sets playback head position within AudioTrack buffer. The new position is specified 354 * in number of frames. 355 * This method must be called with the AudioTrack in paused or stopped state. 356 * Note that the actual position set is <position> modulo the AudioTrack buffer size in frames. 357 * Therefore using this method makes sense only when playing a "static" audio buffer 358 * as opposed to streaming. 359 * The getPosition() method on the other hand returns the total number of frames played since 360 * playback start. 361 * 362 * Parameters: 363 * 364 * position: New playback head position within AudioTrack buffer. 365 * 366 * Returned status (from utils/Errors.h) can be: 367 * - NO_ERROR: successful operation 368 * - INVALID_OPERATION: the AudioTrack is not stopped. 369 * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack 370 * buffer 371 */ 372 status_t setPosition(uint32_t position); 373 status_t getPosition(uint32_t *position); 374 375 /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids 376 * rewriting the buffer before restarting playback after a stop. 377 * This method must be called with the AudioTrack in paused or stopped state. 378 * 379 * Returned status (from utils/Errors.h) can be: 380 * - NO_ERROR: successful operation 381 * - INVALID_OPERATION: the AudioTrack is not stopped. 382 */ 383 status_t reload(); 384 385 /* Returns a handle on the audio output used by this AudioTrack. 386 * 387 * Parameters: 388 * none. 389 * 390 * Returned value: 391 * handle on audio hardware output 392 */ 393 audio_io_handle_t getOutput(); 394 395 /* Returns the unique session ID associated with this track. 396 * 397 * Parameters: 398 * none. 399 * 400 * Returned value: 401 * AudioTrack session ID. 402 */ 403 int getSessionId() const; 404 405 /* Attach track auxiliary output to specified effect. Use effectId = 0 406 * to detach track from effect. 407 * 408 * Parameters: 409 * 410 * effectId: effectId obtained from AudioEffect::id(). 411 * 412 * Returned status (from utils/Errors.h) can be: 413 * - NO_ERROR: successful operation 414 * - INVALID_OPERATION: the effect is not an auxiliary effect. 415 * - BAD_VALUE: The specified effect ID is invalid 416 */ 417 status_t attachAuxEffect(int effectId); 418 419 /* Obtains a buffer of "frameCount" frames. The buffer must be 420 * filled entirely, and then released with releaseBuffer(). 421 * If the track is stopped, obtainBuffer() returns 422 * STOPPED instead of NO_ERROR as long as there are buffers available, 423 * at which point NO_MORE_BUFFERS is returned. 424 * Buffers will be returned until the pool 425 * is exhausted, at which point obtainBuffer() will either block 426 * or return WOULD_BLOCK depending on the value of the "blocking" 427 * parameter. 428 * 429 * Interpretation of waitCount: 430 * +n limits wait time to n * WAIT_PERIOD_MS, 431 * -1 causes an (almost) infinite wait time, 432 * 0 non-blocking. 433 */ 434 435 enum { 436 NO_MORE_BUFFERS = 0x80000001, // same name in AudioFlinger.h, ok to be different value 437 STOPPED = 1 438 }; 439 440 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount); 441 442 /* Release a filled buffer of "frameCount" frames for AudioFlinger to process. */ 443 void releaseBuffer(Buffer* audioBuffer); 444 445 /* As a convenience we provide a write() interface to the audio buffer. 446 * This is implemented on top of obtainBuffer/releaseBuffer. For best 447 * performance use callbacks. Returns actual number of bytes written >= 0, 448 * or one of the following negative status codes: 449 * INVALID_OPERATION AudioTrack is configured for shared buffer mode 450 * BAD_VALUE size is invalid 451 * STOPPED AudioTrack was stopped during the write 452 * NO_MORE_BUFFERS when obtainBuffer() returns same 453 * or any other error code returned by IAudioTrack::start() or restoreTrack_l(). 454 */ 455 ssize_t write(const void* buffer, size_t size); 456 457 /* 458 * Dumps the state of an audio track. 459 */ 460 status_t dump(int fd, const Vector<String16>& args) const; 461 462protected: 463 /* copying audio tracks is not allowed */ 464 AudioTrack(const AudioTrack& other); 465 AudioTrack& operator = (const AudioTrack& other); 466 467 /* a small internal class to handle the callback */ 468 class AudioTrackThread : public Thread 469 { 470 public: 471 AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false); 472 473 // Do not call Thread::requestExitAndWait() without first calling requestExit(). 474 // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough. 475 virtual void requestExit(); 476 477 void pause(); // suspend thread from execution at next loop boundary 478 void resume(); // allow thread to execute, if not requested to exit 479 480 private: 481 friend class AudioTrack; 482 virtual bool threadLoop(); 483 AudioTrack& mReceiver; 484 ~AudioTrackThread(); 485 Mutex mMyLock; // Thread::mLock is private 486 Condition mMyCond; // Thread::mThreadExitedCondition is private 487 bool mPaused; // whether thread is currently paused 488 }; 489 490 // body of AudioTrackThread::threadLoop() 491 bool processAudioBuffer(const sp<AudioTrackThread>& thread); 492 493 status_t createTrack_l(audio_stream_type_t streamType, 494 uint32_t sampleRate, 495 audio_format_t format, 496 audio_channel_mask_t channelMask, 497 int frameCount, 498 audio_output_flags_t flags, 499 const sp<IMemory>& sharedBuffer, 500 audio_io_handle_t output); 501 void flush_l(); 502 status_t setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount); 503 audio_io_handle_t getOutput_l(); 504 status_t restoreTrack_l(audio_track_cblk_t*& cblk, bool fromStart); 505 bool stopped_l() const { return !mActive; } 506 507 sp<IAudioTrack> mAudioTrack; 508 sp<IMemory> mCblkMemory; 509 sp<AudioTrackThread> mAudioTrackThread; 510 511 float mVolume[2]; 512 float mSendLevel; 513 uint32_t mFrameCount; 514 515 audio_track_cblk_t* mCblk; 516 audio_format_t mFormat; 517 audio_stream_type_t mStreamType; 518 uint8_t mChannelCount; 519 uint8_t mMuted; 520 uint8_t mReserved; 521 audio_channel_mask_t mChannelMask; 522 status_t mStatus; 523 uint32_t mLatency; 524 525 bool mActive; // protected by mLock 526 527 callback_t mCbf; // callback handler for events, or NULL 528 void* mUserData; // for client callback handler 529 530 // for notification APIs 531 uint32_t mNotificationFramesReq; // requested number of frames between each 532 // notification callback 533 uint32_t mNotificationFramesAct; // actual number of frames between each 534 // notification callback 535 sp<IMemory> mSharedBuffer; 536 int mLoopCount; 537 uint32_t mRemainingFrames; 538 uint32_t mMarkerPosition; // in frames 539 bool mMarkerReached; 540 uint32_t mNewPosition; // in frames 541 uint32_t mUpdatePeriod; // in frames 542 543 bool mFlushed; // FIXME will be made obsolete by making flush() synchronous 544 audio_output_flags_t mFlags; 545 int mSessionId; 546 int mAuxEffectId; 547 mutable Mutex mLock; 548 status_t mRestoreStatus; 549 bool mIsTimed; 550 int mPreviousPriority; // before start() 551 SchedPolicy mPreviousSchedulingGroup; 552}; 553 554class TimedAudioTrack : public AudioTrack 555{ 556public: 557 TimedAudioTrack(); 558 559 /* allocate a shared memory buffer that can be passed to queueTimedBuffer */ 560 status_t allocateTimedBuffer(size_t size, sp<IMemory>* buffer); 561 562 /* queue a buffer obtained via allocateTimedBuffer for playback at the 563 given timestamp. PTS units are microseconds on the media time timeline. 564 The media time transform (set with setMediaTimeTransform) set by the 565 audio producer will handle converting from media time to local time 566 (perhaps going through the common time timeline in the case of 567 synchronized multiroom audio case) */ 568 status_t queueTimedBuffer(const sp<IMemory>& buffer, int64_t pts); 569 570 /* define a transform between media time and either common time or 571 local time */ 572 enum TargetTimeline {LOCAL_TIME, COMMON_TIME}; 573 status_t setMediaTimeTransform(const LinearTransform& xform, 574 TargetTimeline target); 575}; 576 577}; // namespace android 578 579#endif // ANDROID_AUDIOTRACK_H 580