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