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