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