AudioTrack.h revision ad3af3305f024bcbbd55c894a4995e449498e1ba
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 <cutils/sched_policy.h> 21#include <media/AudioSystem.h> 22#include <media/IAudioTrack.h> 23#include <utils/threads.h> 24 25namespace android { 26 27// ---------------------------------------------------------------------------- 28 29class audio_track_cblk_t; 30class AudioTrackClientProxy; 31class StaticAudioTrackClientProxy; 32 33// ---------------------------------------------------------------------------- 34 35class AudioTrack : public RefBase 36{ 37public: 38 enum channel_index { 39 MONO = 0, 40 LEFT = 0, 41 RIGHT = 1 42 }; 43 44 /* Events used by AudioTrack callback function (callback_t). 45 * Keep in sync with frameworks/base/media/java/android/media/AudioTrack.java NATIVE_EVENT_*. 46 */ 47 enum event_type { 48 EVENT_MORE_DATA = 0, // Request to write more data to buffer. 49 // If this event is delivered but the callback handler 50 // does not want to write more data, the handler must explicitly 51 // ignore the event by setting frameCount to zero. 52 EVENT_UNDERRUN = 1, // Buffer underrun occurred. 53 EVENT_LOOP_END = 2, // Sample loop end was reached; playback restarted from 54 // loop start if loop count was not 0. 55 EVENT_MARKER = 3, // Playback head is at the specified marker position 56 // (See setMarkerPosition()). 57 EVENT_NEW_POS = 4, // Playback head is at a new position 58 // (See setPositionUpdatePeriod()). 59 EVENT_BUFFER_END = 5, // Playback head is at the end of the buffer. 60 // Not currently used by android.media.AudioTrack. 61 EVENT_NEW_IAUDIOTRACK = 6, // IAudioTrack was re-created, either due to re-routing and 62 // voluntary invalidation by mediaserver, or mediaserver crash. 63 EVENT_STREAM_END = 7, // Sent after all the buffers queued in AF and HW are played 64 // back (after stop is called) 65 }; 66 67 /* Client should declare Buffer on the stack and pass address to obtainBuffer() 68 * and releaseBuffer(). See also callback_t for EVENT_MORE_DATA. 69 */ 70 71 class Buffer 72 { 73 public: 74 // FIXME use m prefix 75 size_t frameCount; // number of sample frames corresponding to size; 76 // on input it is the number of frames desired, 77 // on output is the number of frames actually filled 78 79 size_t size; // input/output in bytes == frameCount * frameSize 80 // FIXME this is redundant with respect to frameCount, 81 // and TRANSFER_OBTAIN mode is broken for 8-bit data 82 // since we don't define the frame format 83 84 union { 85 void* raw; 86 short* i16; // signed 16-bit 87 int8_t* i8; // unsigned 8-bit, offset by 0x80 88 }; 89 }; 90 91 /* As a convenience, if a callback is supplied, a handler thread 92 * is automatically created with the appropriate priority. This thread 93 * invokes the callback when a new buffer becomes available or various conditions occur. 94 * Parameters: 95 * 96 * event: type of event notified (see enum AudioTrack::event_type). 97 * user: Pointer to context for use by the callback receiver. 98 * info: Pointer to optional parameter according to event type: 99 * - EVENT_MORE_DATA: pointer to AudioTrack::Buffer struct. The callback must not write 100 * more bytes than indicated by 'size' field and update 'size' if fewer bytes are 101 * written. 102 * - EVENT_UNDERRUN: unused. 103 * - EVENT_LOOP_END: pointer to an int indicating the number of loops remaining. 104 * - EVENT_MARKER: pointer to const uint32_t containing the marker position in frames. 105 * - EVENT_NEW_POS: pointer to const uint32_t containing the new position in frames. 106 * - EVENT_BUFFER_END: unused. 107 * - EVENT_NEW_IAUDIOTRACK: unused. 108 */ 109 110 typedef void (*callback_t)(int event, void* user, void *info); 111 112 /* Returns the minimum frame count required for the successful creation of 113 * an AudioTrack object. 114 * Returned status (from utils/Errors.h) can be: 115 * - NO_ERROR: successful operation 116 * - NO_INIT: audio server or audio hardware not initialized 117 */ 118 119 static status_t getMinFrameCount(size_t* frameCount, 120 audio_stream_type_t streamType, 121 uint32_t sampleRate); 122 123 /* How data is transferred to AudioTrack 124 */ 125 enum transfer_type { 126 TRANSFER_DEFAULT, // not specified explicitly; determine from the other parameters 127 TRANSFER_CALLBACK, // callback EVENT_MORE_DATA 128 TRANSFER_OBTAIN, // FIXME deprecated: call obtainBuffer() and releaseBuffer() 129 TRANSFER_SYNC, // synchronous write() 130 TRANSFER_SHARED, // shared memory 131 }; 132 133 /* Constructs an uninitialized AudioTrack. No connection with 134 * AudioFlinger takes place. Use set() after this. 135 */ 136 AudioTrack(); 137 138 /* Creates an AudioTrack object and registers it with AudioFlinger. 139 * Once created, the track needs to be started before it can be used. 140 * Unspecified values are set to appropriate default values. 141 * With this constructor, the track is configured for streaming mode. 142 * Data to be rendered is supplied by write() or by the callback EVENT_MORE_DATA. 143 * Intermixing a combination of write() and non-ignored EVENT_MORE_DATA is not allowed. 144 * 145 * Parameters: 146 * 147 * streamType: Select the type of audio stream this track is attached to 148 * (e.g. AUDIO_STREAM_MUSIC). 149 * sampleRate: Data source sampling rate in Hz. 150 * format: Audio format (e.g AUDIO_FORMAT_PCM_16_BIT for signed 151 * 16 bits per sample). 152 * channelMask: Channel mask. 153 * frameCount: Minimum size of track PCM buffer in frames. This defines the 154 * application's contribution to the 155 * latency of the track. The actual size selected by the AudioTrack could be 156 * larger if the requested size is not compatible with current audio HAL 157 * configuration. Zero means to use a default value. 158 * flags: See comments on audio_output_flags_t in <system/audio.h>. 159 * cbf: Callback function. If not null, this function is called periodically 160 * to provide new data and inform of marker, position updates, etc. 161 * user: Context for use by the callback receiver. 162 * notificationFrames: The callback function is called each time notificationFrames PCM 163 * frames have been consumed from track input buffer. 164 * This is expressed in units of frames at the initial source sample rate. 165 * sessionId: Specific session ID, or zero to use default. 166 * transferType: How data is transferred to AudioTrack. 167 * threadCanCallJava: Not present in parameter list, and so is fixed at false. 168 */ 169 170 AudioTrack( audio_stream_type_t streamType, 171 uint32_t sampleRate = 0, 172 audio_format_t format = AUDIO_FORMAT_DEFAULT, 173 audio_channel_mask_t channelMask = 0, 174 int frameCount = 0, 175 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 176 callback_t cbf = NULL, 177 void* user = NULL, 178 int notificationFrames = 0, 179 int sessionId = 0, 180 transfer_type transferType = TRANSFER_DEFAULT, 181 const audio_offload_info_t *offloadInfo = NULL); 182 183 /* Creates an audio track and registers it with AudioFlinger. 184 * With this constructor, the track is configured for static buffer mode. 185 * The format must not be 8-bit linear PCM. 186 * Data to be rendered is passed in a shared memory buffer 187 * identified by the argument sharedBuffer, which must be non-0. 188 * The memory should be initialized to the desired data before calling start(). 189 * The write() method is not supported in this case. 190 * It is recommended to pass a callback function to be notified of playback end by an 191 * EVENT_UNDERRUN event. 192 */ 193 194 AudioTrack( audio_stream_type_t streamType, 195 uint32_t sampleRate = 0, 196 audio_format_t format = AUDIO_FORMAT_DEFAULT, 197 audio_channel_mask_t channelMask = 0, 198 const sp<IMemory>& sharedBuffer = 0, 199 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 200 callback_t cbf = NULL, 201 void* user = NULL, 202 int notificationFrames = 0, 203 int sessionId = 0, 204 transfer_type transferType = TRANSFER_DEFAULT, 205 const audio_offload_info_t *offloadInfo = NULL); 206 207 /* Terminates the AudioTrack and unregisters it from AudioFlinger. 208 * Also destroys all resources associated with the AudioTrack. 209 */ 210protected: 211 virtual ~AudioTrack(); 212public: 213 214 /* Initialize an AudioTrack that was created using the AudioTrack() constructor. 215 * Don't call set() more than once, or after the AudioTrack() constructors that take parameters. 216 * Returned status (from utils/Errors.h) can be: 217 * - NO_ERROR: successful initialization 218 * - INVALID_OPERATION: AudioTrack is already initialized 219 * - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...) 220 * - NO_INIT: audio server or audio hardware not initialized 221 * If sharedBuffer is non-0, the frameCount parameter is ignored and 222 * replaced by the shared buffer's total allocated size in frame units. 223 * 224 * Parameters not listed in the AudioTrack constructors above: 225 * 226 * threadCanCallJava: Whether callbacks are made from an attached thread and thus can call JNI. 227 */ 228 status_t set(audio_stream_type_t streamType = AUDIO_STREAM_DEFAULT, 229 uint32_t sampleRate = 0, 230 audio_format_t format = AUDIO_FORMAT_DEFAULT, 231 audio_channel_mask_t channelMask = 0, 232 int frameCount = 0, 233 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 234 callback_t cbf = NULL, 235 void* user = NULL, 236 int notificationFrames = 0, 237 const sp<IMemory>& sharedBuffer = 0, 238 bool threadCanCallJava = false, 239 int sessionId = 0, 240 transfer_type transferType = TRANSFER_DEFAULT, 241 const audio_offload_info_t *offloadInfo = NULL); 242 243 /* Result of constructing the AudioTrack. This must be checked 244 * before using any AudioTrack API (except for set()), because using 245 * an uninitialized AudioTrack produces undefined results. 246 * See set() method above for possible return codes. 247 */ 248 status_t initCheck() const { return mStatus; } 249 250 /* Returns this track's estimated latency in milliseconds. 251 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any) 252 * and audio hardware driver. 253 */ 254 uint32_t latency() const { return mLatency; } 255 256 /* getters, see constructors and set() */ 257 258 audio_stream_type_t streamType() const { return mStreamType; } 259 audio_format_t format() const { return mFormat; } 260 261 /* Return frame size in bytes, which for linear PCM is 262 * channelCount * (bit depth per channel / 8). 263 * channelCount is determined from channelMask, and bit depth comes from format. 264 * For non-linear formats, the frame size is typically 1 byte. 265 */ 266 size_t frameSize() const { return mFrameSize; } 267 268 uint32_t channelCount() const { return mChannelCount; } 269 uint32_t frameCount() const { return mFrameCount; } 270 271 /* Return the static buffer specified in constructor or set(), or 0 for streaming mode */ 272 sp<IMemory> sharedBuffer() const { return mSharedBuffer; } 273 274 /* After it's created the track is not active. Call start() to 275 * make it active. If set, the callback will start being called. 276 * If the track was previously paused, volume is ramped up over the first mix buffer. 277 */ 278 void start(); 279 280 /* Stop a track. 281 * In static buffer mode, the track is stopped immediately. 282 * In streaming mode, the callback will cease being called. Note that obtainBuffer() still 283 * works and will fill up buffers until the pool is exhausted, and then will return WOULD_BLOCK. 284 * In streaming mode the stop does not occur immediately: any data remaining in the buffer 285 * is first drained, mixed, and output, and only then is the track marked as stopped. 286 */ 287 void stop(); 288 bool stopped() const; 289 290 /* Flush a stopped or paused track. All previously buffered data is discarded immediately. 291 * This has the effect of draining the buffers without mixing or output. 292 * Flush is intended for streaming mode, for example before switching to non-contiguous content. 293 * This function is a no-op if the track is not stopped or paused, or uses a static buffer. 294 */ 295 void flush(); 296 297 /* Pause a track. After pause, the callback will cease being called and 298 * obtainBuffer returns WOULD_BLOCK. Note that obtainBuffer() still works 299 * and will fill up buffers until the pool is exhausted. 300 * Volume is ramped down over the next mix buffer following the pause request, 301 * and then the track is marked as paused. It can be resumed with ramp up by start(). 302 */ 303 void pause(); 304 305 /* Set volume for this track, mostly used for games' sound effects 306 * left and right volumes. Levels must be >= 0.0 and <= 1.0. 307 * This is the older API. New applications should use setVolume(float) when possible. 308 */ 309 status_t setVolume(float left, float right); 310 311 /* Set volume for all channels. This is the preferred API for new applications, 312 * especially for multi-channel content. 313 */ 314 status_t setVolume(float volume); 315 316 /* Set the send level for this track. An auxiliary effect should be attached 317 * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0. 318 */ 319 status_t setAuxEffectSendLevel(float level); 320 void getAuxEffectSendLevel(float* level) const; 321 322 /* Set source sample rate for this track in Hz, mostly used for games' sound effects 323 */ 324 status_t setSampleRate(uint32_t sampleRate); 325 326 /* Return current source sample rate in Hz, or 0 if unknown */ 327 uint32_t getSampleRate() const; 328 329 /* Enables looping and sets the start and end points of looping. 330 * Only supported for static buffer mode. 331 * 332 * FIXME The comments below are for the new planned interpretation which is not yet implemented. 333 * Currently the legacy behavior is still implemented, where loopStart and loopEnd 334 * are in wrapping (overflow) frame units like the return value of getPosition(). 335 * The plan is to fix all callers to use the new version at same time implementation changes. 336 * 337 * Parameters: 338 * 339 * loopStart: loop start in frames relative to start of buffer. 340 * loopEnd: loop end in frames relative to start of buffer. 341 * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any 342 * pending or active loop. loopCount == -1 means infinite looping. 343 * 344 * For proper operation the following condition must be respected: 345 * loopCount != 0 implies 0 <= loopStart < loopEnd <= frameCount(). 346 * 347 * If the loop period (loopEnd - loopStart) is too small for the implementation to support, 348 * setLoop() will return BAD_VALUE. loopCount must be >= -1. 349 * 350 */ 351 status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount); 352 353 /* Sets marker position. When playback reaches the number of frames specified, a callback with 354 * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker 355 * notification callback. To set a marker at a position which would compute as 0, 356 * a workaround is to the set the marker at a nearby position such as ~0 or 1. 357 * If the AudioTrack has been opened with no callback function associated, the operation will 358 * fail. 359 * 360 * Parameters: 361 * 362 * marker: marker position expressed in wrapping (overflow) frame units, 363 * like the return value of getPosition(). 364 * 365 * Returned status (from utils/Errors.h) can be: 366 * - NO_ERROR: successful operation 367 * - INVALID_OPERATION: the AudioTrack has no callback installed. 368 */ 369 status_t setMarkerPosition(uint32_t marker); 370 status_t getMarkerPosition(uint32_t *marker) const; 371 372 /* Sets position update period. Every time the number of frames specified has been played, 373 * a callback with event type EVENT_NEW_POS is called. 374 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 375 * callback. 376 * If the AudioTrack has been opened with no callback function associated, the operation will 377 * fail. 378 * Extremely small values may be rounded up to a value the implementation can support. 379 * 380 * Parameters: 381 * 382 * updatePeriod: position update notification period expressed in frames. 383 * 384 * Returned status (from utils/Errors.h) can be: 385 * - NO_ERROR: successful operation 386 * - INVALID_OPERATION: the AudioTrack has no callback installed. 387 */ 388 status_t setPositionUpdatePeriod(uint32_t updatePeriod); 389 status_t getPositionUpdatePeriod(uint32_t *updatePeriod) const; 390 391 /* Sets playback head position. 392 * Only supported for static buffer mode. 393 * 394 * FIXME The comments below are for the new planned interpretation which is not yet implemented. 395 * Currently the legacy behavior is still implemented, where the new position 396 * is in wrapping (overflow) frame units like the return value of getPosition(). 397 * The plan is to fix all callers to use the new version at same time implementation changes. 398 * 399 * Parameters: 400 * 401 * position: New playback head position in frames relative to start of buffer. 402 * 0 <= position <= frameCount(). Note that end of buffer is permitted, 403 * but will result in an immediate underrun if started. 404 * 405 * Returned status (from utils/Errors.h) can be: 406 * - NO_ERROR: successful operation 407 * - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode. 408 * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack 409 * buffer 410 */ 411 status_t setPosition(uint32_t position); 412 413 /* Return the total number of frames played since playback start. 414 * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz. 415 * It is reset to zero by flush(), reload(), and stop(). 416 * 417 * Parameters: 418 * 419 * position: Address where to return play head position. 420 * 421 * Returned status (from utils/Errors.h) can be: 422 * - NO_ERROR: successful operation 423 * - BAD_VALUE: position is NULL 424 */ 425 status_t getPosition(uint32_t *position) const; 426 427 /* For static buffer mode only, this returns the current playback position in frames 428 * relative to start of buffer. It is analogous to the new API for 429 * setLoop() and setPosition(). After underrun, the position will be at end of buffer. 430 */ 431 status_t getBufferPosition(uint32_t *position); 432 433 /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids 434 * rewriting the buffer before restarting playback after a stop. 435 * This method must be called with the AudioTrack in paused or stopped state. 436 * Not allowed in streaming mode. 437 * 438 * Returned status (from utils/Errors.h) can be: 439 * - NO_ERROR: successful operation 440 * - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode. 441 */ 442 status_t reload(); 443 444 /* Returns a handle on the audio output used by this AudioTrack. 445 * 446 * Parameters: 447 * none. 448 * 449 * Returned value: 450 * handle on audio hardware output 451 */ 452 audio_io_handle_t getOutput(); 453 454 /* Returns the unique session ID associated with this track. 455 * 456 * Parameters: 457 * none. 458 * 459 * Returned value: 460 * AudioTrack session ID. 461 */ 462 int getSessionId() const { return mSessionId; } 463 464 /* Attach track auxiliary output to specified effect. Use effectId = 0 465 * to detach track from effect. 466 * 467 * Parameters: 468 * 469 * effectId: effectId obtained from AudioEffect::id(). 470 * 471 * Returned status (from utils/Errors.h) can be: 472 * - NO_ERROR: successful operation 473 * - INVALID_OPERATION: the effect is not an auxiliary effect. 474 * - BAD_VALUE: The specified effect ID is invalid 475 */ 476 status_t attachAuxEffect(int effectId); 477 478 /* Obtains a buffer of up to "audioBuffer->frameCount" empty slots for frames. 479 * After filling these slots with data, the caller should release them with releaseBuffer(). 480 * If the track buffer is not full, obtainBuffer() returns as many contiguous 481 * [empty slots for] frames as are available immediately. 482 * If the track buffer is full and track is stopped, obtainBuffer() returns WOULD_BLOCK 483 * regardless of the value of waitCount. 484 * If the track buffer is full and track is not stopped, obtainBuffer() blocks with a 485 * maximum timeout based on waitCount; see chart below. 486 * Buffers will be returned until the pool 487 * is exhausted, at which point obtainBuffer() will either block 488 * or return WOULD_BLOCK depending on the value of the "waitCount" 489 * parameter. 490 * Each sample is 16-bit signed PCM. 491 * 492 * obtainBuffer() and releaseBuffer() are deprecated for direct use by applications, 493 * which should use write() or callback EVENT_MORE_DATA instead. 494 * 495 * Interpretation of waitCount: 496 * +n limits wait time to n * WAIT_PERIOD_MS, 497 * -1 causes an (almost) infinite wait time, 498 * 0 non-blocking. 499 * 500 * Buffer fields 501 * On entry: 502 * frameCount number of frames requested 503 * After error return: 504 * frameCount 0 505 * size 0 506 * raw undefined 507 * After successful return: 508 * frameCount actual number of frames available, <= number requested 509 * size actual number of bytes available 510 * raw pointer to the buffer 511 */ 512 513 /* FIXME Deprecated public API for TRANSFER_OBTAIN mode */ 514 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount) 515 __attribute__((__deprecated__)); 516 517private: 518 /* New internal API 519 * If nonContig is non-NULL, it is an output parameter that will be set to the number of 520 * additional non-contiguous frames that are available immediately. 521 * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(), 522 * in case the requested amount of frames is in two or more non-contiguous regions. 523 * FIXME requested and elapsed are both relative times. Consider changing to absolute time. 524 */ 525 status_t obtainBuffer(Buffer* audioBuffer, const struct timespec *requested, 526 struct timespec *elapsed = NULL, size_t *nonContig = NULL); 527public: 528 529//EL_FIXME to be reconciled with new obtainBuffer() return codes and control block proxy 530// enum { 531// NO_MORE_BUFFERS = 0x80000001, // same name in AudioFlinger.h, ok to be different value 532// TEAR_DOWN = 0x80000002, 533// STOPPED = 1, 534// STREAM_END_WAIT, 535// STREAM_END 536// }; 537 538 /* Release a filled buffer of "audioBuffer->frameCount" frames for AudioFlinger to process. */ 539 // FIXME make private when obtainBuffer() for TRANSFER_OBTAIN is removed 540 void releaseBuffer(Buffer* audioBuffer); 541 542 /* As a convenience we provide a write() interface to the audio buffer. 543 * Input parameter 'size' is in byte units. 544 * This is implemented on top of obtainBuffer/releaseBuffer. For best 545 * performance use callbacks. Returns actual number of bytes written >= 0, 546 * or one of the following negative status codes: 547 * INVALID_OPERATION AudioTrack is configured for shared buffer mode 548 * BAD_VALUE size is invalid 549 * WOULD_BLOCK when obtainBuffer() returns same, or 550 * AudioTrack was stopped during the write 551 * or any other error code returned by IAudioTrack::start() or restoreTrack_l(). 552 * Not supported for static buffer mode. 553 */ 554 ssize_t write(const void* buffer, size_t size); 555 556 /* 557 * Dumps the state of an audio track. 558 */ 559 status_t dump(int fd, const Vector<String16>& args) const; 560 561 /* 562 * Return the total number of frames which AudioFlinger desired but were unavailable, 563 * and thus which resulted in an underrun. Reset to zero by stop(). 564 */ 565 uint32_t getUnderrunFrames() const; 566 567 /* Get the flags */ 568 audio_output_flags_t getFlags() const { return mFlags; } 569 570 /* Set parameters - only possible when using direct output */ 571 status_t setParameters(const String8& keyValuePairs); 572 573 /* Get parameters */ 574 String8 getParameters(const String8& keys); 575 576protected: 577 /* copying audio tracks is not allowed */ 578 AudioTrack(const AudioTrack& other); 579 AudioTrack& operator = (const AudioTrack& other); 580 581 /* a small internal class to handle the callback */ 582 class AudioTrackThread : public Thread 583 { 584 public: 585 AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false); 586 587 // Do not call Thread::requestExitAndWait() without first calling requestExit(). 588 // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough. 589 virtual void requestExit(); 590 591 void pause(); // suspend thread from execution at next loop boundary 592 void resume(); // allow thread to execute, if not requested to exit 593 void pauseConditional(); 594 // like pause(), but only if prior resume() wasn't latched 595 596 private: 597 friend class AudioTrack; 598 virtual bool threadLoop(); 599 AudioTrack& mReceiver; 600 virtual ~AudioTrackThread(); 601 Mutex mMyLock; // Thread::mLock is private 602 Condition mMyCond; // Thread::mThreadExitedCondition is private 603 bool mPaused; // whether thread is currently paused 604 bool mResumeLatch; // whether next pauseConditional() will be a nop 605 }; 606 607 // body of AudioTrackThread::threadLoop() 608 // returns the maximum amount of time before we would like to run again, where: 609 // 0 immediately 610 // > 0 no later than this many nanoseconds from now 611 // NS_WHENEVER still active but no particular deadline 612 // NS_INACTIVE inactive so don't run again until re-started 613 // NS_NEVER never again 614 static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3; 615 nsecs_t processAudioBuffer(const sp<AudioTrackThread>& thread); 616 status_t processStreamEnd(int32_t waitCount); 617 618 619 // caller must hold lock on mLock for all _l methods 620 621 status_t createTrack_l(audio_stream_type_t streamType, 622 uint32_t sampleRate, 623 audio_format_t format, 624 size_t frameCount, 625 audio_output_flags_t flags, 626 const sp<IMemory>& sharedBuffer, 627 audio_io_handle_t output, 628 size_t epoch); 629 630 // can only be called when mState != STATE_ACTIVE 631 void flush_l(); 632 633 void setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount); 634 audio_io_handle_t getOutput_l(); 635 636 status_t getPosition_l(uint32_t *position); 637 638 // FIXME enum is faster than strcmp() for parameter 'from' 639 status_t restoreTrack_l(const char *from); 640 641 // may be changed if IAudioTrack is re-created 642 sp<IAudioTrack> mAudioTrack; 643 sp<IMemory> mCblkMemory; 644 audio_track_cblk_t* mCblk; // re-load after mLock.unlock() 645 646 sp<AudioTrackThread> mAudioTrackThread; 647 float mVolume[2]; 648 float mSendLevel; 649 uint32_t mSampleRate; 650 size_t mFrameCount; // corresponds to current IAudioTrack 651 size_t mReqFrameCount; // frame count to request the next time a new 652 // IAudioTrack is needed 653 654 655 // constant after constructor or set() 656 audio_format_t mFormat; // as requested by client, not forced to 16-bit 657 audio_stream_type_t mStreamType; 658 uint32_t mChannelCount; 659 audio_channel_mask_t mChannelMask; 660 transfer_type mTransfer; 661 662 // mFrameSize is equal to mFrameSizeAF for non-PCM or 16-bit PCM data. For 8-bit PCM data, it's 663 // twice as large as mFrameSize because data is expanded to 16-bit before it's stored in buffer. 664 size_t mFrameSize; // app-level frame size 665 size_t mFrameSizeAF; // AudioFlinger frame size 666 667 status_t mStatus; 668 669 // can change dynamically when IAudioTrack invalidated 670 uint32_t mLatency; // in ms 671 672 // Indicates the current track state. Protected by mLock. 673 enum State { 674 STATE_ACTIVE, 675 STATE_STOPPED, 676 STATE_PAUSED, 677 STATE_FLUSHED, 678 } mState; 679 680 callback_t mCbf; // callback handler for events, or NULL 681 void* mUserData; // for client callback handler 682 683 // for notification APIs 684 uint32_t mNotificationFramesReq; // requested number of frames between each 685 // notification callback, 686 // at initial source sample rate 687 uint32_t mNotificationFramesAct; // actual number of frames between each 688 // notification callback, 689 // at initial source sample rate 690 bool mRefreshRemaining; // processAudioBuffer() should refresh next 2 691 692 // These are private to processAudioBuffer(), and are not protected by a lock 693 uint32_t mRemainingFrames; // number of frames to request in obtainBuffer() 694 bool mRetryOnPartialBuffer; // sleep and retry after partial obtainBuffer() 695 int mObservedSequence; // last observed value of mSequence 696 697 sp<IMemory> mSharedBuffer; 698 uint32_t mLoopPeriod; // in frames, zero means looping is disabled 699 uint32_t mMarkerPosition; // in wrapping (overflow) frame units 700 bool mMarkerReached; 701 uint32_t mNewPosition; // in frames 702 uint32_t mUpdatePeriod; // in frames, zero means no EVENT_NEW_POS 703 704 audio_output_flags_t mFlags; 705 int mSessionId; 706 int mAuxEffectId; 707 708 mutable Mutex mLock; 709 710 bool mIsTimed; 711 int mPreviousPriority; // before start() 712 SchedPolicy mPreviousSchedulingGroup; 713 bool mAwaitBoost; // thread should wait for priority boost before running 714 715 // The proxy should only be referenced while a lock is held because the proxy isn't 716 // multi-thread safe, especially the SingleStateQueue part of the proxy. 717 // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock, 718 // provided that the caller also holds an extra reference to the proxy and shared memory to keep 719 // them around in case they are replaced during the obtainBuffer(). 720 sp<StaticAudioTrackClientProxy> mStaticProxy; // for type safety only 721 sp<AudioTrackClientProxy> mProxy; // primary owner of the memory 722 723 bool mInUnderrun; // whether track is currently in underrun state 724 725private: 726 class DeathNotifier : public IBinder::DeathRecipient { 727 public: 728 DeathNotifier(AudioTrack* audioTrack) : mAudioTrack(audioTrack) { } 729 protected: 730 virtual void binderDied(const wp<IBinder>& who); 731 private: 732 const wp<AudioTrack> mAudioTrack; 733 }; 734 735 sp<DeathNotifier> mDeathNotifier; 736 uint32_t mSequence; // incremented for each new IAudioTrack attempt 737}; 738 739class TimedAudioTrack : public AudioTrack 740{ 741public: 742 TimedAudioTrack(); 743 744 /* allocate a shared memory buffer that can be passed to queueTimedBuffer */ 745 status_t allocateTimedBuffer(size_t size, sp<IMemory>* buffer); 746 747 /* queue a buffer obtained via allocateTimedBuffer for playback at the 748 given timestamp. PTS units are microseconds on the media time timeline. 749 The media time transform (set with setMediaTimeTransform) set by the 750 audio producer will handle converting from media time to local time 751 (perhaps going through the common time timeline in the case of 752 synchronized multiroom audio case) */ 753 status_t queueTimedBuffer(const sp<IMemory>& buffer, int64_t pts); 754 755 /* define a transform between media time and either common time or 756 local time */ 757 enum TargetTimeline {LOCAL_TIME, COMMON_TIME}; 758 status_t setMediaTimeTransform(const LinearTransform& xform, 759 TargetTimeline target); 760}; 761 762}; // namespace android 763 764#endif // ANDROID_AUDIOTRACK_H 765