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