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