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