AudioTrack.h revision 8edb8dc44b8a2f81bdb5db645b6b708548771a31
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, // 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 * set() is not multi-thread safe. 242 * Returned status (from utils/Errors.h) can be: 243 * - NO_ERROR: successful initialization 244 * - INVALID_OPERATION: AudioTrack is already initialized 245 * - BAD_VALUE: invalid parameter (channelMask, format, sampleRate...) 246 * - NO_INIT: audio server or audio hardware not initialized 247 * If status is not equal to NO_ERROR, don't call any other APIs on this AudioTrack. 248 * If sharedBuffer is non-0, the frameCount parameter is ignored and 249 * replaced by the shared buffer's total allocated size in frame units. 250 * 251 * Parameters not listed in the AudioTrack constructors above: 252 * 253 * threadCanCallJava: Whether callbacks are made from an attached thread and thus can call JNI. 254 * 255 * Internal state post condition: 256 * (mStreamType == AUDIO_STREAM_DEFAULT) implies this AudioTrack has valid attributes 257 */ 258 status_t set(audio_stream_type_t streamType, 259 uint32_t sampleRate, 260 audio_format_t format, 261 audio_channel_mask_t channelMask, 262 size_t frameCount = 0, 263 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE, 264 callback_t cbf = NULL, 265 void* user = NULL, 266 uint32_t notificationFrames = 0, 267 const sp<IMemory>& sharedBuffer = 0, 268 bool threadCanCallJava = false, 269 int sessionId = AUDIO_SESSION_ALLOCATE, 270 transfer_type transferType = TRANSFER_DEFAULT, 271 const audio_offload_info_t *offloadInfo = NULL, 272 int uid = -1, 273 pid_t pid = -1, 274 const audio_attributes_t* pAttributes = NULL); 275 276 /* Result of constructing the AudioTrack. This must be checked for successful initialization 277 * before using any AudioTrack API (except for set()), because using 278 * an uninitialized AudioTrack produces undefined results. 279 * See set() method above for possible return codes. 280 */ 281 status_t initCheck() const { return mStatus; } 282 283 /* Returns this track's estimated latency in milliseconds. 284 * This includes the latency due to AudioTrack buffer size, AudioMixer (if any) 285 * and audio hardware driver. 286 */ 287 uint32_t latency() const { return mLatency; } 288 289 /* getters, see constructors and set() */ 290 291 audio_stream_type_t streamType() const; 292 audio_format_t format() const { return mFormat; } 293 294 /* Return frame size in bytes, which for linear PCM is 295 * channelCount * (bit depth per channel / 8). 296 * channelCount is determined from channelMask, and bit depth comes from format. 297 * For non-linear formats, the frame size is typically 1 byte. 298 */ 299 size_t frameSize() const { return mFrameSize; } 300 301 uint32_t channelCount() const { return mChannelCount; } 302 size_t frameCount() const { return mFrameCount; } 303 304 /* Return the static buffer specified in constructor or set(), or 0 for streaming mode */ 305 sp<IMemory> sharedBuffer() const { return mSharedBuffer; } 306 307 /* After it's created the track is not active. Call start() to 308 * make it active. If set, the callback will start being called. 309 * If the track was previously paused, volume is ramped up over the first mix buffer. 310 */ 311 status_t start(); 312 313 /* Stop a track. 314 * In static buffer mode, the track is stopped immediately. 315 * In streaming mode, the callback will cease being called. Note that obtainBuffer() still 316 * works and will fill up buffers until the pool is exhausted, and then will return WOULD_BLOCK. 317 * In streaming mode the stop does not occur immediately: any data remaining in the buffer 318 * is first drained, mixed, and output, and only then is the track marked as stopped. 319 */ 320 void stop(); 321 bool stopped() const; 322 323 /* Flush a stopped or paused track. All previously buffered data is discarded immediately. 324 * This has the effect of draining the buffers without mixing or output. 325 * Flush is intended for streaming mode, for example before switching to non-contiguous content. 326 * This function is a no-op if the track is not stopped or paused, or uses a static buffer. 327 */ 328 void flush(); 329 330 /* Pause a track. After pause, the callback will cease being called and 331 * obtainBuffer returns WOULD_BLOCK. Note that obtainBuffer() still works 332 * and will fill up buffers until the pool is exhausted. 333 * Volume is ramped down over the next mix buffer following the pause request, 334 * and then the track is marked as paused. It can be resumed with ramp up by start(). 335 */ 336 void pause(); 337 338 /* Set volume for this track, mostly used for games' sound effects 339 * left and right volumes. Levels must be >= 0.0 and <= 1.0. 340 * This is the older API. New applications should use setVolume(float) when possible. 341 */ 342 status_t setVolume(float left, float right); 343 344 /* Set volume for all channels. This is the preferred API for new applications, 345 * especially for multi-channel content. 346 */ 347 status_t setVolume(float volume); 348 349 /* Set the send level for this track. An auxiliary effect should be attached 350 * to the track with attachEffect(). Level must be >= 0.0 and <= 1.0. 351 */ 352 status_t setAuxEffectSendLevel(float level); 353 void getAuxEffectSendLevel(float* level) const; 354 355 /* Set source sample rate for this track in Hz, mostly used for games' sound effects 356 */ 357 status_t setSampleRate(uint32_t sampleRate); 358 359 /* Return current source sample rate in Hz */ 360 uint32_t getSampleRate() const; 361 362 /* Set source playback rate for timestretch 363 * 1.0 is normal speed: < 1.0 is slower, > 1.0 is faster 364 * 1.0 is normal pitch: < 1.0 is lower pitch, > 1.0 is higher pitch 365 * 366 * AUDIO_TIMESTRETCH_SPEED_MIN <= speed <= AUDIO_TIMESTRETCH_SPEED_MAX 367 * AUDIO_TIMESTRETCH_PITCH_MIN <= pitch <= AUDIO_TIMESTRETCH_PITCH_MAX 368 * 369 * Speed increases the playback rate of media, but does not alter pitch. 370 * Pitch increases the "tonal frequency" of media, but does not affect the playback rate. 371 */ 372 status_t setPlaybackRate(float speed, float pitch); 373 374 /* Return current playback rate */ 375 void getPlaybackRate(float *speed, float *pitch) const; 376 377 /* Enables looping and sets the start and end points of looping. 378 * Only supported for static buffer mode. 379 * 380 * Parameters: 381 * 382 * loopStart: loop start in frames relative to start of buffer. 383 * loopEnd: loop end in frames relative to start of buffer. 384 * loopCount: number of loops to execute. Calling setLoop() with loopCount == 0 cancels any 385 * pending or active loop. loopCount == -1 means infinite looping. 386 * 387 * For proper operation the following condition must be respected: 388 * loopCount != 0 implies 0 <= loopStart < loopEnd <= frameCount(). 389 * 390 * If the loop period (loopEnd - loopStart) is too small for the implementation to support, 391 * setLoop() will return BAD_VALUE. loopCount must be >= -1. 392 * 393 */ 394 status_t setLoop(uint32_t loopStart, uint32_t loopEnd, int loopCount); 395 396 /* Sets marker position. When playback reaches the number of frames specified, a callback with 397 * event type EVENT_MARKER is called. Calling setMarkerPosition with marker == 0 cancels marker 398 * notification callback. To set a marker at a position which would compute as 0, 399 * a workaround is to set the marker at a nearby position such as ~0 or 1. 400 * If the AudioTrack has been opened with no callback function associated, the operation will 401 * fail. 402 * 403 * Parameters: 404 * 405 * marker: marker position expressed in wrapping (overflow) frame units, 406 * like the return value of getPosition(). 407 * 408 * Returned status (from utils/Errors.h) can be: 409 * - NO_ERROR: successful operation 410 * - INVALID_OPERATION: the AudioTrack has no callback installed. 411 */ 412 status_t setMarkerPosition(uint32_t marker); 413 status_t getMarkerPosition(uint32_t *marker) const; 414 415 /* Sets position update period. Every time the number of frames specified has been played, 416 * a callback with event type EVENT_NEW_POS is called. 417 * Calling setPositionUpdatePeriod with updatePeriod == 0 cancels new position notification 418 * callback. 419 * If the AudioTrack has been opened with no callback function associated, the operation will 420 * fail. 421 * Extremely small values may be rounded up to a value the implementation can support. 422 * 423 * Parameters: 424 * 425 * updatePeriod: position update notification period expressed in frames. 426 * 427 * Returned status (from utils/Errors.h) can be: 428 * - NO_ERROR: successful operation 429 * - INVALID_OPERATION: the AudioTrack has no callback installed. 430 */ 431 status_t setPositionUpdatePeriod(uint32_t updatePeriod); 432 status_t getPositionUpdatePeriod(uint32_t *updatePeriod) const; 433 434 /* Sets playback head position. 435 * Only supported for static buffer mode. 436 * 437 * Parameters: 438 * 439 * position: New playback head position in frames relative to start of buffer. 440 * 0 <= position <= frameCount(). Note that end of buffer is permitted, 441 * but will result in an immediate underrun if started. 442 * 443 * Returned status (from utils/Errors.h) can be: 444 * - NO_ERROR: successful operation 445 * - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode. 446 * - BAD_VALUE: The specified position is beyond the number of frames present in AudioTrack 447 * buffer 448 */ 449 status_t setPosition(uint32_t position); 450 451 /* Return the total number of frames played since playback start. 452 * The counter will wrap (overflow) periodically, e.g. every ~27 hours at 44.1 kHz. 453 * It is reset to zero by flush(), reload(), and stop(). 454 * 455 * Parameters: 456 * 457 * position: Address where to return play head position. 458 * 459 * Returned status (from utils/Errors.h) can be: 460 * - NO_ERROR: successful operation 461 * - BAD_VALUE: position is NULL 462 */ 463 status_t getPosition(uint32_t *position); 464 465 /* For static buffer mode only, this returns the current playback position in frames 466 * relative to start of buffer. It is analogous to the position units used by 467 * setLoop() and setPosition(). After underrun, the position will be at end of buffer. 468 */ 469 status_t getBufferPosition(uint32_t *position); 470 471 /* Forces AudioTrack buffer full condition. When playing a static buffer, this method avoids 472 * rewriting the buffer before restarting playback after a stop. 473 * This method must be called with the AudioTrack in paused or stopped state. 474 * Not allowed in streaming mode. 475 * 476 * Returned status (from utils/Errors.h) can be: 477 * - NO_ERROR: successful operation 478 * - INVALID_OPERATION: the AudioTrack is not stopped or paused, or is streaming mode. 479 */ 480 status_t reload(); 481 482 /* Returns a handle on the audio output used by this AudioTrack. 483 * 484 * Parameters: 485 * none. 486 * 487 * Returned value: 488 * handle on audio hardware output, or AUDIO_IO_HANDLE_NONE if the 489 * track needed to be re-created but that failed 490 */ 491private: 492 audio_io_handle_t getOutput() const; 493public: 494 495 /* Selects the audio device to use for output of this AudioTrack. A value of 496 * AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing. 497 * 498 * Parameters: 499 * The device ID of the selected device (as returned by the AudioDevicesManager API). 500 * 501 * Returned value: 502 * - NO_ERROR: successful operation 503 * TODO: what else can happen here? 504 */ 505 status_t setOutputDevice(audio_port_handle_t deviceId); 506 507 /* Returns the ID of the audio device used for output of this AudioTrack. 508 * A value of AUDIO_PORT_HANDLE_NONE indicates default (AudioPolicyManager) routing. 509 * 510 * Parameters: 511 * none. 512 */ 513 audio_port_handle_t getOutputDevice(); 514 515 /* Returns the unique session ID associated with this track. 516 * 517 * Parameters: 518 * none. 519 * 520 * Returned value: 521 * AudioTrack session ID. 522 */ 523 int getSessionId() const { return mSessionId; } 524 525 /* Attach track auxiliary output to specified effect. Use effectId = 0 526 * to detach track from effect. 527 * 528 * Parameters: 529 * 530 * effectId: effectId obtained from AudioEffect::id(). 531 * 532 * Returned status (from utils/Errors.h) can be: 533 * - NO_ERROR: successful operation 534 * - INVALID_OPERATION: the effect is not an auxiliary effect. 535 * - BAD_VALUE: The specified effect ID is invalid 536 */ 537 status_t attachAuxEffect(int effectId); 538 539 /* Public API for TRANSFER_OBTAIN mode. 540 * Obtains a buffer of up to "audioBuffer->frameCount" empty slots for frames. 541 * After filling these slots with data, the caller should release them with releaseBuffer(). 542 * If the track buffer is not full, obtainBuffer() returns as many contiguous 543 * [empty slots for] frames as are available immediately. 544 * 545 * If nonContig is non-NULL, it is an output parameter that will be set to the number of 546 * additional non-contiguous frames that are predicted to be available immediately, 547 * if the client were to release the first frames and then call obtainBuffer() again. 548 * This value is only a prediction, and needs to be confirmed. 549 * It will be set to zero for an error return. 550 * 551 * If the track buffer is full and track is stopped, obtainBuffer() returns WOULD_BLOCK 552 * regardless of the value of waitCount. 553 * If the track buffer is full and track is not stopped, obtainBuffer() blocks with a 554 * maximum timeout based on waitCount; see chart below. 555 * Buffers will be returned until the pool 556 * is exhausted, at which point obtainBuffer() will either block 557 * or return WOULD_BLOCK depending on the value of the "waitCount" 558 * parameter. 559 * 560 * Interpretation of waitCount: 561 * +n limits wait time to n * WAIT_PERIOD_MS, 562 * -1 causes an (almost) infinite wait time, 563 * 0 non-blocking. 564 * 565 * Buffer fields 566 * On entry: 567 * frameCount number of [empty slots for] frames requested 568 * size ignored 569 * raw ignored 570 * After error return: 571 * frameCount 0 572 * size 0 573 * raw undefined 574 * After successful return: 575 * frameCount actual number of [empty slots for] frames available, <= number requested 576 * size actual number of bytes available 577 * raw pointer to the buffer 578 */ 579 status_t obtainBuffer(Buffer* audioBuffer, int32_t waitCount, 580 size_t *nonContig = NULL); 581 582private: 583 /* If nonContig is non-NULL, it is an output parameter that will be set to the number of 584 * additional non-contiguous frames that are predicted to be available immediately, 585 * if the client were to release the first frames and then call obtainBuffer() again. 586 * This value is only a prediction, and needs to be confirmed. 587 * It will be set to zero for an error return. 588 * FIXME We could pass an array of Buffers instead of only one Buffer to obtainBuffer(), 589 * in case the requested amount of frames is in two or more non-contiguous regions. 590 * FIXME requested and elapsed are both relative times. Consider changing to absolute time. 591 */ 592 status_t obtainBuffer(Buffer* audioBuffer, const struct timespec *requested, 593 struct timespec *elapsed = NULL, size_t *nonContig = NULL); 594public: 595 596 /* Public API for TRANSFER_OBTAIN mode. 597 * Release a filled buffer of frames for AudioFlinger to process. 598 * 599 * Buffer fields: 600 * frameCount currently ignored but recommend to set to actual number of frames filled 601 * size actual number of bytes filled, must be multiple of frameSize 602 * raw ignored 603 */ 604 void releaseBuffer(const Buffer* audioBuffer); 605 606 /* As a convenience we provide a write() interface to the audio buffer. 607 * Input parameter 'size' is in byte units. 608 * This is implemented on top of obtainBuffer/releaseBuffer. For best 609 * performance use callbacks. Returns actual number of bytes written >= 0, 610 * or one of the following negative status codes: 611 * INVALID_OPERATION AudioTrack is configured for static buffer or streaming mode 612 * BAD_VALUE size is invalid 613 * WOULD_BLOCK when obtainBuffer() returns same, or 614 * AudioTrack was stopped during the write 615 * or any other error code returned by IAudioTrack::start() or restoreTrack_l(). 616 * Default behavior is to only return when all data has been transferred. Set 'blocking' to 617 * false for the method to return immediately without waiting to try multiple times to write 618 * the full content of the buffer. 619 */ 620 ssize_t write(const void* buffer, size_t size, bool blocking = true); 621 622 /* 623 * Dumps the state of an audio track. 624 * Not a general-purpose API; intended only for use by media player service to dump its tracks. 625 */ 626 status_t dump(int fd, const Vector<String16>& args) const; 627 628 /* 629 * Return the total number of frames which AudioFlinger desired but were unavailable, 630 * and thus which resulted in an underrun. Reset to zero by stop(). 631 */ 632 uint32_t getUnderrunFrames() const; 633 634 /* Get the flags */ 635 audio_output_flags_t getFlags() const { AutoMutex _l(mLock); return mFlags; } 636 637 /* Set parameters - only possible when using direct output */ 638 status_t setParameters(const String8& keyValuePairs); 639 640 /* Get parameters */ 641 String8 getParameters(const String8& keys); 642 643 /* Poll for a timestamp on demand. 644 * Use if EVENT_NEW_TIMESTAMP is not delivered often enough for your needs, 645 * or if you need to get the most recent timestamp outside of the event callback handler. 646 * Caution: calling this method too often may be inefficient; 647 * if you need a high resolution mapping between frame position and presentation time, 648 * consider implementing that at application level, based on the low resolution timestamps. 649 * Returns NO_ERROR if timestamp is valid. 650 * WOULD_BLOCK if called in STOPPED or FLUSHED state, or if called immediately after 651 * start/ACTIVE, when the number of frames consumed is less than the 652 * overall hardware latency to physical output. In WOULD_BLOCK cases, 653 * one might poll again, or use getPosition(), or use 0 position and 654 * current time for the timestamp. 655 * INVALID_OPERATION if called on a FastTrack, wrong state, or some other error. 656 * 657 * The timestamp parameter is undefined on return, if status is not NO_ERROR. 658 */ 659 status_t getTimestamp(AudioTimestamp& timestamp); 660 661protected: 662 /* copying audio tracks is not allowed */ 663 AudioTrack(const AudioTrack& other); 664 AudioTrack& operator = (const AudioTrack& other); 665 666 /* a small internal class to handle the callback */ 667 class AudioTrackThread : public Thread 668 { 669 public: 670 AudioTrackThread(AudioTrack& receiver, bool bCanCallJava = false); 671 672 // Do not call Thread::requestExitAndWait() without first calling requestExit(). 673 // Thread::requestExitAndWait() is not virtual, and the implementation doesn't do enough. 674 virtual void requestExit(); 675 676 void pause(); // suspend thread from execution at next loop boundary 677 void resume(); // allow thread to execute, if not requested to exit 678 void wake(); // wake to handle changed notification conditions. 679 680 private: 681 void pauseInternal(nsecs_t ns = 0LL); 682 // like pause(), but only used internally within thread 683 684 friend class AudioTrack; 685 virtual bool threadLoop(); 686 AudioTrack& mReceiver; 687 virtual ~AudioTrackThread(); 688 Mutex mMyLock; // Thread::mLock is private 689 Condition mMyCond; // Thread::mThreadExitedCondition is private 690 bool mPaused; // whether thread is requested to pause at next loop entry 691 bool mPausedInt; // whether thread internally requests pause 692 nsecs_t mPausedNs; // if mPausedInt then associated timeout, otherwise ignored 693 bool mIgnoreNextPausedInt; // skip any internal pause and go immediately 694 // to processAudioBuffer() as state may have changed 695 // since pause time calculated. 696 }; 697 698 // body of AudioTrackThread::threadLoop() 699 // returns the maximum amount of time before we would like to run again, where: 700 // 0 immediately 701 // > 0 no later than this many nanoseconds from now 702 // NS_WHENEVER still active but no particular deadline 703 // NS_INACTIVE inactive so don't run again until re-started 704 // NS_NEVER never again 705 static const nsecs_t NS_WHENEVER = -1, NS_INACTIVE = -2, NS_NEVER = -3; 706 nsecs_t processAudioBuffer(); 707 708 // caller must hold lock on mLock for all _l methods 709 710 status_t createTrack_l(); 711 712 // can only be called when mState != STATE_ACTIVE 713 void flush_l(); 714 715 void setLoop_l(uint32_t loopStart, uint32_t loopEnd, int loopCount); 716 717 // FIXME enum is faster than strcmp() for parameter 'from' 718 status_t restoreTrack_l(const char *from); 719 720 bool isOffloaded() const; 721 bool isDirect() const; 722 bool isOffloadedOrDirect() const; 723 724 bool isOffloaded_l() const 725 { return (mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0; } 726 727 bool isOffloadedOrDirect_l() const 728 { return (mFlags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD| 729 AUDIO_OUTPUT_FLAG_DIRECT)) != 0; } 730 731 bool isDirect_l() const 732 { return (mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0; } 733 734 // increment mPosition by the delta of mServer, and return new value of mPosition 735 uint32_t updateAndGetPosition_l(); 736 737 // check sample rate and speed is compatible with AudioTrack 738 bool isSampleRateSpeedAllowed_l(uint32_t sampleRate, float speed) const; 739 740 // Next 4 fields may be changed if IAudioTrack is re-created, but always != 0 741 sp<IAudioTrack> mAudioTrack; 742 sp<IMemory> mCblkMemory; 743 audio_track_cblk_t* mCblk; // re-load after mLock.unlock() 744 audio_io_handle_t mOutput; // returned by AudioSystem::getOutput() 745 746 sp<AudioTrackThread> mAudioTrackThread; 747 748 float mVolume[2]; 749 float mSendLevel; 750 mutable uint32_t mSampleRate; // mutable because getSampleRate() can update it 751 float mSpeed; // timestretch: 1.0f for normal speed. 752 float mPitch; // timestretch: 1.0f for normal pitch. 753 size_t mFrameCount; // corresponds to current IAudioTrack, value is 754 // reported back by AudioFlinger to the client 755 size_t mReqFrameCount; // frame count to request the first or next time 756 // a new IAudioTrack is needed, non-decreasing 757 758 // constant after constructor or set() 759 audio_format_t mFormat; // as requested by client, not forced to 16-bit 760 audio_stream_type_t mStreamType; // mStreamType == AUDIO_STREAM_DEFAULT implies 761 // this AudioTrack has valid attributes 762 uint32_t mChannelCount; 763 audio_channel_mask_t mChannelMask; 764 sp<IMemory> mSharedBuffer; 765 transfer_type mTransfer; 766 audio_offload_info_t mOffloadInfoCopy; 767 const audio_offload_info_t* mOffloadInfo; 768 audio_attributes_t mAttributes; 769 770 size_t mFrameSize; // frame size in bytes 771 772 status_t mStatus; 773 774 // can change dynamically when IAudioTrack invalidated 775 uint32_t mLatency; // in ms 776 777 // Indicates the current track state. Protected by mLock. 778 enum State { 779 STATE_ACTIVE, 780 STATE_STOPPED, 781 STATE_PAUSED, 782 STATE_PAUSED_STOPPING, 783 STATE_FLUSHED, 784 STATE_STOPPING, 785 } mState; 786 787 // for client callback handler 788 callback_t mCbf; // callback handler for events, or NULL 789 void* mUserData; 790 791 // for notification APIs 792 uint32_t mNotificationFramesReq; // requested number of frames between each 793 // notification callback, 794 // at initial source sample rate 795 uint32_t mNotificationFramesAct; // actual number of frames between each 796 // notification callback, 797 // at initial source sample rate 798 bool mRefreshRemaining; // processAudioBuffer() should refresh 799 // mRemainingFrames and mRetryOnPartialBuffer 800 801 // used for static track cbf and restoration 802 int32_t mLoopCount; // last setLoop loopCount; zero means disabled 803 uint32_t mLoopStart; // last setLoop loopStart 804 uint32_t mLoopEnd; // last setLoop loopEnd 805 int32_t mLoopCountNotified; // the last loopCount notified by callback. 806 // mLoopCountNotified counts down, matching 807 // the remaining loop count for static track 808 // playback. 809 810 // These are private to processAudioBuffer(), and are not protected by a lock 811 uint32_t mRemainingFrames; // number of frames to request in obtainBuffer() 812 bool mRetryOnPartialBuffer; // sleep and retry after partial obtainBuffer() 813 uint32_t mObservedSequence; // last observed value of mSequence 814 815 uint32_t mMarkerPosition; // in wrapping (overflow) frame units 816 bool mMarkerReached; 817 uint32_t mNewPosition; // in frames 818 uint32_t mUpdatePeriod; // in frames, zero means no EVENT_NEW_POS 819 820 uint32_t mServer; // in frames, last known mProxy->getPosition() 821 // which is count of frames consumed by server, 822 // reset by new IAudioTrack, 823 // whether it is reset by stop() is TBD 824 uint32_t mPosition; // in frames, like mServer except continues 825 // monotonically after new IAudioTrack, 826 // and could be easily widened to uint64_t 827 uint32_t mReleased; // in frames, count of frames released to server 828 // but not necessarily consumed by server, 829 // reset by stop() but continues monotonically 830 // after new IAudioTrack to restore mPosition, 831 // and could be easily widened to uint64_t 832 int64_t mStartUs; // the start time after flush or stop. 833 // only used for offloaded and direct tracks. 834 835 audio_output_flags_t mFlags; 836 // const after set(), except for bits AUDIO_OUTPUT_FLAG_FAST and AUDIO_OUTPUT_FLAG_OFFLOAD. 837 // mLock must be held to read or write those bits reliably. 838 839 int mSessionId; 840 int mAuxEffectId; 841 842 mutable Mutex mLock; 843 844 bool mIsTimed; 845 int mPreviousPriority; // before start() 846 SchedPolicy mPreviousSchedulingGroup; 847 bool mAwaitBoost; // thread should wait for priority boost before running 848 849 // The proxy should only be referenced while a lock is held because the proxy isn't 850 // multi-thread safe, especially the SingleStateQueue part of the proxy. 851 // An exception is that a blocking ClientProxy::obtainBuffer() may be called without a lock, 852 // provided that the caller also holds an extra reference to the proxy and shared memory to keep 853 // them around in case they are replaced during the obtainBuffer(). 854 sp<StaticAudioTrackClientProxy> mStaticProxy; // for type safety only 855 sp<AudioTrackClientProxy> mProxy; // primary owner of the memory 856 857 bool mInUnderrun; // whether track is currently in underrun state 858 uint32_t mPausedPosition; 859 860 // For Device Selection API 861 // a value of AUDIO_PORT_HANDLE_NONE indicated default (AudioPolicyManager) routing. 862 int mSelectedDeviceId; 863 864private: 865 class DeathNotifier : public IBinder::DeathRecipient { 866 public: 867 DeathNotifier(AudioTrack* audioTrack) : mAudioTrack(audioTrack) { } 868 protected: 869 virtual void binderDied(const wp<IBinder>& who); 870 private: 871 const wp<AudioTrack> mAudioTrack; 872 }; 873 874 sp<DeathNotifier> mDeathNotifier; 875 uint32_t mSequence; // incremented for each new IAudioTrack attempt 876 int mClientUid; 877 pid_t mClientPid; 878}; 879 880class TimedAudioTrack : public AudioTrack 881{ 882public: 883 TimedAudioTrack(); 884 885 /* allocate a shared memory buffer that can be passed to queueTimedBuffer */ 886 status_t allocateTimedBuffer(size_t size, sp<IMemory>* buffer); 887 888 /* queue a buffer obtained via allocateTimedBuffer for playback at the 889 given timestamp. PTS units are microseconds on the media time timeline. 890 The media time transform (set with setMediaTimeTransform) set by the 891 audio producer will handle converting from media time to local time 892 (perhaps going through the common time timeline in the case of 893 synchronized multiroom audio case) */ 894 status_t queueTimedBuffer(const sp<IMemory>& buffer, int64_t pts); 895 896 /* define a transform between media time and either common time or 897 local time */ 898 enum TargetTimeline {LOCAL_TIME, COMMON_TIME}; 899 status_t setMediaTimeTransform(const LinearTransform& xform, 900 TargetTimeline target); 901}; 902 903}; // namespace android 904 905#endif // ANDROID_AUDIOTRACK_H 906