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