1 /* 2 * Copyright (C) 2008 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 package android.media; 18 19 import android.annotation.CallbackExecutor; 20 import android.annotation.FloatRange; 21 import android.annotation.IntDef; 22 import android.annotation.IntRange; 23 import android.annotation.NonNull; 24 import android.annotation.Nullable; 25 import android.annotation.RequiresPermission; 26 import android.annotation.SystemApi; 27 import android.annotation.TestApi; 28 import android.compat.annotation.UnsupportedAppUsage; 29 import android.os.Binder; 30 import android.os.Handler; 31 import android.os.HandlerThread; 32 import android.os.Looper; 33 import android.os.Message; 34 import android.os.PersistableBundle; 35 import android.util.ArrayMap; 36 import android.util.Log; 37 38 import com.android.internal.annotations.GuardedBy; 39 40 import java.lang.annotation.Retention; 41 import java.lang.annotation.RetentionPolicy; 42 import java.lang.ref.WeakReference; 43 import java.nio.ByteBuffer; 44 import java.nio.ByteOrder; 45 import java.nio.NioUtils; 46 import java.util.LinkedList; 47 import java.util.concurrent.Executor; 48 49 /** 50 * The AudioTrack class manages and plays a single audio resource for Java applications. 51 * It allows streaming of PCM audio buffers to the audio sink for playback. This is 52 * achieved by "pushing" the data to the AudioTrack object using one of the 53 * {@link #write(byte[], int, int)}, {@link #write(short[], int, int)}, 54 * and {@link #write(float[], int, int, int)} methods. 55 * 56 * <p>An AudioTrack instance can operate under two modes: static or streaming.<br> 57 * In Streaming mode, the application writes a continuous stream of data to the AudioTrack, using 58 * one of the {@code write()} methods. These are blocking and return when the data has been 59 * transferred from the Java layer to the native layer and queued for playback. The streaming 60 * mode is most useful when playing blocks of audio data that for instance are: 61 * 62 * <ul> 63 * <li>too big to fit in memory because of the duration of the sound to play,</li> 64 * <li>too big to fit in memory because of the characteristics of the audio data 65 * (high sampling rate, bits per sample ...)</li> 66 * <li>received or generated while previously queued audio is playing.</li> 67 * </ul> 68 * 69 * The static mode should be chosen when dealing with short sounds that fit in memory and 70 * that need to be played with the smallest latency possible. The static mode will 71 * therefore be preferred for UI and game sounds that are played often, and with the 72 * smallest overhead possible. 73 * 74 * <p>Upon creation, an AudioTrack object initializes its associated audio buffer. 75 * The size of this buffer, specified during the construction, determines how long an AudioTrack 76 * can play before running out of data.<br> 77 * For an AudioTrack using the static mode, this size is the maximum size of the sound that can 78 * be played from it.<br> 79 * For the streaming mode, data will be written to the audio sink in chunks of 80 * sizes less than or equal to the total buffer size. 81 * 82 * AudioTrack is not final and thus permits subclasses, but such use is not recommended. 83 */ 84 public class AudioTrack extends PlayerBase 85 implements AudioRouting 86 , VolumeAutomation 87 { 88 //--------------------------------------------------------- 89 // Constants 90 //-------------------- 91 /** Minimum value for a linear gain or auxiliary effect level. 92 * This value must be exactly equal to 0.0f; do not change it. 93 */ 94 private static final float GAIN_MIN = 0.0f; 95 /** Maximum value for a linear gain or auxiliary effect level. 96 * This value must be greater than or equal to 1.0f. 97 */ 98 private static final float GAIN_MAX = 1.0f; 99 100 /** indicates AudioTrack state is stopped */ 101 public static final int PLAYSTATE_STOPPED = 1; // matches SL_PLAYSTATE_STOPPED 102 /** indicates AudioTrack state is paused */ 103 public static final int PLAYSTATE_PAUSED = 2; // matches SL_PLAYSTATE_PAUSED 104 /** indicates AudioTrack state is playing */ 105 public static final int PLAYSTATE_PLAYING = 3; // matches SL_PLAYSTATE_PLAYING 106 /** 107 * @hide 108 * indicates AudioTrack state is stopping waiting for NATIVE_EVENT_STREAM_END to 109 * transition to PLAYSTATE_STOPPED. 110 * Only valid for offload mode. 111 */ 112 private static final int PLAYSTATE_STOPPING = 4; 113 /** 114 * @hide 115 * indicates AudioTrack state is paused from stopping state. Will transition to 116 * PLAYSTATE_STOPPING if play() is called. 117 * Only valid for offload mode. 118 */ 119 private static final int PLAYSTATE_PAUSED_STOPPING = 5; 120 121 // keep these values in sync with android_media_AudioTrack.cpp 122 /** 123 * Creation mode where audio data is transferred from Java to the native layer 124 * only once before the audio starts playing. 125 */ 126 public static final int MODE_STATIC = 0; 127 /** 128 * Creation mode where audio data is streamed from Java to the native layer 129 * as the audio is playing. 130 */ 131 public static final int MODE_STREAM = 1; 132 133 /** @hide */ 134 @IntDef({ 135 MODE_STATIC, 136 MODE_STREAM 137 }) 138 @Retention(RetentionPolicy.SOURCE) 139 public @interface TransferMode {} 140 141 /** 142 * State of an AudioTrack that was not successfully initialized upon creation. 143 */ 144 public static final int STATE_UNINITIALIZED = 0; 145 /** 146 * State of an AudioTrack that is ready to be used. 147 */ 148 public static final int STATE_INITIALIZED = 1; 149 /** 150 * State of a successfully initialized AudioTrack that uses static data, 151 * but that hasn't received that data yet. 152 */ 153 public static final int STATE_NO_STATIC_DATA = 2; 154 155 /** 156 * Denotes a successful operation. 157 */ 158 public static final int SUCCESS = AudioSystem.SUCCESS; 159 /** 160 * Denotes a generic operation failure. 161 */ 162 public static final int ERROR = AudioSystem.ERROR; 163 /** 164 * Denotes a failure due to the use of an invalid value. 165 */ 166 public static final int ERROR_BAD_VALUE = AudioSystem.BAD_VALUE; 167 /** 168 * Denotes a failure due to the improper use of a method. 169 */ 170 public static final int ERROR_INVALID_OPERATION = AudioSystem.INVALID_OPERATION; 171 /** 172 * An error code indicating that the object reporting it is no longer valid and needs to 173 * be recreated. 174 */ 175 public static final int ERROR_DEAD_OBJECT = AudioSystem.DEAD_OBJECT; 176 /** 177 * {@link #getTimestampWithStatus(AudioTimestamp)} is called in STOPPED or FLUSHED state, 178 * or immediately after start/ACTIVE. 179 * @hide 180 */ 181 public static final int ERROR_WOULD_BLOCK = AudioSystem.WOULD_BLOCK; 182 183 // Error codes: 184 // to keep in sync with frameworks/base/core/jni/android_media_AudioTrack.cpp 185 private static final int ERROR_NATIVESETUP_AUDIOSYSTEM = -16; 186 private static final int ERROR_NATIVESETUP_INVALIDCHANNELMASK = -17; 187 private static final int ERROR_NATIVESETUP_INVALIDFORMAT = -18; 188 private static final int ERROR_NATIVESETUP_INVALIDSTREAMTYPE = -19; 189 private static final int ERROR_NATIVESETUP_NATIVEINITFAILED = -20; 190 191 // Events: 192 // to keep in sync with frameworks/av/include/media/AudioTrack.h 193 // Note: To avoid collisions with other event constants, 194 // do not define an event here that is the same value as 195 // AudioSystem.NATIVE_EVENT_ROUTING_CHANGE. 196 197 /** 198 * Event id denotes when playback head has reached a previously set marker. 199 */ 200 private static final int NATIVE_EVENT_MARKER = 3; 201 /** 202 * Event id denotes when previously set update period has elapsed during playback. 203 */ 204 private static final int NATIVE_EVENT_NEW_POS = 4; 205 /** 206 * Callback for more data 207 */ 208 private static final int NATIVE_EVENT_CAN_WRITE_MORE_DATA = 9; 209 /** 210 * IAudioTrack tear down for offloaded tracks 211 * TODO: when received, java AudioTrack must be released 212 */ 213 private static final int NATIVE_EVENT_NEW_IAUDIOTRACK = 6; 214 /** 215 * Event id denotes when all the buffers queued in AF and HW are played 216 * back (after stop is called) for an offloaded track. 217 */ 218 private static final int NATIVE_EVENT_STREAM_END = 7; 219 /** 220 * Event id denotes when the codec format changes. 221 * 222 * Note: Similar to a device routing change (AudioSystem.NATIVE_EVENT_ROUTING_CHANGE), 223 * this event comes from the AudioFlinger Thread / Output Stream management 224 * (not from buffer indications as above). 225 */ 226 private static final int NATIVE_EVENT_CODEC_FORMAT_CHANGE = 100; 227 228 private final static String TAG = "android.media.AudioTrack"; 229 230 /** @hide */ 231 @IntDef({ 232 ENCAPSULATION_MODE_NONE, 233 ENCAPSULATION_MODE_ELEMENTARY_STREAM, 234 // ENCAPSULATION_MODE_HANDLE, @SystemApi 235 }) 236 @Retention(RetentionPolicy.SOURCE) 237 public @interface EncapsulationMode {} 238 239 // Important: The ENCAPSULATION_MODE values must be kept in sync with native header files. 240 /** 241 * This mode indicates no metadata encapsulation, 242 * which is the default mode for sending audio data 243 * through {@code AudioTrack}. 244 */ 245 public static final int ENCAPSULATION_MODE_NONE = 0; 246 /** 247 * This mode indicates metadata encapsulation with an elementary stream payload. 248 * Both compressed and PCM format is allowed. 249 */ 250 public static final int ENCAPSULATION_MODE_ELEMENTARY_STREAM = 1; 251 /** 252 * This mode indicates metadata encapsulation with a handle payload 253 * and is set through {@link Builder#setEncapsulationMode(int)}. 254 * The handle is a 64 bit long, provided by the Tuner API 255 * in {@link android.os.Build.VERSION_CODES#R}. 256 * @hide 257 */ 258 @SystemApi 259 @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) 260 public static final int ENCAPSULATION_MODE_HANDLE = 2; 261 262 /* Enumeration of metadata types permitted for use by 263 * encapsulation mode audio streams. 264 */ 265 /** @hide */ 266 @IntDef(prefix = { "ENCAPSULATION_METADATA_TYPE_" }, value = { 267 ENCAPSULATION_METADATA_TYPE_NONE, /* reserved */ 268 ENCAPSULATION_METADATA_TYPE_FRAMEWORK_TUNER, 269 ENCAPSULATION_METADATA_TYPE_DVB_AD_DESCRIPTOR, 270 }) 271 @Retention(RetentionPolicy.SOURCE) 272 public @interface EncapsulationMetadataType {} 273 274 /** 275 * Reserved do not use. 276 * @hide 277 */ 278 public static final int ENCAPSULATION_METADATA_TYPE_NONE = 0; // reserved 279 280 /** 281 * Encapsulation metadata type for framework tuner information. 282 * 283 * Refer to the Android Media TV Tuner API for details. 284 */ 285 public static final int ENCAPSULATION_METADATA_TYPE_FRAMEWORK_TUNER = 1; 286 287 /** 288 * Encapsulation metadata type for DVB AD descriptor. 289 * 290 * This metadata is formatted per ETSI TS 101 154 Table E.1: AD_descriptor. 291 */ 292 public static final int ENCAPSULATION_METADATA_TYPE_DVB_AD_DESCRIPTOR = 2; 293 294 /* Dual Mono handling is used when a stereo audio stream 295 * contains separate audio content on the left and right channels. 296 * Such information about the content of the stream may be found, for example, in 297 * ITU T-REC-J.94-201610 A.6.2.3 Component descriptor. 298 */ 299 /** @hide */ 300 @IntDef({ 301 DUAL_MONO_MODE_OFF, 302 DUAL_MONO_MODE_LR, 303 DUAL_MONO_MODE_LL, 304 DUAL_MONO_MODE_RR, 305 }) 306 @Retention(RetentionPolicy.SOURCE) 307 public @interface DualMonoMode {} 308 // Important: The DUAL_MONO_MODE values must be kept in sync with native header files. 309 /** 310 * This mode disables any Dual Mono presentation effect. 311 * 312 */ 313 public static final int DUAL_MONO_MODE_OFF = 0; 314 315 /** 316 * This mode indicates that a stereo stream should be presented 317 * with the left and right audio channels blended together 318 * and delivered to both channels. 319 * 320 * Behavior for non-stereo streams is implementation defined. 321 * A suggested guideline is that the left-right stereo symmetric 322 * channels are pairwise blended; 323 * the other channels such as center are left alone. 324 * 325 * The Dual Mono effect occurs before volume scaling. 326 */ 327 public static final int DUAL_MONO_MODE_LR = 1; 328 329 /** 330 * This mode indicates that a stereo stream should be presented 331 * with the left audio channel replicated into the right audio channel. 332 * 333 * Behavior for non-stereo streams is implementation defined. 334 * A suggested guideline is that all channels with left-right 335 * stereo symmetry will have the left channel position replicated 336 * into the right channel position. 337 * The center channels (with no left/right symmetry) or unbalanced 338 * channels are left alone. 339 * 340 * The Dual Mono effect occurs before volume scaling. 341 */ 342 public static final int DUAL_MONO_MODE_LL = 2; 343 344 /** 345 * This mode indicates that a stereo stream should be presented 346 * with the right audio channel replicated into the left audio channel. 347 * 348 * Behavior for non-stereo streams is implementation defined. 349 * A suggested guideline is that all channels with left-right 350 * stereo symmetry will have the right channel position replicated 351 * into the left channel position. 352 * The center channels (with no left/right symmetry) or unbalanced 353 * channels are left alone. 354 * 355 * The Dual Mono effect occurs before volume scaling. 356 */ 357 public static final int DUAL_MONO_MODE_RR = 3; 358 359 /** @hide */ 360 @IntDef({ 361 WRITE_BLOCKING, 362 WRITE_NON_BLOCKING 363 }) 364 @Retention(RetentionPolicy.SOURCE) 365 public @interface WriteMode {} 366 367 /** 368 * The write mode indicating the write operation will block until all data has been written, 369 * to be used as the actual value of the writeMode parameter in 370 * {@link #write(byte[], int, int, int)}, {@link #write(short[], int, int, int)}, 371 * {@link #write(float[], int, int, int)}, {@link #write(ByteBuffer, int, int)}, and 372 * {@link #write(ByteBuffer, int, int, long)}. 373 */ 374 public final static int WRITE_BLOCKING = 0; 375 376 /** 377 * The write mode indicating the write operation will return immediately after 378 * queuing as much audio data for playback as possible without blocking, 379 * to be used as the actual value of the writeMode parameter in 380 * {@link #write(ByteBuffer, int, int)}, {@link #write(short[], int, int, int)}, 381 * {@link #write(float[], int, int, int)}, {@link #write(ByteBuffer, int, int)}, and 382 * {@link #write(ByteBuffer, int, int, long)}. 383 */ 384 public final static int WRITE_NON_BLOCKING = 1; 385 386 /** @hide */ 387 @IntDef({ 388 PERFORMANCE_MODE_NONE, 389 PERFORMANCE_MODE_LOW_LATENCY, 390 PERFORMANCE_MODE_POWER_SAVING 391 }) 392 @Retention(RetentionPolicy.SOURCE) 393 public @interface PerformanceMode {} 394 395 /** 396 * Default performance mode for an {@link AudioTrack}. 397 */ 398 public static final int PERFORMANCE_MODE_NONE = 0; 399 400 /** 401 * Low latency performance mode for an {@link AudioTrack}. 402 * If the device supports it, this mode 403 * enables a lower latency path through to the audio output sink. 404 * Effects may no longer work with such an {@code AudioTrack} and 405 * the sample rate must match that of the output sink. 406 * <p> 407 * Applications should be aware that low latency requires careful 408 * buffer management, with smaller chunks of audio data written by each 409 * {@code write()} call. 410 * <p> 411 * If this flag is used without specifying a {@code bufferSizeInBytes} then the 412 * {@code AudioTrack}'s actual buffer size may be too small. 413 * It is recommended that a fairly 414 * large buffer should be specified when the {@code AudioTrack} is created. 415 * Then the actual size can be reduced by calling 416 * {@link #setBufferSizeInFrames(int)}. The buffer size can be optimized 417 * by lowering it after each {@code write()} call until the audio glitches, 418 * which is detected by calling 419 * {@link #getUnderrunCount()}. Then the buffer size can be increased 420 * until there are no glitches. 421 * This tuning step should be done while playing silence. 422 * This technique provides a compromise between latency and glitch rate. 423 */ 424 public static final int PERFORMANCE_MODE_LOW_LATENCY = 1; 425 426 /** 427 * Power saving performance mode for an {@link AudioTrack}. 428 * If the device supports it, this 429 * mode will enable a lower power path to the audio output sink. 430 * In addition, this lower power path typically will have 431 * deeper internal buffers and better underrun resistance, 432 * with a tradeoff of higher latency. 433 * <p> 434 * In this mode, applications should attempt to use a larger buffer size 435 * and deliver larger chunks of audio data per {@code write()} call. 436 * Use {@link #getBufferSizeInFrames()} to determine 437 * the actual buffer size of the {@code AudioTrack} as it may have increased 438 * to accommodate a deeper buffer. 439 */ 440 public static final int PERFORMANCE_MODE_POWER_SAVING = 2; 441 442 // keep in sync with system/media/audio/include/system/audio-base.h 443 private static final int AUDIO_OUTPUT_FLAG_FAST = 0x4; 444 private static final int AUDIO_OUTPUT_FLAG_DEEP_BUFFER = 0x8; 445 446 // Size of HW_AV_SYNC track AV header. 447 private static final float HEADER_V2_SIZE_BYTES = 20.0f; 448 449 //-------------------------------------------------------------------------- 450 // Member variables 451 //-------------------- 452 /** 453 * Indicates the state of the AudioTrack instance. 454 * One of STATE_UNINITIALIZED, STATE_INITIALIZED, or STATE_NO_STATIC_DATA. 455 */ 456 private int mState = STATE_UNINITIALIZED; 457 /** 458 * Indicates the play state of the AudioTrack instance. 459 * One of PLAYSTATE_STOPPED, PLAYSTATE_PAUSED, or PLAYSTATE_PLAYING. 460 */ 461 private int mPlayState = PLAYSTATE_STOPPED; 462 463 /** 464 * Indicates that we are expecting an end of stream callback following a call 465 * to setOffloadEndOfStream() in a gapless track transition context. The native track 466 * will be restarted automatically. 467 */ 468 private boolean mOffloadEosPending = false; 469 470 /** 471 * Lock to ensure mPlayState updates reflect the actual state of the object. 472 */ 473 private final Object mPlayStateLock = new Object(); 474 /** 475 * Sizes of the audio buffer. 476 * These values are set during construction and can be stale. 477 * To obtain the current audio buffer frame count use {@link #getBufferSizeInFrames()}. 478 */ 479 private int mNativeBufferSizeInBytes = 0; 480 private int mNativeBufferSizeInFrames = 0; 481 /** 482 * Handler for events coming from the native code. 483 */ 484 private NativePositionEventHandlerDelegate mEventHandlerDelegate; 485 /** 486 * Looper associated with the thread that creates the AudioTrack instance. 487 */ 488 private final Looper mInitializationLooper; 489 /** 490 * The audio data source sampling rate in Hz. 491 * Never {@link AudioFormat#SAMPLE_RATE_UNSPECIFIED}. 492 */ 493 private int mSampleRate; // initialized by all constructors via audioParamCheck() 494 /** 495 * The number of audio output channels (1 is mono, 2 is stereo, etc.). 496 */ 497 private int mChannelCount = 1; 498 /** 499 * The audio channel mask used for calling native AudioTrack 500 */ 501 private int mChannelMask = AudioFormat.CHANNEL_OUT_MONO; 502 503 /** 504 * The type of the audio stream to play. See 505 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 506 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC}, 507 * {@link AudioManager#STREAM_ALARM}, {@link AudioManager#STREAM_NOTIFICATION}, and 508 * {@link AudioManager#STREAM_DTMF}. 509 */ 510 @UnsupportedAppUsage 511 private int mStreamType = AudioManager.STREAM_MUSIC; 512 513 /** 514 * The way audio is consumed by the audio sink, one of MODE_STATIC or MODE_STREAM. 515 */ 516 private int mDataLoadMode = MODE_STREAM; 517 /** 518 * The current channel position mask, as specified on AudioTrack creation. 519 * Can be set simultaneously with channel index mask {@link #mChannelIndexMask}. 520 * May be set to {@link AudioFormat#CHANNEL_INVALID} if a channel index mask is specified. 521 */ 522 private int mChannelConfiguration = AudioFormat.CHANNEL_OUT_MONO; 523 /** 524 * The channel index mask if specified, otherwise 0. 525 */ 526 private int mChannelIndexMask = 0; 527 /** 528 * The encoding of the audio samples. 529 * @see AudioFormat#ENCODING_PCM_8BIT 530 * @see AudioFormat#ENCODING_PCM_16BIT 531 * @see AudioFormat#ENCODING_PCM_FLOAT 532 */ 533 private int mAudioFormat; // initialized by all constructors via audioParamCheck() 534 /** 535 * The AudioAttributes used in configuration. 536 */ 537 private AudioAttributes mConfiguredAudioAttributes; 538 /** 539 * Audio session ID 540 */ 541 private int mSessionId = AudioManager.AUDIO_SESSION_ID_GENERATE; 542 /** 543 * HW_AV_SYNC track AV Sync Header 544 */ 545 private ByteBuffer mAvSyncHeader = null; 546 /** 547 * HW_AV_SYNC track audio data bytes remaining to write after current AV sync header 548 */ 549 private int mAvSyncBytesRemaining = 0; 550 /** 551 * Offset of the first sample of the audio in byte from start of HW_AV_SYNC track AV header. 552 */ 553 private int mOffset = 0; 554 /** 555 * Indicates whether the track is intended to play in offload mode. 556 */ 557 private boolean mOffloaded = false; 558 /** 559 * When offloaded track: delay for decoder in frames 560 */ 561 private int mOffloadDelayFrames = 0; 562 /** 563 * When offloaded track: padding for decoder in frames 564 */ 565 private int mOffloadPaddingFrames = 0; 566 567 //-------------------------------- 568 // Used exclusively by native code 569 //-------------------- 570 /** 571 * @hide 572 * Accessed by native methods: provides access to C++ AudioTrack object. 573 */ 574 @SuppressWarnings("unused") 575 @UnsupportedAppUsage 576 protected long mNativeTrackInJavaObj; 577 /** 578 * Accessed by native methods: provides access to the JNI data (i.e. resources used by 579 * the native AudioTrack object, but not stored in it). 580 */ 581 @SuppressWarnings("unused") 582 @UnsupportedAppUsage 583 private long mJniData; 584 585 586 //-------------------------------------------------------------------------- 587 // Constructor, Finalize 588 //-------------------- 589 /** 590 * Class constructor. 591 * @param streamType the type of the audio stream. See 592 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 593 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC}, 594 * {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}. 595 * @param sampleRateInHz the initial source sample rate expressed in Hz. 596 * {@link AudioFormat#SAMPLE_RATE_UNSPECIFIED} means to use a route-dependent value 597 * which is usually the sample rate of the sink. 598 * {@link #getSampleRate()} can be used to retrieve the actual sample rate chosen. 599 * @param channelConfig describes the configuration of the audio channels. 600 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 601 * {@link AudioFormat#CHANNEL_OUT_STEREO} 602 * @param audioFormat the format in which the audio data is represented. 603 * See {@link AudioFormat#ENCODING_PCM_16BIT}, 604 * {@link AudioFormat#ENCODING_PCM_8BIT}, 605 * and {@link AudioFormat#ENCODING_PCM_FLOAT}. 606 * @param bufferSizeInBytes the total size (in bytes) of the internal buffer where audio data is 607 * read from for playback. This should be a nonzero multiple of the frame size in bytes. 608 * <p> If the track's creation mode is {@link #MODE_STATIC}, 609 * this is the maximum length sample, or audio clip, that can be played by this instance. 610 * <p> If the track's creation mode is {@link #MODE_STREAM}, 611 * this should be the desired buffer size 612 * for the <code>AudioTrack</code> to satisfy the application's 613 * latency requirements. 614 * If <code>bufferSizeInBytes</code> is less than the 615 * minimum buffer size for the output sink, it is increased to the minimum 616 * buffer size. 617 * The method {@link #getBufferSizeInFrames()} returns the 618 * actual size in frames of the buffer created, which 619 * determines the minimum frequency to write 620 * to the streaming <code>AudioTrack</code> to avoid underrun. 621 * See {@link #getMinBufferSize(int, int, int)} to determine the estimated minimum buffer size 622 * for an AudioTrack instance in streaming mode. 623 * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM} 624 * @throws java.lang.IllegalArgumentException 625 * @deprecated use {@link Builder} or 626 * {@link #AudioTrack(AudioAttributes, AudioFormat, int, int, int)} to specify the 627 * {@link AudioAttributes} instead of the stream type which is only for volume control. 628 */ AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode)629 public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, 630 int bufferSizeInBytes, int mode) 631 throws IllegalArgumentException { 632 this(streamType, sampleRateInHz, channelConfig, audioFormat, 633 bufferSizeInBytes, mode, AudioManager.AUDIO_SESSION_ID_GENERATE); 634 } 635 636 /** 637 * Class constructor with audio session. Use this constructor when the AudioTrack must be 638 * attached to a particular audio session. The primary use of the audio session ID is to 639 * associate audio effects to a particular instance of AudioTrack: if an audio session ID 640 * is provided when creating an AudioEffect, this effect will be applied only to audio tracks 641 * and media players in the same session and not to the output mix. 642 * When an AudioTrack is created without specifying a session, it will create its own session 643 * which can be retrieved by calling the {@link #getAudioSessionId()} method. 644 * If a non-zero session ID is provided, this AudioTrack will share effects attached to this 645 * session 646 * with all other media players or audio tracks in the same session, otherwise a new session 647 * will be created for this track if none is supplied. 648 * @param streamType the type of the audio stream. See 649 * {@link AudioManager#STREAM_VOICE_CALL}, {@link AudioManager#STREAM_SYSTEM}, 650 * {@link AudioManager#STREAM_RING}, {@link AudioManager#STREAM_MUSIC}, 651 * {@link AudioManager#STREAM_ALARM}, and {@link AudioManager#STREAM_NOTIFICATION}. 652 * @param sampleRateInHz the initial source sample rate expressed in Hz. 653 * {@link AudioFormat#SAMPLE_RATE_UNSPECIFIED} means to use a route-dependent value 654 * which is usually the sample rate of the sink. 655 * @param channelConfig describes the configuration of the audio channels. 656 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 657 * {@link AudioFormat#CHANNEL_OUT_STEREO} 658 * @param audioFormat the format in which the audio data is represented. 659 * See {@link AudioFormat#ENCODING_PCM_16BIT} and 660 * {@link AudioFormat#ENCODING_PCM_8BIT}, 661 * and {@link AudioFormat#ENCODING_PCM_FLOAT}. 662 * @param bufferSizeInBytes the total size (in bytes) of the internal buffer where audio data is 663 * read from for playback. This should be a nonzero multiple of the frame size in bytes. 664 * <p> If the track's creation mode is {@link #MODE_STATIC}, 665 * this is the maximum length sample, or audio clip, that can be played by this instance. 666 * <p> If the track's creation mode is {@link #MODE_STREAM}, 667 * this should be the desired buffer size 668 * for the <code>AudioTrack</code> to satisfy the application's 669 * latency requirements. 670 * If <code>bufferSizeInBytes</code> is less than the 671 * minimum buffer size for the output sink, it is increased to the minimum 672 * buffer size. 673 * The method {@link #getBufferSizeInFrames()} returns the 674 * actual size in frames of the buffer created, which 675 * determines the minimum frequency to write 676 * to the streaming <code>AudioTrack</code> to avoid underrun. 677 * You can write data into this buffer in smaller chunks than this size. 678 * See {@link #getMinBufferSize(int, int, int)} to determine the estimated minimum buffer size 679 * for an AudioTrack instance in streaming mode. 680 * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM} 681 * @param sessionId Id of audio session the AudioTrack must be attached to 682 * @throws java.lang.IllegalArgumentException 683 * @deprecated use {@link Builder} or 684 * {@link #AudioTrack(AudioAttributes, AudioFormat, int, int, int)} to specify the 685 * {@link AudioAttributes} instead of the stream type which is only for volume control. 686 */ AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, int bufferSizeInBytes, int mode, int sessionId)687 public AudioTrack(int streamType, int sampleRateInHz, int channelConfig, int audioFormat, 688 int bufferSizeInBytes, int mode, int sessionId) 689 throws IllegalArgumentException { 690 // mState already == STATE_UNINITIALIZED 691 this((new AudioAttributes.Builder()) 692 .setLegacyStreamType(streamType) 693 .build(), 694 (new AudioFormat.Builder()) 695 .setChannelMask(channelConfig) 696 .setEncoding(audioFormat) 697 .setSampleRate(sampleRateInHz) 698 .build(), 699 bufferSizeInBytes, 700 mode, sessionId); 701 deprecateStreamTypeForPlayback(streamType, "AudioTrack", "AudioTrack()"); 702 } 703 704 /** 705 * Class constructor with {@link AudioAttributes} and {@link AudioFormat}. 706 * @param attributes a non-null {@link AudioAttributes} instance. 707 * @param format a non-null {@link AudioFormat} instance describing the format of the data 708 * that will be played through this AudioTrack. See {@link AudioFormat.Builder} for 709 * configuring the audio format parameters such as encoding, channel mask and sample rate. 710 * @param bufferSizeInBytes the total size (in bytes) of the internal buffer where audio data is 711 * read from for playback. This should be a nonzero multiple of the frame size in bytes. 712 * <p> If the track's creation mode is {@link #MODE_STATIC}, 713 * this is the maximum length sample, or audio clip, that can be played by this instance. 714 * <p> If the track's creation mode is {@link #MODE_STREAM}, 715 * this should be the desired buffer size 716 * for the <code>AudioTrack</code> to satisfy the application's 717 * latency requirements. 718 * If <code>bufferSizeInBytes</code> is less than the 719 * minimum buffer size for the output sink, it is increased to the minimum 720 * buffer size. 721 * The method {@link #getBufferSizeInFrames()} returns the 722 * actual size in frames of the buffer created, which 723 * determines the minimum frequency to write 724 * to the streaming <code>AudioTrack</code> to avoid underrun. 725 * See {@link #getMinBufferSize(int, int, int)} to determine the estimated minimum buffer size 726 * for an AudioTrack instance in streaming mode. 727 * @param mode streaming or static buffer. See {@link #MODE_STATIC} and {@link #MODE_STREAM}. 728 * @param sessionId ID of audio session the AudioTrack must be attached to, or 729 * {@link AudioManager#AUDIO_SESSION_ID_GENERATE} if the session isn't known at construction 730 * time. See also {@link AudioManager#generateAudioSessionId()} to obtain a session ID before 731 * construction. 732 * @throws IllegalArgumentException 733 */ AudioTrack(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes, int mode, int sessionId)734 public AudioTrack(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes, 735 int mode, int sessionId) 736 throws IllegalArgumentException { 737 this(attributes, format, bufferSizeInBytes, mode, sessionId, false /*offload*/, 738 ENCAPSULATION_MODE_NONE, null /* tunerConfiguration */); 739 } 740 AudioTrack(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes, int mode, int sessionId, boolean offload, int encapsulationMode, @Nullable TunerConfiguration tunerConfiguration)741 private AudioTrack(AudioAttributes attributes, AudioFormat format, int bufferSizeInBytes, 742 int mode, int sessionId, boolean offload, int encapsulationMode, 743 @Nullable TunerConfiguration tunerConfiguration) 744 throws IllegalArgumentException { 745 super(attributes, AudioPlaybackConfiguration.PLAYER_TYPE_JAM_AUDIOTRACK); 746 // mState already == STATE_UNINITIALIZED 747 748 mConfiguredAudioAttributes = attributes; // object copy not needed, immutable. 749 750 if (format == null) { 751 throw new IllegalArgumentException("Illegal null AudioFormat"); 752 } 753 754 // Check if we should enable deep buffer mode 755 if (shouldEnablePowerSaving(mAttributes, format, bufferSizeInBytes, mode)) { 756 mAttributes = new AudioAttributes.Builder(mAttributes) 757 .replaceFlags((mAttributes.getAllFlags() 758 | AudioAttributes.FLAG_DEEP_BUFFER) 759 & ~AudioAttributes.FLAG_LOW_LATENCY) 760 .build(); 761 } 762 763 // remember which looper is associated with the AudioTrack instantiation 764 Looper looper; 765 if ((looper = Looper.myLooper()) == null) { 766 looper = Looper.getMainLooper(); 767 } 768 769 int rate = format.getSampleRate(); 770 if (rate == AudioFormat.SAMPLE_RATE_UNSPECIFIED) { 771 rate = 0; 772 } 773 774 int channelIndexMask = 0; 775 if ((format.getPropertySetMask() 776 & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK) != 0) { 777 channelIndexMask = format.getChannelIndexMask(); 778 } 779 int channelMask = 0; 780 if ((format.getPropertySetMask() 781 & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK) != 0) { 782 channelMask = format.getChannelMask(); 783 } else if (channelIndexMask == 0) { // if no masks at all, use stereo 784 channelMask = AudioFormat.CHANNEL_OUT_FRONT_LEFT 785 | AudioFormat.CHANNEL_OUT_FRONT_RIGHT; 786 } 787 int encoding = AudioFormat.ENCODING_DEFAULT; 788 if ((format.getPropertySetMask() & AudioFormat.AUDIO_FORMAT_HAS_PROPERTY_ENCODING) != 0) { 789 encoding = format.getEncoding(); 790 } 791 audioParamCheck(rate, channelMask, channelIndexMask, encoding, mode); 792 mOffloaded = offload; 793 mStreamType = AudioSystem.STREAM_DEFAULT; 794 795 audioBuffSizeCheck(bufferSizeInBytes); 796 797 mInitializationLooper = looper; 798 799 if (sessionId < 0) { 800 throw new IllegalArgumentException("Invalid audio session ID: "+sessionId); 801 } 802 803 int[] sampleRate = new int[] {mSampleRate}; 804 int[] session = new int[1]; 805 session[0] = sessionId; 806 // native initialization 807 int initResult = native_setup(new WeakReference<AudioTrack>(this), mAttributes, 808 sampleRate, mChannelMask, mChannelIndexMask, mAudioFormat, 809 mNativeBufferSizeInBytes, mDataLoadMode, session, 0 /*nativeTrackInJavaObj*/, 810 offload, encapsulationMode, tunerConfiguration); 811 if (initResult != SUCCESS) { 812 loge("Error code "+initResult+" when initializing AudioTrack."); 813 return; // with mState == STATE_UNINITIALIZED 814 } 815 816 mSampleRate = sampleRate[0]; 817 mSessionId = session[0]; 818 819 // TODO: consider caching encapsulationMode and tunerConfiguration in the Java object. 820 821 if ((mAttributes.getFlags() & AudioAttributes.FLAG_HW_AV_SYNC) != 0) { 822 int frameSizeInBytes; 823 if (AudioFormat.isEncodingLinearFrames(mAudioFormat)) { 824 frameSizeInBytes = mChannelCount * AudioFormat.getBytesPerSample(mAudioFormat); 825 } else { 826 frameSizeInBytes = 1; 827 } 828 mOffset = ((int) Math.ceil(HEADER_V2_SIZE_BYTES / frameSizeInBytes)) * frameSizeInBytes; 829 } 830 831 if (mDataLoadMode == MODE_STATIC) { 832 mState = STATE_NO_STATIC_DATA; 833 } else { 834 mState = STATE_INITIALIZED; 835 } 836 837 baseRegisterPlayer(); 838 } 839 840 /** 841 * A constructor which explicitly connects a Native (C++) AudioTrack. For use by 842 * the AudioTrackRoutingProxy subclass. 843 * @param nativeTrackInJavaObj a C/C++ pointer to a native AudioTrack 844 * (associated with an OpenSL ES player). 845 * IMPORTANT: For "N", this method is ONLY called to setup a Java routing proxy, 846 * i.e. IAndroidConfiguration::AcquireJavaProxy(). If we call with a 0 in nativeTrackInJavaObj 847 * it means that the OpenSL player interface hasn't been realized, so there is no native 848 * Audiotrack to connect to. In this case wait to call deferred_connect() until the 849 * OpenSLES interface is realized. 850 */ AudioTrack(long nativeTrackInJavaObj)851 /*package*/ AudioTrack(long nativeTrackInJavaObj) { 852 super(new AudioAttributes.Builder().build(), 853 AudioPlaybackConfiguration.PLAYER_TYPE_JAM_AUDIOTRACK); 854 // "final"s 855 mNativeTrackInJavaObj = 0; 856 mJniData = 0; 857 858 // remember which looper is associated with the AudioTrack instantiation 859 Looper looper; 860 if ((looper = Looper.myLooper()) == null) { 861 looper = Looper.getMainLooper(); 862 } 863 mInitializationLooper = looper; 864 865 // other initialization... 866 if (nativeTrackInJavaObj != 0) { 867 baseRegisterPlayer(); 868 deferred_connect(nativeTrackInJavaObj); 869 } else { 870 mState = STATE_UNINITIALIZED; 871 } 872 } 873 874 /** 875 * @hide 876 */ 877 @UnsupportedAppUsage deferred_connect(long nativeTrackInJavaObj)878 /* package */ void deferred_connect(long nativeTrackInJavaObj) { 879 if (mState != STATE_INITIALIZED) { 880 // Note that for this native_setup, we are providing an already created/initialized 881 // *Native* AudioTrack, so the attributes parameters to native_setup() are ignored. 882 int[] session = { 0 }; 883 int[] rates = { 0 }; 884 int initResult = native_setup(new WeakReference<AudioTrack>(this), 885 null /*mAttributes - NA*/, 886 rates /*sampleRate - NA*/, 887 0 /*mChannelMask - NA*/, 888 0 /*mChannelIndexMask - NA*/, 889 0 /*mAudioFormat - NA*/, 890 0 /*mNativeBufferSizeInBytes - NA*/, 891 0 /*mDataLoadMode - NA*/, 892 session, 893 nativeTrackInJavaObj, 894 false /*offload*/, 895 ENCAPSULATION_MODE_NONE, 896 null /* tunerConfiguration */); 897 if (initResult != SUCCESS) { 898 loge("Error code "+initResult+" when initializing AudioTrack."); 899 return; // with mState == STATE_UNINITIALIZED 900 } 901 902 mSessionId = session[0]; 903 904 mState = STATE_INITIALIZED; 905 } 906 } 907 908 /** 909 * TunerConfiguration is used to convey tuner information 910 * from the android.media.tv.Tuner API to AudioTrack construction. 911 * 912 * Use the Builder to construct the TunerConfiguration object, 913 * which is then used by the {@link AudioTrack.Builder} to create an AudioTrack. 914 * @hide 915 */ 916 @SystemApi 917 public static class TunerConfiguration { 918 private final int mContentId; 919 private final int mSyncId; 920 921 /** 922 * Constructs a TunerConfiguration instance for use in {@link AudioTrack.Builder} 923 * 924 * @param contentId selects the audio stream to use. 925 * The contentId may be obtained from 926 * {@link android.media.tv.tuner.filter.Filter#getId()}. 927 * This is always a positive number. 928 * @param syncId selects the clock to use for synchronization 929 * of audio with other streams such as video. 930 * The syncId may be obtained from 931 * {@link android.media.tv.tuner.Tuner#getAvSyncHwId()}. 932 * This is always a positive number. 933 */ 934 @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) TunerConfiguration( @ntRangefrom = 1) int contentId, @IntRange(from = 1)int syncId)935 public TunerConfiguration( 936 @IntRange(from = 1) int contentId, @IntRange(from = 1)int syncId) { 937 if (contentId < 1) { 938 throw new IllegalArgumentException( 939 "contentId " + contentId + " must be positive"); 940 } 941 if (syncId < 1) { 942 throw new IllegalArgumentException("syncId " + syncId + " must be positive"); 943 } 944 mContentId = contentId; 945 mSyncId = syncId; 946 } 947 948 /** 949 * Returns the contentId. 950 */ 951 @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) getContentId()952 public @IntRange(from = 1) int getContentId() { 953 return mContentId; // The Builder ensures this is > 0. 954 } 955 956 /** 957 * Returns the syncId. 958 */ 959 @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) getSyncId()960 public @IntRange(from = 1) int getSyncId() { 961 return mSyncId; // The Builder ensures this is > 0. 962 } 963 } 964 965 /** 966 * Builder class for {@link AudioTrack} objects. 967 * Use this class to configure and create an <code>AudioTrack</code> instance. By setting audio 968 * attributes and audio format parameters, you indicate which of those vary from the default 969 * behavior on the device. 970 * <p> Here is an example where <code>Builder</code> is used to specify all {@link AudioFormat} 971 * parameters, to be used by a new <code>AudioTrack</code> instance: 972 * 973 * <pre class="prettyprint"> 974 * AudioTrack player = new AudioTrack.Builder() 975 * .setAudioAttributes(new AudioAttributes.Builder() 976 * .setUsage(AudioAttributes.USAGE_ALARM) 977 * .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC) 978 * .build()) 979 * .setAudioFormat(new AudioFormat.Builder() 980 * .setEncoding(AudioFormat.ENCODING_PCM_16BIT) 981 * .setSampleRate(44100) 982 * .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO) 983 * .build()) 984 * .setBufferSizeInBytes(minBuffSize) 985 * .build(); 986 * </pre> 987 * <p> 988 * If the audio attributes are not set with {@link #setAudioAttributes(AudioAttributes)}, 989 * attributes comprising {@link AudioAttributes#USAGE_MEDIA} will be used. 990 * <br>If the audio format is not specified or is incomplete, its channel configuration will be 991 * {@link AudioFormat#CHANNEL_OUT_STEREO} and the encoding will be 992 * {@link AudioFormat#ENCODING_PCM_16BIT}. 993 * The sample rate will depend on the device actually selected for playback and can be queried 994 * with {@link #getSampleRate()} method. 995 * <br>If the buffer size is not specified with {@link #setBufferSizeInBytes(int)}, 996 * and the mode is {@link AudioTrack#MODE_STREAM}, the minimum buffer size is used. 997 * <br>If the transfer mode is not specified with {@link #setTransferMode(int)}, 998 * <code>MODE_STREAM</code> will be used. 999 * <br>If the session ID is not specified with {@link #setSessionId(int)}, a new one will 1000 * be generated. 1001 * <br>Offload is false by default. 1002 */ 1003 public static class Builder { 1004 private AudioAttributes mAttributes; 1005 private AudioFormat mFormat; 1006 private int mBufferSizeInBytes; 1007 private int mEncapsulationMode = ENCAPSULATION_MODE_NONE; 1008 private int mSessionId = AudioManager.AUDIO_SESSION_ID_GENERATE; 1009 private int mMode = MODE_STREAM; 1010 private int mPerformanceMode = PERFORMANCE_MODE_NONE; 1011 private boolean mOffload = false; 1012 private TunerConfiguration mTunerConfiguration; 1013 1014 /** 1015 * Constructs a new Builder with the default values as described above. 1016 */ Builder()1017 public Builder() { 1018 } 1019 1020 /** 1021 * Sets the {@link AudioAttributes}. 1022 * @param attributes a non-null {@link AudioAttributes} instance that describes the audio 1023 * data to be played. 1024 * @return the same Builder instance. 1025 * @throws IllegalArgumentException 1026 */ setAudioAttributes(@onNull AudioAttributes attributes)1027 public @NonNull Builder setAudioAttributes(@NonNull AudioAttributes attributes) 1028 throws IllegalArgumentException { 1029 if (attributes == null) { 1030 throw new IllegalArgumentException("Illegal null AudioAttributes argument"); 1031 } 1032 // keep reference, we only copy the data when building 1033 mAttributes = attributes; 1034 return this; 1035 } 1036 1037 /** 1038 * Sets the format of the audio data to be played by the {@link AudioTrack}. 1039 * See {@link AudioFormat.Builder} for configuring the audio format parameters such 1040 * as encoding, channel mask and sample rate. 1041 * @param format a non-null {@link AudioFormat} instance. 1042 * @return the same Builder instance. 1043 * @throws IllegalArgumentException 1044 */ setAudioFormat(@onNull AudioFormat format)1045 public @NonNull Builder setAudioFormat(@NonNull AudioFormat format) 1046 throws IllegalArgumentException { 1047 if (format == null) { 1048 throw new IllegalArgumentException("Illegal null AudioFormat argument"); 1049 } 1050 // keep reference, we only copy the data when building 1051 mFormat = format; 1052 return this; 1053 } 1054 1055 /** 1056 * Sets the total size (in bytes) of the buffer where audio data is read from for playback. 1057 * If using the {@link AudioTrack} in streaming mode 1058 * (see {@link AudioTrack#MODE_STREAM}, you can write data into this buffer in smaller 1059 * chunks than this size. See {@link #getMinBufferSize(int, int, int)} to determine 1060 * the estimated minimum buffer size for the creation of an AudioTrack instance 1061 * in streaming mode. 1062 * <br>If using the <code>AudioTrack</code> in static mode (see 1063 * {@link AudioTrack#MODE_STATIC}), this is the maximum size of the sound that will be 1064 * played by this instance. 1065 * @param bufferSizeInBytes 1066 * @return the same Builder instance. 1067 * @throws IllegalArgumentException 1068 */ setBufferSizeInBytes(@ntRangefrom = 0) int bufferSizeInBytes)1069 public @NonNull Builder setBufferSizeInBytes(@IntRange(from = 0) int bufferSizeInBytes) 1070 throws IllegalArgumentException { 1071 if (bufferSizeInBytes <= 0) { 1072 throw new IllegalArgumentException("Invalid buffer size " + bufferSizeInBytes); 1073 } 1074 mBufferSizeInBytes = bufferSizeInBytes; 1075 return this; 1076 } 1077 1078 /** 1079 * Sets the encapsulation mode. 1080 * 1081 * Encapsulation mode allows metadata to be sent together with 1082 * the audio data payload in a {@code ByteBuffer}. 1083 * This requires a compatible hardware audio codec. 1084 * 1085 * @param encapsulationMode one of {@link AudioTrack#ENCAPSULATION_MODE_NONE}, 1086 * or {@link AudioTrack#ENCAPSULATION_MODE_ELEMENTARY_STREAM}. 1087 * @return the same Builder instance. 1088 */ 1089 // Note: with the correct permission {@code AudioTrack#ENCAPSULATION_MODE_HANDLE} 1090 // may be used as well. setEncapsulationMode(@ncapsulationMode int encapsulationMode)1091 public @NonNull Builder setEncapsulationMode(@EncapsulationMode int encapsulationMode) { 1092 switch (encapsulationMode) { 1093 case ENCAPSULATION_MODE_NONE: 1094 case ENCAPSULATION_MODE_ELEMENTARY_STREAM: 1095 case ENCAPSULATION_MODE_HANDLE: 1096 mEncapsulationMode = encapsulationMode; 1097 break; 1098 default: 1099 throw new IllegalArgumentException( 1100 "Invalid encapsulation mode " + encapsulationMode); 1101 } 1102 return this; 1103 } 1104 1105 /** 1106 * Sets the mode under which buffers of audio data are transferred from the 1107 * {@link AudioTrack} to the framework. 1108 * @param mode one of {@link AudioTrack#MODE_STREAM}, {@link AudioTrack#MODE_STATIC}. 1109 * @return the same Builder instance. 1110 * @throws IllegalArgumentException 1111 */ setTransferMode(@ransferMode int mode)1112 public @NonNull Builder setTransferMode(@TransferMode int mode) 1113 throws IllegalArgumentException { 1114 switch(mode) { 1115 case MODE_STREAM: 1116 case MODE_STATIC: 1117 mMode = mode; 1118 break; 1119 default: 1120 throw new IllegalArgumentException("Invalid transfer mode " + mode); 1121 } 1122 return this; 1123 } 1124 1125 /** 1126 * Sets the session ID the {@link AudioTrack} will be attached to. 1127 * @param sessionId a strictly positive ID number retrieved from another 1128 * <code>AudioTrack</code> via {@link AudioTrack#getAudioSessionId()} or allocated by 1129 * {@link AudioManager} via {@link AudioManager#generateAudioSessionId()}, or 1130 * {@link AudioManager#AUDIO_SESSION_ID_GENERATE}. 1131 * @return the same Builder instance. 1132 * @throws IllegalArgumentException 1133 */ setSessionId(@ntRangefrom = 1) int sessionId)1134 public @NonNull Builder setSessionId(@IntRange(from = 1) int sessionId) 1135 throws IllegalArgumentException { 1136 if ((sessionId != AudioManager.AUDIO_SESSION_ID_GENERATE) && (sessionId < 1)) { 1137 throw new IllegalArgumentException("Invalid audio session ID " + sessionId); 1138 } 1139 mSessionId = sessionId; 1140 return this; 1141 } 1142 1143 /** 1144 * Sets the {@link AudioTrack} performance mode. This is an advisory request which 1145 * may not be supported by the particular device, and the framework is free 1146 * to ignore such request if it is incompatible with other requests or hardware. 1147 * 1148 * @param performanceMode one of 1149 * {@link AudioTrack#PERFORMANCE_MODE_NONE}, 1150 * {@link AudioTrack#PERFORMANCE_MODE_LOW_LATENCY}, 1151 * or {@link AudioTrack#PERFORMANCE_MODE_POWER_SAVING}. 1152 * @return the same Builder instance. 1153 * @throws IllegalArgumentException if {@code performanceMode} is not valid. 1154 */ setPerformanceMode(@erformanceMode int performanceMode)1155 public @NonNull Builder setPerformanceMode(@PerformanceMode int performanceMode) { 1156 switch (performanceMode) { 1157 case PERFORMANCE_MODE_NONE: 1158 case PERFORMANCE_MODE_LOW_LATENCY: 1159 case PERFORMANCE_MODE_POWER_SAVING: 1160 mPerformanceMode = performanceMode; 1161 break; 1162 default: 1163 throw new IllegalArgumentException( 1164 "Invalid performance mode " + performanceMode); 1165 } 1166 return this; 1167 } 1168 1169 /** 1170 * Sets whether this track will play through the offloaded audio path. 1171 * When set to true, at build time, the audio format will be checked against 1172 * {@link AudioManager#isOffloadedPlaybackSupported(AudioFormat,AudioAttributes)} 1173 * to verify the audio format used by this track is supported on the device's offload 1174 * path (if any). 1175 * <br>Offload is only supported for media audio streams, and therefore requires that 1176 * the usage be {@link AudioAttributes#USAGE_MEDIA}. 1177 * @param offload true to require the offload path for playback. 1178 * @return the same Builder instance. 1179 */ setOffloadedPlayback(boolean offload)1180 public @NonNull Builder setOffloadedPlayback(boolean offload) { 1181 mOffload = offload; 1182 return this; 1183 } 1184 1185 /** 1186 * Sets the tuner configuration for the {@code AudioTrack}. 1187 * 1188 * The {@link AudioTrack.TunerConfiguration} consists of parameters obtained from 1189 * the Android TV tuner API which indicate the audio content stream id and the 1190 * synchronization id for the {@code AudioTrack}. 1191 * 1192 * @param tunerConfiguration obtained by {@link AudioTrack.TunerConfiguration.Builder}. 1193 * @return the same Builder instance. 1194 * @hide 1195 */ 1196 @SystemApi 1197 @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_ROUTING) setTunerConfiguration( @onNull TunerConfiguration tunerConfiguration)1198 public @NonNull Builder setTunerConfiguration( 1199 @NonNull TunerConfiguration tunerConfiguration) { 1200 if (tunerConfiguration == null) { 1201 throw new IllegalArgumentException("tunerConfiguration is null"); 1202 } 1203 mTunerConfiguration = tunerConfiguration; 1204 return this; 1205 } 1206 1207 /** 1208 * Builds an {@link AudioTrack} instance initialized with all the parameters set 1209 * on this <code>Builder</code>. 1210 * @return a new successfully initialized {@link AudioTrack} instance. 1211 * @throws UnsupportedOperationException if the parameters set on the <code>Builder</code> 1212 * were incompatible, or if they are not supported by the device, 1213 * or if the device was not available. 1214 */ build()1215 public @NonNull AudioTrack build() throws UnsupportedOperationException { 1216 if (mAttributes == null) { 1217 mAttributes = new AudioAttributes.Builder() 1218 .setUsage(AudioAttributes.USAGE_MEDIA) 1219 .build(); 1220 } 1221 switch (mPerformanceMode) { 1222 case PERFORMANCE_MODE_LOW_LATENCY: 1223 mAttributes = new AudioAttributes.Builder(mAttributes) 1224 .replaceFlags((mAttributes.getAllFlags() 1225 | AudioAttributes.FLAG_LOW_LATENCY) 1226 & ~AudioAttributes.FLAG_DEEP_BUFFER) 1227 .build(); 1228 break; 1229 case PERFORMANCE_MODE_NONE: 1230 if (!shouldEnablePowerSaving(mAttributes, mFormat, mBufferSizeInBytes, mMode)) { 1231 break; // do not enable deep buffer mode. 1232 } 1233 // permitted to fall through to enable deep buffer 1234 case PERFORMANCE_MODE_POWER_SAVING: 1235 mAttributes = new AudioAttributes.Builder(mAttributes) 1236 .replaceFlags((mAttributes.getAllFlags() 1237 | AudioAttributes.FLAG_DEEP_BUFFER) 1238 & ~AudioAttributes.FLAG_LOW_LATENCY) 1239 .build(); 1240 break; 1241 } 1242 1243 if (mFormat == null) { 1244 mFormat = new AudioFormat.Builder() 1245 .setChannelMask(AudioFormat.CHANNEL_OUT_STEREO) 1246 //.setSampleRate(AudioFormat.SAMPLE_RATE_UNSPECIFIED) 1247 .setEncoding(AudioFormat.ENCODING_DEFAULT) 1248 .build(); 1249 } 1250 1251 if (mOffload) { 1252 if (mPerformanceMode == PERFORMANCE_MODE_LOW_LATENCY) { 1253 throw new UnsupportedOperationException( 1254 "Offload and low latency modes are incompatible"); 1255 } 1256 if (!AudioSystem.isOffloadSupported(mFormat, mAttributes)) { 1257 throw new UnsupportedOperationException( 1258 "Cannot create AudioTrack, offload format / attributes not supported"); 1259 } 1260 } 1261 1262 // TODO: Check mEncapsulationMode compatibility with MODE_STATIC, etc? 1263 1264 try { 1265 // If the buffer size is not specified in streaming mode, 1266 // use a single frame for the buffer size and let the 1267 // native code figure out the minimum buffer size. 1268 if (mMode == MODE_STREAM && mBufferSizeInBytes == 0) { 1269 mBufferSizeInBytes = mFormat.getChannelCount() 1270 * mFormat.getBytesPerSample(mFormat.getEncoding()); 1271 } 1272 final AudioTrack track = new AudioTrack( 1273 mAttributes, mFormat, mBufferSizeInBytes, mMode, mSessionId, mOffload, 1274 mEncapsulationMode, mTunerConfiguration); 1275 if (track.getState() == STATE_UNINITIALIZED) { 1276 // release is not necessary 1277 throw new UnsupportedOperationException("Cannot create AudioTrack"); 1278 } 1279 return track; 1280 } catch (IllegalArgumentException e) { 1281 throw new UnsupportedOperationException(e.getMessage()); 1282 } 1283 } 1284 } 1285 1286 /** 1287 * Configures the delay and padding values for the current compressed stream playing 1288 * in offload mode. 1289 * This can only be used on a track successfully initialized with 1290 * {@link AudioTrack.Builder#setOffloadedPlayback(boolean)}. The unit is frames, where a 1291 * frame indicates the number of samples per channel, e.g. 100 frames for a stereo compressed 1292 * stream corresponds to 200 decoded interleaved PCM samples. 1293 * @param delayInFrames number of frames to be ignored at the beginning of the stream. A value 1294 * of 0 indicates no delay is to be applied. 1295 * @param paddingInFrames number of frames to be ignored at the end of the stream. A value of 0 1296 * of 0 indicates no padding is to be applied. 1297 */ setOffloadDelayPadding(@ntRangefrom = 0) int delayInFrames, @IntRange(from = 0) int paddingInFrames)1298 public void setOffloadDelayPadding(@IntRange(from = 0) int delayInFrames, 1299 @IntRange(from = 0) int paddingInFrames) { 1300 if (paddingInFrames < 0) { 1301 throw new IllegalArgumentException("Illegal negative padding"); 1302 } 1303 if (delayInFrames < 0) { 1304 throw new IllegalArgumentException("Illegal negative delay"); 1305 } 1306 if (!mOffloaded) { 1307 throw new IllegalStateException("Illegal use of delay/padding on non-offloaded track"); 1308 } 1309 if (mState == STATE_UNINITIALIZED) { 1310 throw new IllegalStateException("Uninitialized track"); 1311 } 1312 mOffloadDelayFrames = delayInFrames; 1313 mOffloadPaddingFrames = paddingInFrames; 1314 native_set_delay_padding(delayInFrames, paddingInFrames); 1315 } 1316 1317 /** 1318 * Return the decoder delay of an offloaded track, expressed in frames, previously set with 1319 * {@link #setOffloadDelayPadding(int, int)}, or 0 if it was never modified. 1320 * <p>This delay indicates the number of frames to be ignored at the beginning of the stream. 1321 * This value can only be queried on a track successfully initialized with 1322 * {@link AudioTrack.Builder#setOffloadedPlayback(boolean)}. 1323 * @return decoder delay expressed in frames. 1324 */ getOffloadDelay()1325 public @IntRange(from = 0) int getOffloadDelay() { 1326 if (!mOffloaded) { 1327 throw new IllegalStateException("Illegal query of delay on non-offloaded track"); 1328 } 1329 if (mState == STATE_UNINITIALIZED) { 1330 throw new IllegalStateException("Illegal query of delay on uninitialized track"); 1331 } 1332 return mOffloadDelayFrames; 1333 } 1334 1335 /** 1336 * Return the decoder padding of an offloaded track, expressed in frames, previously set with 1337 * {@link #setOffloadDelayPadding(int, int)}, or 0 if it was never modified. 1338 * <p>This padding indicates the number of frames to be ignored at the end of the stream. 1339 * This value can only be queried on a track successfully initialized with 1340 * {@link AudioTrack.Builder#setOffloadedPlayback(boolean)}. 1341 * @return decoder padding expressed in frames. 1342 */ getOffloadPadding()1343 public @IntRange(from = 0) int getOffloadPadding() { 1344 if (!mOffloaded) { 1345 throw new IllegalStateException("Illegal query of padding on non-offloaded track"); 1346 } 1347 if (mState == STATE_UNINITIALIZED) { 1348 throw new IllegalStateException("Illegal query of padding on uninitialized track"); 1349 } 1350 return mOffloadPaddingFrames; 1351 } 1352 1353 /** 1354 * Declares that the last write() operation on this track provided the last buffer of this 1355 * stream. 1356 * After the end of stream, previously set padding and delay values are ignored. 1357 * Can only be called only if the AudioTrack is opened in offload mode 1358 * {@see Builder#setOffloadedPlayback(boolean)}. 1359 * Can only be called only if the AudioTrack is in state {@link #PLAYSTATE_PLAYING} 1360 * {@see #getPlayState()}. 1361 * Use this method in the same thread as any write() operation. 1362 */ setOffloadEndOfStream()1363 public void setOffloadEndOfStream() { 1364 if (!mOffloaded) { 1365 throw new IllegalStateException("EOS not supported on non-offloaded track"); 1366 } 1367 if (mState == STATE_UNINITIALIZED) { 1368 throw new IllegalStateException("Uninitialized track"); 1369 } 1370 if (mPlayState != PLAYSTATE_PLAYING) { 1371 throw new IllegalStateException("EOS not supported if not playing"); 1372 } 1373 synchronized (mStreamEventCbLock) { 1374 if (mStreamEventCbInfoList.size() == 0) { 1375 throw new IllegalStateException("EOS not supported without StreamEventCallback"); 1376 } 1377 } 1378 1379 synchronized (mPlayStateLock) { 1380 native_stop(); 1381 mOffloadEosPending = true; 1382 mPlayState = PLAYSTATE_STOPPING; 1383 } 1384 } 1385 1386 /** 1387 * Returns whether the track was built with {@link Builder#setOffloadedPlayback(boolean)} set 1388 * to {@code true}. 1389 * @return true if the track is using offloaded playback. 1390 */ isOffloadedPlayback()1391 public boolean isOffloadedPlayback() { 1392 return mOffloaded; 1393 } 1394 1395 /** 1396 * Returns whether direct playback of an audio format with the provided attributes is 1397 * currently supported on the system. 1398 * <p>Direct playback means that the audio stream is not resampled or downmixed 1399 * by the framework. Checking for direct support can help the app select the representation 1400 * of audio content that most closely matches the capabilities of the device and peripherials 1401 * (e.g. A/V receiver) connected to it. Note that the provided stream can still be re-encoded 1402 * or mixed with other streams, if needed. 1403 * <p>Also note that this query only provides information about the support of an audio format. 1404 * It does not indicate whether the resources necessary for the playback are available 1405 * at that instant. 1406 * @param format a non-null {@link AudioFormat} instance describing the format of 1407 * the audio data. 1408 * @param attributes a non-null {@link AudioAttributes} instance. 1409 * @return true if the given audio format can be played directly. 1410 */ isDirectPlaybackSupported(@onNull AudioFormat format, @NonNull AudioAttributes attributes)1411 public static boolean isDirectPlaybackSupported(@NonNull AudioFormat format, 1412 @NonNull AudioAttributes attributes) { 1413 if (format == null) { 1414 throw new IllegalArgumentException("Illegal null AudioFormat argument"); 1415 } 1416 if (attributes == null) { 1417 throw new IllegalArgumentException("Illegal null AudioAttributes argument"); 1418 } 1419 return native_is_direct_output_supported(format.getEncoding(), format.getSampleRate(), 1420 format.getChannelMask(), format.getChannelIndexMask(), 1421 attributes.getContentType(), attributes.getUsage(), attributes.getFlags()); 1422 } 1423 1424 /* 1425 * The MAX_LEVEL should be exactly representable by an IEEE 754-2008 base32 float. 1426 * This means fractions must be divisible by a power of 2. For example, 1427 * 10.25f is OK as 0.25 is 1/4, but 10.1f is NOT OK as 1/10 is not expressable by 1428 * a finite binary fraction. 1429 * 1430 * 48.f is the nominal max for API level {@link android os.Build.VERSION_CODES#R}. 1431 * We use this to suggest a baseline range for implementation. 1432 * 1433 * The API contract specification allows increasing this value in a future 1434 * API release, but not decreasing this value. 1435 */ 1436 private static final float MAX_AUDIO_DESCRIPTION_MIX_LEVEL = 48.f; 1437 isValidAudioDescriptionMixLevel(float level)1438 private static boolean isValidAudioDescriptionMixLevel(float level) { 1439 return !(Float.isNaN(level) || level > MAX_AUDIO_DESCRIPTION_MIX_LEVEL); 1440 } 1441 1442 /** 1443 * Sets the Audio Description mix level in dB. 1444 * 1445 * For AudioTracks incorporating a secondary Audio Description stream 1446 * (where such contents may be sent through an Encapsulation Mode 1447 * other than {@link #ENCAPSULATION_MODE_NONE}). 1448 * or internally by a HW channel), 1449 * the level of mixing of the Audio Description to the Main Audio stream 1450 * is controlled by this method. 1451 * 1452 * Such mixing occurs <strong>prior</strong> to overall volume scaling. 1453 * 1454 * @param level a floating point value between 1455 * {@code Float.NEGATIVE_INFINITY} to {@code +48.f}, 1456 * where {@code Float.NEGATIVE_INFINITY} means the Audio Description is not mixed 1457 * and a level of {@code 0.f} means the Audio Description is mixed without scaling. 1458 * @return true on success, false on failure. 1459 */ setAudioDescriptionMixLeveldB( @loatRangeto = 48.f, toInclusive = true) float level)1460 public boolean setAudioDescriptionMixLeveldB( 1461 @FloatRange(to = 48.f, toInclusive = true) float level) { 1462 if (!isValidAudioDescriptionMixLevel(level)) { 1463 throw new IllegalArgumentException("level is out of range" + level); 1464 } 1465 return native_set_audio_description_mix_level_db(level) == SUCCESS; 1466 } 1467 1468 /** 1469 * Returns the Audio Description mix level in dB. 1470 * 1471 * If Audio Description mixing is unavailable from the hardware device, 1472 * a value of {@code Float.NEGATIVE_INFINITY} is returned. 1473 * 1474 * @return the current Audio Description Mix Level in dB. 1475 * A value of {@code Float.NEGATIVE_INFINITY} means 1476 * that the audio description is not mixed or 1477 * the hardware is not available. 1478 * This should reflect the <strong>true</strong> internal device mix level; 1479 * hence the application might receive any floating value 1480 * except {@code Float.NaN}. 1481 */ getAudioDescriptionMixLeveldB()1482 public float getAudioDescriptionMixLeveldB() { 1483 float[] level = { Float.NEGATIVE_INFINITY }; 1484 try { 1485 final int status = native_get_audio_description_mix_level_db(level); 1486 if (status != SUCCESS || Float.isNaN(level[0])) { 1487 return Float.NEGATIVE_INFINITY; 1488 } 1489 } catch (Exception e) { 1490 return Float.NEGATIVE_INFINITY; 1491 } 1492 return level[0]; 1493 } 1494 isValidDualMonoMode(@ualMonoMode int dualMonoMode)1495 private static boolean isValidDualMonoMode(@DualMonoMode int dualMonoMode) { 1496 switch (dualMonoMode) { 1497 case DUAL_MONO_MODE_OFF: 1498 case DUAL_MONO_MODE_LR: 1499 case DUAL_MONO_MODE_LL: 1500 case DUAL_MONO_MODE_RR: 1501 return true; 1502 default: 1503 return false; 1504 } 1505 } 1506 1507 /** 1508 * Sets the Dual Mono mode presentation on the output device. 1509 * 1510 * The Dual Mono mode is generally applied to stereo audio streams 1511 * where the left and right channels come from separate sources. 1512 * 1513 * For compressed audio, where the decoding is done in hardware, 1514 * Dual Mono presentation needs to be performed 1515 * by the hardware output device 1516 * as the PCM audio is not available to the framework. 1517 * 1518 * @param dualMonoMode one of {@link #DUAL_MONO_MODE_OFF}, 1519 * {@link #DUAL_MONO_MODE_LR}, 1520 * {@link #DUAL_MONO_MODE_LL}, 1521 * {@link #DUAL_MONO_MODE_RR}. 1522 * 1523 * @return true on success, false on failure if the output device 1524 * does not support Dual Mono mode. 1525 */ setDualMonoMode(@ualMonoMode int dualMonoMode)1526 public boolean setDualMonoMode(@DualMonoMode int dualMonoMode) { 1527 if (!isValidDualMonoMode(dualMonoMode)) { 1528 throw new IllegalArgumentException( 1529 "Invalid Dual Mono mode " + dualMonoMode); 1530 } 1531 return native_set_dual_mono_mode(dualMonoMode) == SUCCESS; 1532 } 1533 1534 /** 1535 * Returns the Dual Mono mode presentation setting. 1536 * 1537 * If no Dual Mono presentation is available for the output device, 1538 * then {@link #DUAL_MONO_MODE_OFF} is returned. 1539 * 1540 * @return one of {@link #DUAL_MONO_MODE_OFF}, 1541 * {@link #DUAL_MONO_MODE_LR}, 1542 * {@link #DUAL_MONO_MODE_LL}, 1543 * {@link #DUAL_MONO_MODE_RR}. 1544 */ getDualMonoMode()1545 public @DualMonoMode int getDualMonoMode() { 1546 int[] dualMonoMode = { DUAL_MONO_MODE_OFF }; 1547 try { 1548 final int status = native_get_dual_mono_mode(dualMonoMode); 1549 if (status != SUCCESS || !isValidDualMonoMode(dualMonoMode[0])) { 1550 return DUAL_MONO_MODE_OFF; 1551 } 1552 } catch (Exception e) { 1553 return DUAL_MONO_MODE_OFF; 1554 } 1555 return dualMonoMode[0]; 1556 } 1557 1558 // mask of all the positional channels supported, however the allowed combinations 1559 // are further restricted by the matching left/right rule and 1560 // AudioSystem.OUT_CHANNEL_COUNT_MAX 1561 private static final int SUPPORTED_OUT_CHANNELS = 1562 AudioFormat.CHANNEL_OUT_FRONT_LEFT | 1563 AudioFormat.CHANNEL_OUT_FRONT_RIGHT | 1564 AudioFormat.CHANNEL_OUT_FRONT_CENTER | 1565 AudioFormat.CHANNEL_OUT_LOW_FREQUENCY | 1566 AudioFormat.CHANNEL_OUT_BACK_LEFT | 1567 AudioFormat.CHANNEL_OUT_BACK_RIGHT | 1568 AudioFormat.CHANNEL_OUT_BACK_CENTER | 1569 AudioFormat.CHANNEL_OUT_SIDE_LEFT | 1570 AudioFormat.CHANNEL_OUT_SIDE_RIGHT; 1571 1572 // Returns a boolean whether the attributes, format, bufferSizeInBytes, mode allow 1573 // power saving to be automatically enabled for an AudioTrack. Returns false if 1574 // power saving is already enabled in the attributes parameter. shouldEnablePowerSaving( @ullable AudioAttributes attributes, @Nullable AudioFormat format, int bufferSizeInBytes, int mode)1575 private static boolean shouldEnablePowerSaving( 1576 @Nullable AudioAttributes attributes, @Nullable AudioFormat format, 1577 int bufferSizeInBytes, int mode) { 1578 // If no attributes, OK 1579 // otherwise check attributes for USAGE_MEDIA and CONTENT_UNKNOWN, MUSIC, or MOVIE. 1580 // Only consider flags that are not compatible with FLAG_DEEP_BUFFER. We include 1581 // FLAG_DEEP_BUFFER because if set the request is explicit and 1582 // shouldEnablePowerSaving() should return false. 1583 final int flags = attributes.getAllFlags() 1584 & (AudioAttributes.FLAG_DEEP_BUFFER | AudioAttributes.FLAG_LOW_LATENCY 1585 | AudioAttributes.FLAG_HW_AV_SYNC | AudioAttributes.FLAG_BEACON); 1586 1587 if (attributes != null && 1588 (flags != 0 // cannot have any special flags 1589 || attributes.getUsage() != AudioAttributes.USAGE_MEDIA 1590 || (attributes.getContentType() != AudioAttributes.CONTENT_TYPE_UNKNOWN 1591 && attributes.getContentType() != AudioAttributes.CONTENT_TYPE_MUSIC 1592 && attributes.getContentType() != AudioAttributes.CONTENT_TYPE_MOVIE))) { 1593 return false; 1594 } 1595 1596 // Format must be fully specified and be linear pcm 1597 if (format == null 1598 || format.getSampleRate() == AudioFormat.SAMPLE_RATE_UNSPECIFIED 1599 || !AudioFormat.isEncodingLinearPcm(format.getEncoding()) 1600 || !AudioFormat.isValidEncoding(format.getEncoding()) 1601 || format.getChannelCount() < 1) { 1602 return false; 1603 } 1604 1605 // Mode must be streaming 1606 if (mode != MODE_STREAM) { 1607 return false; 1608 } 1609 1610 // A buffer size of 0 is always compatible with deep buffer (when called from the Builder) 1611 // but for app compatibility we only use deep buffer power saving for large buffer sizes. 1612 if (bufferSizeInBytes != 0) { 1613 final long BUFFER_TARGET_MODE_STREAM_MS = 100; 1614 final int MILLIS_PER_SECOND = 1000; 1615 final long bufferTargetSize = 1616 BUFFER_TARGET_MODE_STREAM_MS 1617 * format.getChannelCount() 1618 * format.getBytesPerSample(format.getEncoding()) 1619 * format.getSampleRate() 1620 / MILLIS_PER_SECOND; 1621 if (bufferSizeInBytes < bufferTargetSize) { 1622 return false; 1623 } 1624 } 1625 1626 return true; 1627 } 1628 1629 // Convenience method for the constructor's parameter checks. 1630 // This is where constructor IllegalArgumentException-s are thrown 1631 // postconditions: 1632 // mChannelCount is valid 1633 // mChannelMask is valid 1634 // mAudioFormat is valid 1635 // mSampleRate is valid 1636 // mDataLoadMode is valid audioParamCheck(int sampleRateInHz, int channelConfig, int channelIndexMask, int audioFormat, int mode)1637 private void audioParamCheck(int sampleRateInHz, int channelConfig, int channelIndexMask, 1638 int audioFormat, int mode) { 1639 //-------------- 1640 // sample rate, note these values are subject to change 1641 if ((sampleRateInHz < AudioFormat.SAMPLE_RATE_HZ_MIN || 1642 sampleRateInHz > AudioFormat.SAMPLE_RATE_HZ_MAX) && 1643 sampleRateInHz != AudioFormat.SAMPLE_RATE_UNSPECIFIED) { 1644 throw new IllegalArgumentException(sampleRateInHz 1645 + "Hz is not a supported sample rate."); 1646 } 1647 mSampleRate = sampleRateInHz; 1648 1649 // IEC61937 is based on stereo. We could coerce it to stereo. 1650 // But the application needs to know the stream is stereo so that 1651 // it is encoded and played correctly. So better to just reject it. 1652 if (audioFormat == AudioFormat.ENCODING_IEC61937 1653 && channelConfig != AudioFormat.CHANNEL_OUT_STEREO) { 1654 throw new IllegalArgumentException( 1655 "ENCODING_IEC61937 must be configured as CHANNEL_OUT_STEREO"); 1656 } 1657 1658 //-------------- 1659 // channel config 1660 mChannelConfiguration = channelConfig; 1661 1662 switch (channelConfig) { 1663 case AudioFormat.CHANNEL_OUT_DEFAULT: //AudioFormat.CHANNEL_CONFIGURATION_DEFAULT 1664 case AudioFormat.CHANNEL_OUT_MONO: 1665 case AudioFormat.CHANNEL_CONFIGURATION_MONO: 1666 mChannelCount = 1; 1667 mChannelMask = AudioFormat.CHANNEL_OUT_MONO; 1668 break; 1669 case AudioFormat.CHANNEL_OUT_STEREO: 1670 case AudioFormat.CHANNEL_CONFIGURATION_STEREO: 1671 mChannelCount = 2; 1672 mChannelMask = AudioFormat.CHANNEL_OUT_STEREO; 1673 break; 1674 default: 1675 if (channelConfig == AudioFormat.CHANNEL_INVALID && channelIndexMask != 0) { 1676 mChannelCount = 0; 1677 break; // channel index configuration only 1678 } 1679 if (!isMultichannelConfigSupported(channelConfig)) { 1680 // input channel configuration features unsupported channels 1681 throw new IllegalArgumentException("Unsupported channel configuration."); 1682 } 1683 mChannelMask = channelConfig; 1684 mChannelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig); 1685 } 1686 // check the channel index configuration (if present) 1687 mChannelIndexMask = channelIndexMask; 1688 if (mChannelIndexMask != 0) { 1689 // restrictive: indexMask could allow up to AUDIO_CHANNEL_BITS_LOG2 1690 final int indexMask = (1 << AudioSystem.OUT_CHANNEL_COUNT_MAX) - 1; 1691 if ((channelIndexMask & ~indexMask) != 0) { 1692 throw new IllegalArgumentException("Unsupported channel index configuration " 1693 + channelIndexMask); 1694 } 1695 int channelIndexCount = Integer.bitCount(channelIndexMask); 1696 if (mChannelCount == 0) { 1697 mChannelCount = channelIndexCount; 1698 } else if (mChannelCount != channelIndexCount) { 1699 throw new IllegalArgumentException("Channel count must match"); 1700 } 1701 } 1702 1703 //-------------- 1704 // audio format 1705 if (audioFormat == AudioFormat.ENCODING_DEFAULT) { 1706 audioFormat = AudioFormat.ENCODING_PCM_16BIT; 1707 } 1708 1709 if (!AudioFormat.isPublicEncoding(audioFormat)) { 1710 throw new IllegalArgumentException("Unsupported audio encoding."); 1711 } 1712 mAudioFormat = audioFormat; 1713 1714 //-------------- 1715 // audio load mode 1716 if (((mode != MODE_STREAM) && (mode != MODE_STATIC)) || 1717 ((mode != MODE_STREAM) && !AudioFormat.isEncodingLinearPcm(mAudioFormat))) { 1718 throw new IllegalArgumentException("Invalid mode."); 1719 } 1720 mDataLoadMode = mode; 1721 } 1722 1723 /** 1724 * Convenience method to check that the channel configuration (a.k.a channel mask) is supported 1725 * @param channelConfig the mask to validate 1726 * @return false if the AudioTrack can't be used with such a mask 1727 */ isMultichannelConfigSupported(int channelConfig)1728 private static boolean isMultichannelConfigSupported(int channelConfig) { 1729 // check for unsupported channels 1730 if ((channelConfig & SUPPORTED_OUT_CHANNELS) != channelConfig) { 1731 loge("Channel configuration features unsupported channels"); 1732 return false; 1733 } 1734 final int channelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig); 1735 if (channelCount > AudioSystem.OUT_CHANNEL_COUNT_MAX) { 1736 loge("Channel configuration contains too many channels " + 1737 channelCount + ">" + AudioSystem.OUT_CHANNEL_COUNT_MAX); 1738 return false; 1739 } 1740 // check for unsupported multichannel combinations: 1741 // - FL/FR must be present 1742 // - L/R channels must be paired (e.g. no single L channel) 1743 final int frontPair = 1744 AudioFormat.CHANNEL_OUT_FRONT_LEFT | AudioFormat.CHANNEL_OUT_FRONT_RIGHT; 1745 if ((channelConfig & frontPair) != frontPair) { 1746 loge("Front channels must be present in multichannel configurations"); 1747 return false; 1748 } 1749 final int backPair = 1750 AudioFormat.CHANNEL_OUT_BACK_LEFT | AudioFormat.CHANNEL_OUT_BACK_RIGHT; 1751 if ((channelConfig & backPair) != 0) { 1752 if ((channelConfig & backPair) != backPair) { 1753 loge("Rear channels can't be used independently"); 1754 return false; 1755 } 1756 } 1757 final int sidePair = 1758 AudioFormat.CHANNEL_OUT_SIDE_LEFT | AudioFormat.CHANNEL_OUT_SIDE_RIGHT; 1759 if ((channelConfig & sidePair) != 0 1760 && (channelConfig & sidePair) != sidePair) { 1761 loge("Side channels can't be used independently"); 1762 return false; 1763 } 1764 return true; 1765 } 1766 1767 1768 // Convenience method for the constructor's audio buffer size check. 1769 // preconditions: 1770 // mChannelCount is valid 1771 // mAudioFormat is valid 1772 // postcondition: 1773 // mNativeBufferSizeInBytes is valid (multiple of frame size, positive) audioBuffSizeCheck(int audioBufferSize)1774 private void audioBuffSizeCheck(int audioBufferSize) { 1775 // NB: this section is only valid with PCM or IEC61937 data. 1776 // To update when supporting compressed formats 1777 int frameSizeInBytes; 1778 if (AudioFormat.isEncodingLinearFrames(mAudioFormat)) { 1779 frameSizeInBytes = mChannelCount * AudioFormat.getBytesPerSample(mAudioFormat); 1780 } else { 1781 frameSizeInBytes = 1; 1782 } 1783 if ((audioBufferSize % frameSizeInBytes != 0) || (audioBufferSize < 1)) { 1784 throw new IllegalArgumentException("Invalid audio buffer size."); 1785 } 1786 1787 mNativeBufferSizeInBytes = audioBufferSize; 1788 mNativeBufferSizeInFrames = audioBufferSize / frameSizeInBytes; 1789 } 1790 1791 1792 /** 1793 * Releases the native AudioTrack resources. 1794 */ release()1795 public void release() { 1796 synchronized (mStreamEventCbLock){ 1797 endStreamEventHandling(); 1798 } 1799 // even though native_release() stops the native AudioTrack, we need to stop 1800 // AudioTrack subclasses too. 1801 try { 1802 stop(); 1803 } catch(IllegalStateException ise) { 1804 // don't raise an exception, we're releasing the resources. 1805 } 1806 baseRelease(); 1807 native_release(); 1808 synchronized (mPlayStateLock) { 1809 mState = STATE_UNINITIALIZED; 1810 mPlayState = PLAYSTATE_STOPPED; 1811 mPlayStateLock.notify(); 1812 } 1813 } 1814 1815 @Override finalize()1816 protected void finalize() { 1817 baseRelease(); 1818 native_finalize(); 1819 } 1820 1821 //-------------------------------------------------------------------------- 1822 // Getters 1823 //-------------------- 1824 /** 1825 * Returns the minimum gain value, which is the constant 0.0. 1826 * Gain values less than 0.0 will be clamped to 0.0. 1827 * <p>The word "volume" in the API name is historical; this is actually a linear gain. 1828 * @return the minimum value, which is the constant 0.0. 1829 */ getMinVolume()1830 static public float getMinVolume() { 1831 return GAIN_MIN; 1832 } 1833 1834 /** 1835 * Returns the maximum gain value, which is greater than or equal to 1.0. 1836 * Gain values greater than the maximum will be clamped to the maximum. 1837 * <p>The word "volume" in the API name is historical; this is actually a gain. 1838 * expressed as a linear multiplier on sample values, where a maximum value of 1.0 1839 * corresponds to a gain of 0 dB (sample values left unmodified). 1840 * @return the maximum value, which is greater than or equal to 1.0. 1841 */ getMaxVolume()1842 static public float getMaxVolume() { 1843 return GAIN_MAX; 1844 } 1845 1846 /** 1847 * Returns the configured audio source sample rate in Hz. 1848 * The initial source sample rate depends on the constructor parameters, 1849 * but the source sample rate may change if {@link #setPlaybackRate(int)} is called. 1850 * If the constructor had a specific sample rate, then the initial sink sample rate is that 1851 * value. 1852 * If the constructor had {@link AudioFormat#SAMPLE_RATE_UNSPECIFIED}, 1853 * then the initial sink sample rate is a route-dependent default value based on the source [sic]. 1854 */ getSampleRate()1855 public int getSampleRate() { 1856 return mSampleRate; 1857 } 1858 1859 /** 1860 * Returns the current playback sample rate rate in Hz. 1861 */ getPlaybackRate()1862 public int getPlaybackRate() { 1863 return native_get_playback_rate(); 1864 } 1865 1866 /** 1867 * Returns the current playback parameters. 1868 * See {@link #setPlaybackParams(PlaybackParams)} to set playback parameters 1869 * @return current {@link PlaybackParams}. 1870 * @throws IllegalStateException if track is not initialized. 1871 */ getPlaybackParams()1872 public @NonNull PlaybackParams getPlaybackParams() { 1873 return native_get_playback_params(); 1874 } 1875 1876 /** 1877 * Returns the {@link AudioAttributes} used in configuration. 1878 * If a {@code streamType} is used instead of an {@code AudioAttributes} 1879 * to configure the AudioTrack 1880 * (the use of {@code streamType} for configuration is deprecated), 1881 * then the {@code AudioAttributes} 1882 * equivalent to the {@code streamType} is returned. 1883 * @return The {@code AudioAttributes} used to configure the AudioTrack. 1884 * @throws IllegalStateException If the track is not initialized. 1885 */ getAudioAttributes()1886 public @NonNull AudioAttributes getAudioAttributes() { 1887 if (mState == STATE_UNINITIALIZED || mConfiguredAudioAttributes == null) { 1888 throw new IllegalStateException("track not initialized"); 1889 } 1890 return mConfiguredAudioAttributes; 1891 } 1892 1893 /** 1894 * Returns the configured audio data encoding. See {@link AudioFormat#ENCODING_PCM_8BIT}, 1895 * {@link AudioFormat#ENCODING_PCM_16BIT}, and {@link AudioFormat#ENCODING_PCM_FLOAT}. 1896 */ getAudioFormat()1897 public int getAudioFormat() { 1898 return mAudioFormat; 1899 } 1900 1901 /** 1902 * Returns the volume stream type of this AudioTrack. 1903 * Compare the result against {@link AudioManager#STREAM_VOICE_CALL}, 1904 * {@link AudioManager#STREAM_SYSTEM}, {@link AudioManager#STREAM_RING}, 1905 * {@link AudioManager#STREAM_MUSIC}, {@link AudioManager#STREAM_ALARM}, 1906 * {@link AudioManager#STREAM_NOTIFICATION}, {@link AudioManager#STREAM_DTMF} or 1907 * {@link AudioManager#STREAM_ACCESSIBILITY}. 1908 */ getStreamType()1909 public int getStreamType() { 1910 return mStreamType; 1911 } 1912 1913 /** 1914 * Returns the configured channel position mask. 1915 * <p> For example, refer to {@link AudioFormat#CHANNEL_OUT_MONO}, 1916 * {@link AudioFormat#CHANNEL_OUT_STEREO}, {@link AudioFormat#CHANNEL_OUT_5POINT1}. 1917 * This method may return {@link AudioFormat#CHANNEL_INVALID} if 1918 * a channel index mask was used. Consider 1919 * {@link #getFormat()} instead, to obtain an {@link AudioFormat}, 1920 * which contains both the channel position mask and the channel index mask. 1921 */ getChannelConfiguration()1922 public int getChannelConfiguration() { 1923 return mChannelConfiguration; 1924 } 1925 1926 /** 1927 * Returns the configured <code>AudioTrack</code> format. 1928 * @return an {@link AudioFormat} containing the 1929 * <code>AudioTrack</code> parameters at the time of configuration. 1930 */ getFormat()1931 public @NonNull AudioFormat getFormat() { 1932 AudioFormat.Builder builder = new AudioFormat.Builder() 1933 .setSampleRate(mSampleRate) 1934 .setEncoding(mAudioFormat); 1935 if (mChannelConfiguration != AudioFormat.CHANNEL_INVALID) { 1936 builder.setChannelMask(mChannelConfiguration); 1937 } 1938 if (mChannelIndexMask != AudioFormat.CHANNEL_INVALID /* 0 */) { 1939 builder.setChannelIndexMask(mChannelIndexMask); 1940 } 1941 return builder.build(); 1942 } 1943 1944 /** 1945 * Returns the configured number of channels. 1946 */ getChannelCount()1947 public int getChannelCount() { 1948 return mChannelCount; 1949 } 1950 1951 /** 1952 * Returns the state of the AudioTrack instance. This is useful after the 1953 * AudioTrack instance has been created to check if it was initialized 1954 * properly. This ensures that the appropriate resources have been acquired. 1955 * @see #STATE_UNINITIALIZED 1956 * @see #STATE_INITIALIZED 1957 * @see #STATE_NO_STATIC_DATA 1958 */ getState()1959 public int getState() { 1960 return mState; 1961 } 1962 1963 /** 1964 * Returns the playback state of the AudioTrack instance. 1965 * @see #PLAYSTATE_STOPPED 1966 * @see #PLAYSTATE_PAUSED 1967 * @see #PLAYSTATE_PLAYING 1968 */ getPlayState()1969 public int getPlayState() { 1970 synchronized (mPlayStateLock) { 1971 switch (mPlayState) { 1972 case PLAYSTATE_STOPPING: 1973 return PLAYSTATE_PLAYING; 1974 case PLAYSTATE_PAUSED_STOPPING: 1975 return PLAYSTATE_PAUSED; 1976 default: 1977 return mPlayState; 1978 } 1979 } 1980 } 1981 1982 1983 /** 1984 * Returns the effective size of the <code>AudioTrack</code> buffer 1985 * that the application writes to. 1986 * <p> This will be less than or equal to the result of 1987 * {@link #getBufferCapacityInFrames()}. 1988 * It will be equal if {@link #setBufferSizeInFrames(int)} has never been called. 1989 * <p> If the track is subsequently routed to a different output sink, the buffer 1990 * size and capacity may enlarge to accommodate. 1991 * <p> If the <code>AudioTrack</code> encoding indicates compressed data, 1992 * e.g. {@link AudioFormat#ENCODING_AC3}, then the frame count returned is 1993 * the size of the <code>AudioTrack</code> buffer in bytes. 1994 * <p> See also {@link AudioManager#getProperty(String)} for key 1995 * {@link AudioManager#PROPERTY_OUTPUT_FRAMES_PER_BUFFER}. 1996 * @return current size in frames of the <code>AudioTrack</code> buffer. 1997 * @throws IllegalStateException if track is not initialized. 1998 */ getBufferSizeInFrames()1999 public @IntRange (from = 0) int getBufferSizeInFrames() { 2000 return native_get_buffer_size_frames(); 2001 } 2002 2003 /** 2004 * Limits the effective size of the <code>AudioTrack</code> buffer 2005 * that the application writes to. 2006 * <p> A write to this AudioTrack will not fill the buffer beyond this limit. 2007 * If a blocking write is used then the write will block until the data 2008 * can fit within this limit. 2009 * <p>Changing this limit modifies the latency associated with 2010 * the buffer for this track. A smaller size will give lower latency 2011 * but there may be more glitches due to buffer underruns. 2012 * <p>The actual size used may not be equal to this requested size. 2013 * It will be limited to a valid range with a maximum of 2014 * {@link #getBufferCapacityInFrames()}. 2015 * It may also be adjusted slightly for internal reasons. 2016 * If bufferSizeInFrames is less than zero then {@link #ERROR_BAD_VALUE} 2017 * will be returned. 2018 * <p>This method is only supported for PCM audio. 2019 * It is not supported for compressed audio tracks. 2020 * 2021 * @param bufferSizeInFrames requested buffer size in frames 2022 * @return the actual buffer size in frames or an error code, 2023 * {@link #ERROR_BAD_VALUE}, {@link #ERROR_INVALID_OPERATION} 2024 * @throws IllegalStateException if track is not initialized. 2025 */ setBufferSizeInFrames(@ntRange from = 0) int bufferSizeInFrames)2026 public int setBufferSizeInFrames(@IntRange (from = 0) int bufferSizeInFrames) { 2027 if (mDataLoadMode == MODE_STATIC || mState == STATE_UNINITIALIZED) { 2028 return ERROR_INVALID_OPERATION; 2029 } 2030 if (bufferSizeInFrames < 0) { 2031 return ERROR_BAD_VALUE; 2032 } 2033 return native_set_buffer_size_frames(bufferSizeInFrames); 2034 } 2035 2036 /** 2037 * Returns the maximum size of the <code>AudioTrack</code> buffer in frames. 2038 * <p> If the track's creation mode is {@link #MODE_STATIC}, 2039 * it is equal to the specified bufferSizeInBytes on construction, converted to frame units. 2040 * A static track's frame count will not change. 2041 * <p> If the track's creation mode is {@link #MODE_STREAM}, 2042 * it is greater than or equal to the specified bufferSizeInBytes converted to frame units. 2043 * For streaming tracks, this value may be rounded up to a larger value if needed by 2044 * the target output sink, and 2045 * if the track is subsequently routed to a different output sink, the 2046 * frame count may enlarge to accommodate. 2047 * <p> If the <code>AudioTrack</code> encoding indicates compressed data, 2048 * e.g. {@link AudioFormat#ENCODING_AC3}, then the frame count returned is 2049 * the size of the <code>AudioTrack</code> buffer in bytes. 2050 * <p> See also {@link AudioManager#getProperty(String)} for key 2051 * {@link AudioManager#PROPERTY_OUTPUT_FRAMES_PER_BUFFER}. 2052 * @return maximum size in frames of the <code>AudioTrack</code> buffer. 2053 * @throws IllegalStateException if track is not initialized. 2054 */ getBufferCapacityInFrames()2055 public @IntRange (from = 0) int getBufferCapacityInFrames() { 2056 return native_get_buffer_capacity_frames(); 2057 } 2058 2059 /** 2060 * Returns the frame count of the native <code>AudioTrack</code> buffer. 2061 * @return current size in frames of the <code>AudioTrack</code> buffer. 2062 * @throws IllegalStateException 2063 * @deprecated Use the identical public method {@link #getBufferSizeInFrames()} instead. 2064 */ 2065 @Deprecated getNativeFrameCount()2066 protected int getNativeFrameCount() { 2067 return native_get_buffer_capacity_frames(); 2068 } 2069 2070 /** 2071 * Returns marker position expressed in frames. 2072 * @return marker position in wrapping frame units similar to {@link #getPlaybackHeadPosition}, 2073 * or zero if marker is disabled. 2074 */ getNotificationMarkerPosition()2075 public int getNotificationMarkerPosition() { 2076 return native_get_marker_pos(); 2077 } 2078 2079 /** 2080 * Returns the notification update period expressed in frames. 2081 * Zero means that no position update notifications are being delivered. 2082 */ getPositionNotificationPeriod()2083 public int getPositionNotificationPeriod() { 2084 return native_get_pos_update_period(); 2085 } 2086 2087 /** 2088 * Returns the playback head position expressed in frames. 2089 * Though the "int" type is signed 32-bits, the value should be reinterpreted as if it is 2090 * unsigned 32-bits. That is, the next position after 0x7FFFFFFF is (int) 0x80000000. 2091 * This is a continuously advancing counter. It will wrap (overflow) periodically, 2092 * for example approximately once every 27:03:11 hours:minutes:seconds at 44.1 kHz. 2093 * It is reset to zero by {@link #flush()}, {@link #reloadStaticData()}, and {@link #stop()}. 2094 * If the track's creation mode is {@link #MODE_STATIC}, the return value indicates 2095 * the total number of frames played since reset, 2096 * <i>not</i> the current offset within the buffer. 2097 */ getPlaybackHeadPosition()2098 public int getPlaybackHeadPosition() { 2099 return native_get_position(); 2100 } 2101 2102 /** 2103 * Returns this track's estimated latency in milliseconds. This includes the latency due 2104 * to AudioTrack buffer size, AudioMixer (if any) and audio hardware driver. 2105 * 2106 * DO NOT UNHIDE. The existing approach for doing A/V sync has too many problems. We need 2107 * a better solution. 2108 * @hide 2109 */ 2110 @UnsupportedAppUsage(trackingBug = 130237544) getLatency()2111 public int getLatency() { 2112 return native_get_latency(); 2113 } 2114 2115 /** 2116 * Returns the number of underrun occurrences in the application-level write buffer 2117 * since the AudioTrack was created. 2118 * An underrun occurs if the application does not write audio 2119 * data quickly enough, causing the buffer to underflow 2120 * and a potential audio glitch or pop. 2121 * <p> 2122 * Underruns are less likely when buffer sizes are large. 2123 * It may be possible to eliminate underruns by recreating the AudioTrack with 2124 * a larger buffer. 2125 * Or by using {@link #setBufferSizeInFrames(int)} to dynamically increase the 2126 * effective size of the buffer. 2127 */ getUnderrunCount()2128 public int getUnderrunCount() { 2129 return native_get_underrun_count(); 2130 } 2131 2132 /** 2133 * Returns the current performance mode of the {@link AudioTrack}. 2134 * 2135 * @return one of {@link AudioTrack#PERFORMANCE_MODE_NONE}, 2136 * {@link AudioTrack#PERFORMANCE_MODE_LOW_LATENCY}, 2137 * or {@link AudioTrack#PERFORMANCE_MODE_POWER_SAVING}. 2138 * Use {@link AudioTrack.Builder#setPerformanceMode} 2139 * in the {@link AudioTrack.Builder} to enable a performance mode. 2140 * @throws IllegalStateException if track is not initialized. 2141 */ getPerformanceMode()2142 public @PerformanceMode int getPerformanceMode() { 2143 final int flags = native_get_flags(); 2144 if ((flags & AUDIO_OUTPUT_FLAG_FAST) != 0) { 2145 return PERFORMANCE_MODE_LOW_LATENCY; 2146 } else if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) { 2147 return PERFORMANCE_MODE_POWER_SAVING; 2148 } else { 2149 return PERFORMANCE_MODE_NONE; 2150 } 2151 } 2152 2153 /** 2154 * Returns the output sample rate in Hz for the specified stream type. 2155 */ getNativeOutputSampleRate(int streamType)2156 static public int getNativeOutputSampleRate(int streamType) { 2157 return native_get_output_sample_rate(streamType); 2158 } 2159 2160 /** 2161 * Returns the estimated minimum buffer size required for an AudioTrack 2162 * object to be created in the {@link #MODE_STREAM} mode. 2163 * The size is an estimate because it does not consider either the route or the sink, 2164 * since neither is known yet. Note that this size doesn't 2165 * guarantee a smooth playback under load, and higher values should be chosen according to 2166 * the expected frequency at which the buffer will be refilled with additional data to play. 2167 * For example, if you intend to dynamically set the source sample rate of an AudioTrack 2168 * to a higher value than the initial source sample rate, be sure to configure the buffer size 2169 * based on the highest planned sample rate. 2170 * @param sampleRateInHz the source sample rate expressed in Hz. 2171 * {@link AudioFormat#SAMPLE_RATE_UNSPECIFIED} is not permitted. 2172 * @param channelConfig describes the configuration of the audio channels. 2173 * See {@link AudioFormat#CHANNEL_OUT_MONO} and 2174 * {@link AudioFormat#CHANNEL_OUT_STEREO} 2175 * @param audioFormat the format in which the audio data is represented. 2176 * See {@link AudioFormat#ENCODING_PCM_16BIT} and 2177 * {@link AudioFormat#ENCODING_PCM_8BIT}, 2178 * and {@link AudioFormat#ENCODING_PCM_FLOAT}. 2179 * @return {@link #ERROR_BAD_VALUE} if an invalid parameter was passed, 2180 * or {@link #ERROR} if unable to query for output properties, 2181 * or the minimum buffer size expressed in bytes. 2182 */ getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat)2183 static public int getMinBufferSize(int sampleRateInHz, int channelConfig, int audioFormat) { 2184 int channelCount = 0; 2185 switch(channelConfig) { 2186 case AudioFormat.CHANNEL_OUT_MONO: 2187 case AudioFormat.CHANNEL_CONFIGURATION_MONO: 2188 channelCount = 1; 2189 break; 2190 case AudioFormat.CHANNEL_OUT_STEREO: 2191 case AudioFormat.CHANNEL_CONFIGURATION_STEREO: 2192 channelCount = 2; 2193 break; 2194 default: 2195 if (!isMultichannelConfigSupported(channelConfig)) { 2196 loge("getMinBufferSize(): Invalid channel configuration."); 2197 return ERROR_BAD_VALUE; 2198 } else { 2199 channelCount = AudioFormat.channelCountFromOutChannelMask(channelConfig); 2200 } 2201 } 2202 2203 if (!AudioFormat.isPublicEncoding(audioFormat)) { 2204 loge("getMinBufferSize(): Invalid audio format."); 2205 return ERROR_BAD_VALUE; 2206 } 2207 2208 // sample rate, note these values are subject to change 2209 // Note: AudioFormat.SAMPLE_RATE_UNSPECIFIED is not allowed 2210 if ( (sampleRateInHz < AudioFormat.SAMPLE_RATE_HZ_MIN) || 2211 (sampleRateInHz > AudioFormat.SAMPLE_RATE_HZ_MAX) ) { 2212 loge("getMinBufferSize(): " + sampleRateInHz + " Hz is not a supported sample rate."); 2213 return ERROR_BAD_VALUE; 2214 } 2215 2216 int size = native_get_min_buff_size(sampleRateInHz, channelCount, audioFormat); 2217 if (size <= 0) { 2218 loge("getMinBufferSize(): error querying hardware"); 2219 return ERROR; 2220 } 2221 else { 2222 return size; 2223 } 2224 } 2225 2226 /** 2227 * Returns the audio session ID. 2228 * 2229 * @return the ID of the audio session this AudioTrack belongs to. 2230 */ getAudioSessionId()2231 public int getAudioSessionId() { 2232 return mSessionId; 2233 } 2234 2235 /** 2236 * Poll for a timestamp on demand. 2237 * <p> 2238 * If you need to track timestamps during initial warmup or after a routing or mode change, 2239 * you should request a new timestamp periodically until the reported timestamps 2240 * show that the frame position is advancing, or until it becomes clear that 2241 * timestamps are unavailable for this route. 2242 * <p> 2243 * After the clock is advancing at a stable rate, 2244 * query for a new timestamp approximately once every 10 seconds to once per minute. 2245 * Calling this method more often is inefficient. 2246 * It is also counter-productive to call this method more often than recommended, 2247 * because the short-term differences between successive timestamp reports are not meaningful. 2248 * If you need a high-resolution mapping between frame position and presentation time, 2249 * consider implementing that at application level, based on low-resolution timestamps. 2250 * <p> 2251 * The audio data at the returned position may either already have been 2252 * presented, or may have not yet been presented but is committed to be presented. 2253 * It is not possible to request the time corresponding to a particular position, 2254 * or to request the (fractional) position corresponding to a particular time. 2255 * If you need such features, consider implementing them at application level. 2256 * 2257 * @param timestamp a reference to a non-null AudioTimestamp instance allocated 2258 * and owned by caller. 2259 * @return true if a timestamp is available, or false if no timestamp is available. 2260 * If a timestamp is available, 2261 * the AudioTimestamp instance is filled in with a position in frame units, together 2262 * with the estimated time when that frame was presented or is committed to 2263 * be presented. 2264 * In the case that no timestamp is available, any supplied instance is left unaltered. 2265 * A timestamp may be temporarily unavailable while the audio clock is stabilizing, 2266 * or during and immediately after a route change. 2267 * A timestamp is permanently unavailable for a given route if the route does not support 2268 * timestamps. In this case, the approximate frame position can be obtained 2269 * using {@link #getPlaybackHeadPosition}. 2270 * However, it may be useful to continue to query for 2271 * timestamps occasionally, to recover after a route change. 2272 */ 2273 // Add this text when the "on new timestamp" API is added: 2274 // Use if you need to get the most recent timestamp outside of the event callback handler. getTimestamp(AudioTimestamp timestamp)2275 public boolean getTimestamp(AudioTimestamp timestamp) 2276 { 2277 if (timestamp == null) { 2278 throw new IllegalArgumentException(); 2279 } 2280 // It's unfortunate, but we have to either create garbage every time or use synchronized 2281 long[] longArray = new long[2]; 2282 int ret = native_get_timestamp(longArray); 2283 if (ret != SUCCESS) { 2284 return false; 2285 } 2286 timestamp.framePosition = longArray[0]; 2287 timestamp.nanoTime = longArray[1]; 2288 return true; 2289 } 2290 2291 /** 2292 * Poll for a timestamp on demand. 2293 * <p> 2294 * Same as {@link #getTimestamp(AudioTimestamp)} but with a more useful return code. 2295 * 2296 * @param timestamp a reference to a non-null AudioTimestamp instance allocated 2297 * and owned by caller. 2298 * @return {@link #SUCCESS} if a timestamp is available 2299 * {@link #ERROR_WOULD_BLOCK} if called in STOPPED or FLUSHED state, or if called 2300 * immediately after start/ACTIVE, when the number of frames consumed is less than the 2301 * overall hardware latency to physical output. In WOULD_BLOCK cases, one might poll 2302 * again, or use {@link #getPlaybackHeadPosition}, or use 0 position and current time 2303 * for the timestamp. 2304 * {@link #ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 2305 * needs to be recreated. 2306 * {@link #ERROR_INVALID_OPERATION} if current route does not support 2307 * timestamps. In this case, the approximate frame position can be obtained 2308 * using {@link #getPlaybackHeadPosition}. 2309 * 2310 * The AudioTimestamp instance is filled in with a position in frame units, together 2311 * with the estimated time when that frame was presented or is committed to 2312 * be presented. 2313 * @hide 2314 */ 2315 // Add this text when the "on new timestamp" API is added: 2316 // Use if you need to get the most recent timestamp outside of the event callback handler. getTimestampWithStatus(AudioTimestamp timestamp)2317 public int getTimestampWithStatus(AudioTimestamp timestamp) 2318 { 2319 if (timestamp == null) { 2320 throw new IllegalArgumentException(); 2321 } 2322 // It's unfortunate, but we have to either create garbage every time or use synchronized 2323 long[] longArray = new long[2]; 2324 int ret = native_get_timestamp(longArray); 2325 timestamp.framePosition = longArray[0]; 2326 timestamp.nanoTime = longArray[1]; 2327 return ret; 2328 } 2329 2330 /** 2331 * Return Metrics data about the current AudioTrack instance. 2332 * 2333 * @return a {@link PersistableBundle} containing the set of attributes and values 2334 * available for the media being handled by this instance of AudioTrack 2335 * The attributes are descibed in {@link MetricsConstants}. 2336 * 2337 * Additional vendor-specific fields may also be present in 2338 * the return value. 2339 */ getMetrics()2340 public PersistableBundle getMetrics() { 2341 PersistableBundle bundle = native_getMetrics(); 2342 return bundle; 2343 } 2344 native_getMetrics()2345 private native PersistableBundle native_getMetrics(); 2346 2347 //-------------------------------------------------------------------------- 2348 // Initialization / configuration 2349 //-------------------- 2350 /** 2351 * Sets the listener the AudioTrack notifies when a previously set marker is reached or 2352 * for each periodic playback head position update. 2353 * Notifications will be received in the same thread as the one in which the AudioTrack 2354 * instance was created. 2355 * @param listener 2356 */ setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener)2357 public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener) { 2358 setPlaybackPositionUpdateListener(listener, null); 2359 } 2360 2361 /** 2362 * Sets the listener the AudioTrack notifies when a previously set marker is reached or 2363 * for each periodic playback head position update. 2364 * Use this method to receive AudioTrack events in the Handler associated with another 2365 * thread than the one in which you created the AudioTrack instance. 2366 * @param listener 2367 * @param handler the Handler that will receive the event notification messages. 2368 */ setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener, Handler handler)2369 public void setPlaybackPositionUpdateListener(OnPlaybackPositionUpdateListener listener, 2370 Handler handler) { 2371 if (listener != null) { 2372 mEventHandlerDelegate = new NativePositionEventHandlerDelegate(this, listener, handler); 2373 } else { 2374 mEventHandlerDelegate = null; 2375 } 2376 } 2377 2378 clampGainOrLevel(float gainOrLevel)2379 private static float clampGainOrLevel(float gainOrLevel) { 2380 if (Float.isNaN(gainOrLevel)) { 2381 throw new IllegalArgumentException(); 2382 } 2383 if (gainOrLevel < GAIN_MIN) { 2384 gainOrLevel = GAIN_MIN; 2385 } else if (gainOrLevel > GAIN_MAX) { 2386 gainOrLevel = GAIN_MAX; 2387 } 2388 return gainOrLevel; 2389 } 2390 2391 2392 /** 2393 * Sets the specified left and right output gain values on the AudioTrack. 2394 * <p>Gain values are clamped to the closed interval [0.0, max] where 2395 * max is the value of {@link #getMaxVolume}. 2396 * A value of 0.0 results in zero gain (silence), and 2397 * a value of 1.0 means unity gain (signal unchanged). 2398 * The default value is 1.0 meaning unity gain. 2399 * <p>The word "volume" in the API name is historical; this is actually a linear gain. 2400 * @param leftGain output gain for the left channel. 2401 * @param rightGain output gain for the right channel 2402 * @return error code or success, see {@link #SUCCESS}, 2403 * {@link #ERROR_INVALID_OPERATION} 2404 * @deprecated Applications should use {@link #setVolume} instead, as it 2405 * more gracefully scales down to mono, and up to multi-channel content beyond stereo. 2406 */ 2407 @Deprecated setStereoVolume(float leftGain, float rightGain)2408 public int setStereoVolume(float leftGain, float rightGain) { 2409 if (mState == STATE_UNINITIALIZED) { 2410 return ERROR_INVALID_OPERATION; 2411 } 2412 2413 baseSetVolume(leftGain, rightGain); 2414 return SUCCESS; 2415 } 2416 2417 @Override playerSetVolume(boolean muting, float leftVolume, float rightVolume)2418 void playerSetVolume(boolean muting, float leftVolume, float rightVolume) { 2419 leftVolume = clampGainOrLevel(muting ? 0.0f : leftVolume); 2420 rightVolume = clampGainOrLevel(muting ? 0.0f : rightVolume); 2421 2422 native_setVolume(leftVolume, rightVolume); 2423 } 2424 2425 2426 /** 2427 * Sets the specified output gain value on all channels of this track. 2428 * <p>Gain values are clamped to the closed interval [0.0, max] where 2429 * max is the value of {@link #getMaxVolume}. 2430 * A value of 0.0 results in zero gain (silence), and 2431 * a value of 1.0 means unity gain (signal unchanged). 2432 * The default value is 1.0 meaning unity gain. 2433 * <p>This API is preferred over {@link #setStereoVolume}, as it 2434 * more gracefully scales down to mono, and up to multi-channel content beyond stereo. 2435 * <p>The word "volume" in the API name is historical; this is actually a linear gain. 2436 * @param gain output gain for all channels. 2437 * @return error code or success, see {@link #SUCCESS}, 2438 * {@link #ERROR_INVALID_OPERATION} 2439 */ setVolume(float gain)2440 public int setVolume(float gain) { 2441 return setStereoVolume(gain, gain); 2442 } 2443 2444 @Override playerApplyVolumeShaper( @onNull VolumeShaper.Configuration configuration, @NonNull VolumeShaper.Operation operation)2445 /* package */ int playerApplyVolumeShaper( 2446 @NonNull VolumeShaper.Configuration configuration, 2447 @NonNull VolumeShaper.Operation operation) { 2448 return native_applyVolumeShaper(configuration, operation); 2449 } 2450 2451 @Override playerGetVolumeShaperState(int id)2452 /* package */ @Nullable VolumeShaper.State playerGetVolumeShaperState(int id) { 2453 return native_getVolumeShaperState(id); 2454 } 2455 2456 @Override createVolumeShaper( @onNull VolumeShaper.Configuration configuration)2457 public @NonNull VolumeShaper createVolumeShaper( 2458 @NonNull VolumeShaper.Configuration configuration) { 2459 return new VolumeShaper(configuration, this); 2460 } 2461 2462 /** 2463 * Sets the playback sample rate for this track. This sets the sampling rate at which 2464 * the audio data will be consumed and played back 2465 * (as set by the sampleRateInHz parameter in the 2466 * {@link #AudioTrack(int, int, int, int, int, int)} constructor), 2467 * not the original sampling rate of the 2468 * content. For example, setting it to half the sample rate of the content will cause the 2469 * playback to last twice as long, but will also result in a pitch shift down by one octave. 2470 * The valid sample rate range is from 1 Hz to twice the value returned by 2471 * {@link #getNativeOutputSampleRate(int)}. 2472 * Use {@link #setPlaybackParams(PlaybackParams)} for speed control. 2473 * <p> This method may also be used to repurpose an existing <code>AudioTrack</code> 2474 * for playback of content of differing sample rate, 2475 * but with identical encoding and channel mask. 2476 * @param sampleRateInHz the sample rate expressed in Hz 2477 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 2478 * {@link #ERROR_INVALID_OPERATION} 2479 */ setPlaybackRate(int sampleRateInHz)2480 public int setPlaybackRate(int sampleRateInHz) { 2481 if (mState != STATE_INITIALIZED) { 2482 return ERROR_INVALID_OPERATION; 2483 } 2484 if (sampleRateInHz <= 0) { 2485 return ERROR_BAD_VALUE; 2486 } 2487 return native_set_playback_rate(sampleRateInHz); 2488 } 2489 2490 2491 /** 2492 * Sets the playback parameters. 2493 * This method returns failure if it cannot apply the playback parameters. 2494 * One possible cause is that the parameters for speed or pitch are out of range. 2495 * Another possible cause is that the <code>AudioTrack</code> is streaming 2496 * (see {@link #MODE_STREAM}) and the 2497 * buffer size is too small. For speeds greater than 1.0f, the <code>AudioTrack</code> buffer 2498 * on configuration must be larger than the speed multiplied by the minimum size 2499 * {@link #getMinBufferSize(int, int, int)}) to allow proper playback. 2500 * @param params see {@link PlaybackParams}. In particular, 2501 * speed, pitch, and audio mode should be set. 2502 * @throws IllegalArgumentException if the parameters are invalid or not accepted. 2503 * @throws IllegalStateException if track is not initialized. 2504 */ setPlaybackParams(@onNull PlaybackParams params)2505 public void setPlaybackParams(@NonNull PlaybackParams params) { 2506 if (params == null) { 2507 throw new IllegalArgumentException("params is null"); 2508 } 2509 native_set_playback_params(params); 2510 } 2511 2512 2513 /** 2514 * Sets the position of the notification marker. At most one marker can be active. 2515 * @param markerInFrames marker position in wrapping frame units similar to 2516 * {@link #getPlaybackHeadPosition}, or zero to disable the marker. 2517 * To set a marker at a position which would appear as zero due to wraparound, 2518 * a workaround is to use a non-zero position near zero, such as -1 or 1. 2519 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 2520 * {@link #ERROR_INVALID_OPERATION} 2521 */ setNotificationMarkerPosition(int markerInFrames)2522 public int setNotificationMarkerPosition(int markerInFrames) { 2523 if (mState == STATE_UNINITIALIZED) { 2524 return ERROR_INVALID_OPERATION; 2525 } 2526 return native_set_marker_pos(markerInFrames); 2527 } 2528 2529 2530 /** 2531 * Sets the period for the periodic notification event. 2532 * @param periodInFrames update period expressed in frames. 2533 * Zero period means no position updates. A negative period is not allowed. 2534 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_INVALID_OPERATION} 2535 */ setPositionNotificationPeriod(int periodInFrames)2536 public int setPositionNotificationPeriod(int periodInFrames) { 2537 if (mState == STATE_UNINITIALIZED) { 2538 return ERROR_INVALID_OPERATION; 2539 } 2540 return native_set_pos_update_period(periodInFrames); 2541 } 2542 2543 2544 /** 2545 * Sets the playback head position within the static buffer. 2546 * The track must be stopped or paused for the position to be changed, 2547 * and must use the {@link #MODE_STATIC} mode. 2548 * @param positionInFrames playback head position within buffer, expressed in frames. 2549 * Zero corresponds to start of buffer. 2550 * The position must not be greater than the buffer size in frames, or negative. 2551 * Though this method and {@link #getPlaybackHeadPosition()} have similar names, 2552 * the position values have different meanings. 2553 * <br> 2554 * If looping is currently enabled and the new position is greater than or equal to the 2555 * loop end marker, the behavior varies by API level: 2556 * as of {@link android.os.Build.VERSION_CODES#M}, 2557 * the looping is first disabled and then the position is set. 2558 * For earlier API levels, the behavior is unspecified. 2559 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 2560 * {@link #ERROR_INVALID_OPERATION} 2561 */ setPlaybackHeadPosition(@ntRange from = 0) int positionInFrames)2562 public int setPlaybackHeadPosition(@IntRange (from = 0) int positionInFrames) { 2563 if (mDataLoadMode == MODE_STREAM || mState == STATE_UNINITIALIZED || 2564 getPlayState() == PLAYSTATE_PLAYING) { 2565 return ERROR_INVALID_OPERATION; 2566 } 2567 if (!(0 <= positionInFrames && positionInFrames <= mNativeBufferSizeInFrames)) { 2568 return ERROR_BAD_VALUE; 2569 } 2570 return native_set_position(positionInFrames); 2571 } 2572 2573 /** 2574 * Sets the loop points and the loop count. The loop can be infinite. 2575 * Similarly to setPlaybackHeadPosition, 2576 * the track must be stopped or paused for the loop points to be changed, 2577 * and must use the {@link #MODE_STATIC} mode. 2578 * @param startInFrames loop start marker expressed in frames. 2579 * Zero corresponds to start of buffer. 2580 * The start marker must not be greater than or equal to the buffer size in frames, or negative. 2581 * @param endInFrames loop end marker expressed in frames. 2582 * The total buffer size in frames corresponds to end of buffer. 2583 * The end marker must not be greater than the buffer size in frames. 2584 * For looping, the end marker must not be less than or equal to the start marker, 2585 * but to disable looping 2586 * it is permitted for start marker, end marker, and loop count to all be 0. 2587 * If any input parameters are out of range, this method returns {@link #ERROR_BAD_VALUE}. 2588 * If the loop period (endInFrames - startInFrames) is too small for the implementation to 2589 * support, 2590 * {@link #ERROR_BAD_VALUE} is returned. 2591 * The loop range is the interval [startInFrames, endInFrames). 2592 * <br> 2593 * As of {@link android.os.Build.VERSION_CODES#M}, the position is left unchanged, 2594 * unless it is greater than or equal to the loop end marker, in which case 2595 * it is forced to the loop start marker. 2596 * For earlier API levels, the effect on position is unspecified. 2597 * @param loopCount the number of times the loop is looped; must be greater than or equal to -1. 2598 * A value of -1 means infinite looping, and 0 disables looping. 2599 * A value of positive N means to "loop" (go back) N times. For example, 2600 * a value of one means to play the region two times in total. 2601 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 2602 * {@link #ERROR_INVALID_OPERATION} 2603 */ setLoopPoints(@ntRange from = 0) int startInFrames, @IntRange (from = 0) int endInFrames, @IntRange (from = -1) int loopCount)2604 public int setLoopPoints(@IntRange (from = 0) int startInFrames, 2605 @IntRange (from = 0) int endInFrames, @IntRange (from = -1) int loopCount) { 2606 if (mDataLoadMode == MODE_STREAM || mState == STATE_UNINITIALIZED || 2607 getPlayState() == PLAYSTATE_PLAYING) { 2608 return ERROR_INVALID_OPERATION; 2609 } 2610 if (loopCount == 0) { 2611 ; // explicitly allowed as an exception to the loop region range check 2612 } else if (!(0 <= startInFrames && startInFrames < mNativeBufferSizeInFrames && 2613 startInFrames < endInFrames && endInFrames <= mNativeBufferSizeInFrames)) { 2614 return ERROR_BAD_VALUE; 2615 } 2616 return native_set_loop(startInFrames, endInFrames, loopCount); 2617 } 2618 2619 /** 2620 * Sets the audio presentation. 2621 * If the audio presentation is invalid then {@link #ERROR_BAD_VALUE} will be returned. 2622 * If a multi-stream decoder (MSD) is not present, or the format does not support 2623 * multiple presentations, then {@link #ERROR_INVALID_OPERATION} will be returned. 2624 * {@link #ERROR} is returned in case of any other error. 2625 * @param presentation see {@link AudioPresentation}. In particular, id should be set. 2626 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR}, 2627 * {@link #ERROR_BAD_VALUE}, {@link #ERROR_INVALID_OPERATION} 2628 * @throws IllegalArgumentException if the audio presentation is null. 2629 * @throws IllegalStateException if track is not initialized. 2630 */ setPresentation(@onNull AudioPresentation presentation)2631 public int setPresentation(@NonNull AudioPresentation presentation) { 2632 if (presentation == null) { 2633 throw new IllegalArgumentException("audio presentation is null"); 2634 } 2635 return native_setPresentation(presentation.getPresentationId(), 2636 presentation.getProgramId()); 2637 } 2638 2639 /** 2640 * Sets the initialization state of the instance. This method was originally intended to be used 2641 * in an AudioTrack subclass constructor to set a subclass-specific post-initialization state. 2642 * However, subclasses of AudioTrack are no longer recommended, so this method is obsolete. 2643 * @param state the state of the AudioTrack instance 2644 * @deprecated Only accessible by subclasses, which are not recommended for AudioTrack. 2645 */ 2646 @Deprecated setState(int state)2647 protected void setState(int state) { 2648 mState = state; 2649 } 2650 2651 2652 //--------------------------------------------------------- 2653 // Transport control methods 2654 //-------------------- 2655 /** 2656 * Starts playing an AudioTrack. 2657 * <p> 2658 * If track's creation mode is {@link #MODE_STATIC}, you must have called one of 2659 * the write methods ({@link #write(byte[], int, int)}, {@link #write(byte[], int, int, int)}, 2660 * {@link #write(short[], int, int)}, {@link #write(short[], int, int, int)}, 2661 * {@link #write(float[], int, int, int)}, or {@link #write(ByteBuffer, int, int)}) prior to 2662 * play(). 2663 * <p> 2664 * If the mode is {@link #MODE_STREAM}, you can optionally prime the data path prior to 2665 * calling play(), by writing up to <code>bufferSizeInBytes</code> (from constructor). 2666 * If you don't call write() first, or if you call write() but with an insufficient amount of 2667 * data, then the track will be in underrun state at play(). In this case, 2668 * playback will not actually start playing until the data path is filled to a 2669 * device-specific minimum level. This requirement for the path to be filled 2670 * to a minimum level is also true when resuming audio playback after calling stop(). 2671 * Similarly the buffer will need to be filled up again after 2672 * the track underruns due to failure to call write() in a timely manner with sufficient data. 2673 * For portability, an application should prime the data path to the maximum allowed 2674 * by writing data until the write() method returns a short transfer count. 2675 * This allows play() to start immediately, and reduces the chance of underrun. 2676 * 2677 * @throws IllegalStateException if the track isn't properly initialized 2678 */ play()2679 public void play() 2680 throws IllegalStateException { 2681 if (mState != STATE_INITIALIZED) { 2682 throw new IllegalStateException("play() called on uninitialized AudioTrack."); 2683 } 2684 //FIXME use lambda to pass startImpl to superclass 2685 final int delay = getStartDelayMs(); 2686 if (delay == 0) { 2687 startImpl(); 2688 } else { 2689 new Thread() { 2690 public void run() { 2691 try { 2692 Thread.sleep(delay); 2693 } catch (InterruptedException e) { 2694 e.printStackTrace(); 2695 } 2696 baseSetStartDelayMs(0); 2697 try { 2698 startImpl(); 2699 } catch (IllegalStateException e) { 2700 // fail silently for a state exception when it is happening after 2701 // a delayed start, as the player state could have changed between the 2702 // call to start() and the execution of startImpl() 2703 } 2704 } 2705 }.start(); 2706 } 2707 } 2708 startImpl()2709 private void startImpl() { 2710 synchronized(mPlayStateLock) { 2711 baseStart(); 2712 native_start(); 2713 if (mPlayState == PLAYSTATE_PAUSED_STOPPING) { 2714 mPlayState = PLAYSTATE_STOPPING; 2715 } else { 2716 mPlayState = PLAYSTATE_PLAYING; 2717 mOffloadEosPending = false; 2718 } 2719 } 2720 } 2721 2722 /** 2723 * Stops playing the audio data. 2724 * When used on an instance created in {@link #MODE_STREAM} mode, audio will stop playing 2725 * after the last buffer that was written has been played. For an immediate stop, use 2726 * {@link #pause()}, followed by {@link #flush()} to discard audio data that hasn't been played 2727 * back yet. 2728 * @throws IllegalStateException 2729 */ stop()2730 public void stop() 2731 throws IllegalStateException { 2732 if (mState != STATE_INITIALIZED) { 2733 throw new IllegalStateException("stop() called on uninitialized AudioTrack."); 2734 } 2735 2736 // stop playing 2737 synchronized(mPlayStateLock) { 2738 native_stop(); 2739 baseStop(); 2740 if (mOffloaded && mPlayState != PLAYSTATE_PAUSED_STOPPING) { 2741 mPlayState = PLAYSTATE_STOPPING; 2742 } else { 2743 mPlayState = PLAYSTATE_STOPPED; 2744 mOffloadEosPending = false; 2745 mAvSyncHeader = null; 2746 mAvSyncBytesRemaining = 0; 2747 mPlayStateLock.notify(); 2748 } 2749 } 2750 } 2751 2752 /** 2753 * Pauses the playback of the audio data. Data that has not been played 2754 * back will not be discarded. Subsequent calls to {@link #play} will play 2755 * this data back. See {@link #flush()} to discard this data. 2756 * 2757 * @throws IllegalStateException 2758 */ pause()2759 public void pause() 2760 throws IllegalStateException { 2761 if (mState != STATE_INITIALIZED) { 2762 throw new IllegalStateException("pause() called on uninitialized AudioTrack."); 2763 } 2764 2765 // pause playback 2766 synchronized(mPlayStateLock) { 2767 native_pause(); 2768 basePause(); 2769 if (mPlayState == PLAYSTATE_STOPPING) { 2770 mPlayState = PLAYSTATE_PAUSED_STOPPING; 2771 } else { 2772 mPlayState = PLAYSTATE_PAUSED; 2773 } 2774 } 2775 } 2776 2777 2778 //--------------------------------------------------------- 2779 // Audio data supply 2780 //-------------------- 2781 2782 /** 2783 * Flushes the audio data currently queued for playback. Any data that has 2784 * been written but not yet presented will be discarded. No-op if not stopped or paused, 2785 * or if the track's creation mode is not {@link #MODE_STREAM}. 2786 * <BR> Note that although data written but not yet presented is discarded, there is no 2787 * guarantee that all of the buffer space formerly used by that data 2788 * is available for a subsequent write. 2789 * For example, a call to {@link #write(byte[], int, int)} with <code>sizeInBytes</code> 2790 * less than or equal to the total buffer size 2791 * may return a short actual transfer count. 2792 */ flush()2793 public void flush() { 2794 if (mState == STATE_INITIALIZED) { 2795 // flush the data in native layer 2796 native_flush(); 2797 mAvSyncHeader = null; 2798 mAvSyncBytesRemaining = 0; 2799 } 2800 2801 } 2802 2803 /** 2804 * Writes the audio data to the audio sink for playback (streaming mode), 2805 * or copies audio data for later playback (static buffer mode). 2806 * The format specified in the AudioTrack constructor should be 2807 * {@link AudioFormat#ENCODING_PCM_8BIT} to correspond to the data in the array. 2808 * The format can be {@link AudioFormat#ENCODING_PCM_16BIT}, but this is deprecated. 2809 * <p> 2810 * In streaming mode, the write will normally block until all the data has been enqueued for 2811 * playback, and will return a full transfer count. However, if the track is stopped or paused 2812 * on entry, or another thread interrupts the write by calling stop or pause, or an I/O error 2813 * occurs during the write, then the write may return a short transfer count. 2814 * <p> 2815 * In static buffer mode, copies the data to the buffer starting at offset 0. 2816 * Note that the actual playback of this data might occur after this function returns. 2817 * 2818 * @param audioData the array that holds the data to play. 2819 * @param offsetInBytes the offset expressed in bytes in audioData where the data to write 2820 * starts. 2821 * Must not be negative, or cause the data access to go out of bounds of the array. 2822 * @param sizeInBytes the number of bytes to write in audioData after the offset. 2823 * Must not be negative, or cause the data access to go out of bounds of the array. 2824 * @return zero or the positive number of bytes that were written, or one of the following 2825 * error codes. The number of bytes will be a multiple of the frame size in bytes 2826 * not to exceed sizeInBytes. 2827 * <ul> 2828 * <li>{@link #ERROR_INVALID_OPERATION} if the track isn't properly initialized</li> 2829 * <li>{@link #ERROR_BAD_VALUE} if the parameters don't resolve to valid data and indexes</li> 2830 * <li>{@link #ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 2831 * needs to be recreated. The dead object error code is not returned if some data was 2832 * successfully transferred. In this case, the error is returned at the next write()</li> 2833 * <li>{@link #ERROR} in case of other error</li> 2834 * </ul> 2835 * This is equivalent to {@link #write(byte[], int, int, int)} with <code>writeMode</code> 2836 * set to {@link #WRITE_BLOCKING}. 2837 */ write(@onNull byte[] audioData, int offsetInBytes, int sizeInBytes)2838 public int write(@NonNull byte[] audioData, int offsetInBytes, int sizeInBytes) { 2839 return write(audioData, offsetInBytes, sizeInBytes, WRITE_BLOCKING); 2840 } 2841 2842 /** 2843 * Writes the audio data to the audio sink for playback (streaming mode), 2844 * or copies audio data for later playback (static buffer mode). 2845 * The format specified in the AudioTrack constructor should be 2846 * {@link AudioFormat#ENCODING_PCM_8BIT} to correspond to the data in the array. 2847 * The format can be {@link AudioFormat#ENCODING_PCM_16BIT}, but this is deprecated. 2848 * <p> 2849 * In streaming mode, the blocking behavior depends on the write mode. If the write mode is 2850 * {@link #WRITE_BLOCKING}, the write will normally block until all the data has been enqueued 2851 * for playback, and will return a full transfer count. However, if the write mode is 2852 * {@link #WRITE_NON_BLOCKING}, or the track is stopped or paused on entry, or another thread 2853 * interrupts the write by calling stop or pause, or an I/O error 2854 * occurs during the write, then the write may return a short transfer count. 2855 * <p> 2856 * In static buffer mode, copies the data to the buffer starting at offset 0, 2857 * and the write mode is ignored. 2858 * Note that the actual playback of this data might occur after this function returns. 2859 * 2860 * @param audioData the array that holds the data to play. 2861 * @param offsetInBytes the offset expressed in bytes in audioData where the data to write 2862 * starts. 2863 * Must not be negative, or cause the data access to go out of bounds of the array. 2864 * @param sizeInBytes the number of bytes to write in audioData after the offset. 2865 * Must not be negative, or cause the data access to go out of bounds of the array. 2866 * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no 2867 * effect in static mode. 2868 * <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written 2869 * to the audio sink. 2870 * <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after 2871 * queuing as much audio data for playback as possible without blocking. 2872 * @return zero or the positive number of bytes that were written, or one of the following 2873 * error codes. The number of bytes will be a multiple of the frame size in bytes 2874 * not to exceed sizeInBytes. 2875 * <ul> 2876 * <li>{@link #ERROR_INVALID_OPERATION} if the track isn't properly initialized</li> 2877 * <li>{@link #ERROR_BAD_VALUE} if the parameters don't resolve to valid data and indexes</li> 2878 * <li>{@link #ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 2879 * needs to be recreated. The dead object error code is not returned if some data was 2880 * successfully transferred. In this case, the error is returned at the next write()</li> 2881 * <li>{@link #ERROR} in case of other error</li> 2882 * </ul> 2883 */ write(@onNull byte[] audioData, int offsetInBytes, int sizeInBytes, @WriteMode int writeMode)2884 public int write(@NonNull byte[] audioData, int offsetInBytes, int sizeInBytes, 2885 @WriteMode int writeMode) { 2886 2887 if (mState == STATE_UNINITIALIZED || mAudioFormat == AudioFormat.ENCODING_PCM_FLOAT) { 2888 return ERROR_INVALID_OPERATION; 2889 } 2890 2891 if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) { 2892 Log.e(TAG, "AudioTrack.write() called with invalid blocking mode"); 2893 return ERROR_BAD_VALUE; 2894 } 2895 2896 if ( (audioData == null) || (offsetInBytes < 0 ) || (sizeInBytes < 0) 2897 || (offsetInBytes + sizeInBytes < 0) // detect integer overflow 2898 || (offsetInBytes + sizeInBytes > audioData.length)) { 2899 return ERROR_BAD_VALUE; 2900 } 2901 2902 if (!blockUntilOffloadDrain(writeMode)) { 2903 return 0; 2904 } 2905 2906 final int ret = native_write_byte(audioData, offsetInBytes, sizeInBytes, mAudioFormat, 2907 writeMode == WRITE_BLOCKING); 2908 2909 if ((mDataLoadMode == MODE_STATIC) 2910 && (mState == STATE_NO_STATIC_DATA) 2911 && (ret > 0)) { 2912 // benign race with respect to other APIs that read mState 2913 mState = STATE_INITIALIZED; 2914 } 2915 2916 return ret; 2917 } 2918 2919 /** 2920 * Writes the audio data to the audio sink for playback (streaming mode), 2921 * or copies audio data for later playback (static buffer mode). 2922 * The format specified in the AudioTrack constructor should be 2923 * {@link AudioFormat#ENCODING_PCM_16BIT} to correspond to the data in the array. 2924 * <p> 2925 * In streaming mode, the write will normally block until all the data has been enqueued for 2926 * playback, and will return a full transfer count. However, if the track is stopped or paused 2927 * on entry, or another thread interrupts the write by calling stop or pause, or an I/O error 2928 * occurs during the write, then the write may return a short transfer count. 2929 * <p> 2930 * In static buffer mode, copies the data to the buffer starting at offset 0. 2931 * Note that the actual playback of this data might occur after this function returns. 2932 * 2933 * @param audioData the array that holds the data to play. 2934 * @param offsetInShorts the offset expressed in shorts in audioData where the data to play 2935 * starts. 2936 * Must not be negative, or cause the data access to go out of bounds of the array. 2937 * @param sizeInShorts the number of shorts to read in audioData after the offset. 2938 * Must not be negative, or cause the data access to go out of bounds of the array. 2939 * @return zero or the positive number of shorts that were written, or one of the following 2940 * error codes. The number of shorts will be a multiple of the channel count not to 2941 * exceed sizeInShorts. 2942 * <ul> 2943 * <li>{@link #ERROR_INVALID_OPERATION} if the track isn't properly initialized</li> 2944 * <li>{@link #ERROR_BAD_VALUE} if the parameters don't resolve to valid data and indexes</li> 2945 * <li>{@link #ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 2946 * needs to be recreated. The dead object error code is not returned if some data was 2947 * successfully transferred. In this case, the error is returned at the next write()</li> 2948 * <li>{@link #ERROR} in case of other error</li> 2949 * </ul> 2950 * This is equivalent to {@link #write(short[], int, int, int)} with <code>writeMode</code> 2951 * set to {@link #WRITE_BLOCKING}. 2952 */ write(@onNull short[] audioData, int offsetInShorts, int sizeInShorts)2953 public int write(@NonNull short[] audioData, int offsetInShorts, int sizeInShorts) { 2954 return write(audioData, offsetInShorts, sizeInShorts, WRITE_BLOCKING); 2955 } 2956 2957 /** 2958 * Writes the audio data to the audio sink for playback (streaming mode), 2959 * or copies audio data for later playback (static buffer mode). 2960 * The format specified in the AudioTrack constructor should be 2961 * {@link AudioFormat#ENCODING_PCM_16BIT} to correspond to the data in the array. 2962 * <p> 2963 * In streaming mode, the blocking behavior depends on the write mode. If the write mode is 2964 * {@link #WRITE_BLOCKING}, the write will normally block until all the data has been enqueued 2965 * for playback, and will return a full transfer count. However, if the write mode is 2966 * {@link #WRITE_NON_BLOCKING}, or the track is stopped or paused on entry, or another thread 2967 * interrupts the write by calling stop or pause, or an I/O error 2968 * occurs during the write, then the write may return a short transfer count. 2969 * <p> 2970 * In static buffer mode, copies the data to the buffer starting at offset 0. 2971 * Note that the actual playback of this data might occur after this function returns. 2972 * 2973 * @param audioData the array that holds the data to write. 2974 * @param offsetInShorts the offset expressed in shorts in audioData where the data to write 2975 * starts. 2976 * Must not be negative, or cause the data access to go out of bounds of the array. 2977 * @param sizeInShorts the number of shorts to read in audioData after the offset. 2978 * Must not be negative, or cause the data access to go out of bounds of the array. 2979 * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no 2980 * effect in static mode. 2981 * <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written 2982 * to the audio sink. 2983 * <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after 2984 * queuing as much audio data for playback as possible without blocking. 2985 * @return zero or the positive number of shorts that were written, or one of the following 2986 * error codes. The number of shorts will be a multiple of the channel count not to 2987 * exceed sizeInShorts. 2988 * <ul> 2989 * <li>{@link #ERROR_INVALID_OPERATION} if the track isn't properly initialized</li> 2990 * <li>{@link #ERROR_BAD_VALUE} if the parameters don't resolve to valid data and indexes</li> 2991 * <li>{@link #ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 2992 * needs to be recreated. The dead object error code is not returned if some data was 2993 * successfully transferred. In this case, the error is returned at the next write()</li> 2994 * <li>{@link #ERROR} in case of other error</li> 2995 * </ul> 2996 */ write(@onNull short[] audioData, int offsetInShorts, int sizeInShorts, @WriteMode int writeMode)2997 public int write(@NonNull short[] audioData, int offsetInShorts, int sizeInShorts, 2998 @WriteMode int writeMode) { 2999 3000 if (mState == STATE_UNINITIALIZED || mAudioFormat == AudioFormat.ENCODING_PCM_FLOAT) { 3001 return ERROR_INVALID_OPERATION; 3002 } 3003 3004 if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) { 3005 Log.e(TAG, "AudioTrack.write() called with invalid blocking mode"); 3006 return ERROR_BAD_VALUE; 3007 } 3008 3009 if ( (audioData == null) || (offsetInShorts < 0 ) || (sizeInShorts < 0) 3010 || (offsetInShorts + sizeInShorts < 0) // detect integer overflow 3011 || (offsetInShorts + sizeInShorts > audioData.length)) { 3012 return ERROR_BAD_VALUE; 3013 } 3014 3015 if (!blockUntilOffloadDrain(writeMode)) { 3016 return 0; 3017 } 3018 3019 final int ret = native_write_short(audioData, offsetInShorts, sizeInShorts, mAudioFormat, 3020 writeMode == WRITE_BLOCKING); 3021 3022 if ((mDataLoadMode == MODE_STATIC) 3023 && (mState == STATE_NO_STATIC_DATA) 3024 && (ret > 0)) { 3025 // benign race with respect to other APIs that read mState 3026 mState = STATE_INITIALIZED; 3027 } 3028 3029 return ret; 3030 } 3031 3032 /** 3033 * Writes the audio data to the audio sink for playback (streaming mode), 3034 * or copies audio data for later playback (static buffer mode). 3035 * The format specified in the AudioTrack constructor should be 3036 * {@link AudioFormat#ENCODING_PCM_FLOAT} to correspond to the data in the array. 3037 * <p> 3038 * In streaming mode, the blocking behavior depends on the write mode. If the write mode is 3039 * {@link #WRITE_BLOCKING}, the write will normally block until all the data has been enqueued 3040 * for playback, and will return a full transfer count. However, if the write mode is 3041 * {@link #WRITE_NON_BLOCKING}, or the track is stopped or paused on entry, or another thread 3042 * interrupts the write by calling stop or pause, or an I/O error 3043 * occurs during the write, then the write may return a short transfer count. 3044 * <p> 3045 * In static buffer mode, copies the data to the buffer starting at offset 0, 3046 * and the write mode is ignored. 3047 * Note that the actual playback of this data might occur after this function returns. 3048 * 3049 * @param audioData the array that holds the data to write. 3050 * The implementation does not clip for sample values within the nominal range 3051 * [-1.0f, 1.0f], provided that all gains in the audio pipeline are 3052 * less than or equal to unity (1.0f), and in the absence of post-processing effects 3053 * that could add energy, such as reverb. For the convenience of applications 3054 * that compute samples using filters with non-unity gain, 3055 * sample values +3 dB beyond the nominal range are permitted. 3056 * However such values may eventually be limited or clipped, depending on various gains 3057 * and later processing in the audio path. Therefore applications are encouraged 3058 * to provide samples values within the nominal range. 3059 * @param offsetInFloats the offset, expressed as a number of floats, 3060 * in audioData where the data to write starts. 3061 * Must not be negative, or cause the data access to go out of bounds of the array. 3062 * @param sizeInFloats the number of floats to write in audioData after the offset. 3063 * Must not be negative, or cause the data access to go out of bounds of the array. 3064 * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no 3065 * effect in static mode. 3066 * <br>With {@link #WRITE_BLOCKING}, the write will block until all data has been written 3067 * to the audio sink. 3068 * <br>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after 3069 * queuing as much audio data for playback as possible without blocking. 3070 * @return zero or the positive number of floats that were written, or one of the following 3071 * error codes. The number of floats will be a multiple of the channel count not to 3072 * exceed sizeInFloats. 3073 * <ul> 3074 * <li>{@link #ERROR_INVALID_OPERATION} if the track isn't properly initialized</li> 3075 * <li>{@link #ERROR_BAD_VALUE} if the parameters don't resolve to valid data and indexes</li> 3076 * <li>{@link #ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 3077 * needs to be recreated. The dead object error code is not returned if some data was 3078 * successfully transferred. In this case, the error is returned at the next write()</li> 3079 * <li>{@link #ERROR} in case of other error</li> 3080 * </ul> 3081 */ write(@onNull float[] audioData, int offsetInFloats, int sizeInFloats, @WriteMode int writeMode)3082 public int write(@NonNull float[] audioData, int offsetInFloats, int sizeInFloats, 3083 @WriteMode int writeMode) { 3084 3085 if (mState == STATE_UNINITIALIZED) { 3086 Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED"); 3087 return ERROR_INVALID_OPERATION; 3088 } 3089 3090 if (mAudioFormat != AudioFormat.ENCODING_PCM_FLOAT) { 3091 Log.e(TAG, "AudioTrack.write(float[] ...) requires format ENCODING_PCM_FLOAT"); 3092 return ERROR_INVALID_OPERATION; 3093 } 3094 3095 if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) { 3096 Log.e(TAG, "AudioTrack.write() called with invalid blocking mode"); 3097 return ERROR_BAD_VALUE; 3098 } 3099 3100 if ( (audioData == null) || (offsetInFloats < 0 ) || (sizeInFloats < 0) 3101 || (offsetInFloats + sizeInFloats < 0) // detect integer overflow 3102 || (offsetInFloats + sizeInFloats > audioData.length)) { 3103 Log.e(TAG, "AudioTrack.write() called with invalid array, offset, or size"); 3104 return ERROR_BAD_VALUE; 3105 } 3106 3107 if (!blockUntilOffloadDrain(writeMode)) { 3108 return 0; 3109 } 3110 3111 final int ret = native_write_float(audioData, offsetInFloats, sizeInFloats, mAudioFormat, 3112 writeMode == WRITE_BLOCKING); 3113 3114 if ((mDataLoadMode == MODE_STATIC) 3115 && (mState == STATE_NO_STATIC_DATA) 3116 && (ret > 0)) { 3117 // benign race with respect to other APIs that read mState 3118 mState = STATE_INITIALIZED; 3119 } 3120 3121 return ret; 3122 } 3123 3124 3125 /** 3126 * Writes the audio data to the audio sink for playback (streaming mode), 3127 * or copies audio data for later playback (static buffer mode). 3128 * The audioData in ByteBuffer should match the format specified in the AudioTrack constructor. 3129 * <p> 3130 * In streaming mode, the blocking behavior depends on the write mode. If the write mode is 3131 * {@link #WRITE_BLOCKING}, the write will normally block until all the data has been enqueued 3132 * for playback, and will return a full transfer count. However, if the write mode is 3133 * {@link #WRITE_NON_BLOCKING}, or the track is stopped or paused on entry, or another thread 3134 * interrupts the write by calling stop or pause, or an I/O error 3135 * occurs during the write, then the write may return a short transfer count. 3136 * <p> 3137 * In static buffer mode, copies the data to the buffer starting at offset 0, 3138 * and the write mode is ignored. 3139 * Note that the actual playback of this data might occur after this function returns. 3140 * 3141 * @param audioData the buffer that holds the data to write, starting at the position reported 3142 * by <code>audioData.position()</code>. 3143 * <BR>Note that upon return, the buffer position (<code>audioData.position()</code>) will 3144 * have been advanced to reflect the amount of data that was successfully written to 3145 * the AudioTrack. 3146 * @param sizeInBytes number of bytes to write. It is recommended but not enforced 3147 * that the number of bytes requested be a multiple of the frame size (sample size in 3148 * bytes multiplied by the channel count). 3149 * <BR>Note this may differ from <code>audioData.remaining()</code>, but cannot exceed it. 3150 * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. It has no 3151 * effect in static mode. 3152 * <BR>With {@link #WRITE_BLOCKING}, the write will block until all data has been written 3153 * to the audio sink. 3154 * <BR>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after 3155 * queuing as much audio data for playback as possible without blocking. 3156 * @return zero or the positive number of bytes that were written, or one of the following 3157 * error codes. 3158 * <ul> 3159 * <li>{@link #ERROR_INVALID_OPERATION} if the track isn't properly initialized</li> 3160 * <li>{@link #ERROR_BAD_VALUE} if the parameters don't resolve to valid data and indexes</li> 3161 * <li>{@link #ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 3162 * needs to be recreated. The dead object error code is not returned if some data was 3163 * successfully transferred. In this case, the error is returned at the next write()</li> 3164 * <li>{@link #ERROR} in case of other error</li> 3165 * </ul> 3166 */ write(@onNull ByteBuffer audioData, int sizeInBytes, @WriteMode int writeMode)3167 public int write(@NonNull ByteBuffer audioData, int sizeInBytes, 3168 @WriteMode int writeMode) { 3169 3170 if (mState == STATE_UNINITIALIZED) { 3171 Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED"); 3172 return ERROR_INVALID_OPERATION; 3173 } 3174 3175 if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) { 3176 Log.e(TAG, "AudioTrack.write() called with invalid blocking mode"); 3177 return ERROR_BAD_VALUE; 3178 } 3179 3180 if ( (audioData == null) || (sizeInBytes < 0) || (sizeInBytes > audioData.remaining())) { 3181 Log.e(TAG, "AudioTrack.write() called with invalid size (" + sizeInBytes + ") value"); 3182 return ERROR_BAD_VALUE; 3183 } 3184 3185 if (!blockUntilOffloadDrain(writeMode)) { 3186 return 0; 3187 } 3188 3189 int ret = 0; 3190 if (audioData.isDirect()) { 3191 ret = native_write_native_bytes(audioData, 3192 audioData.position(), sizeInBytes, mAudioFormat, 3193 writeMode == WRITE_BLOCKING); 3194 } else { 3195 ret = native_write_byte(NioUtils.unsafeArray(audioData), 3196 NioUtils.unsafeArrayOffset(audioData) + audioData.position(), 3197 sizeInBytes, mAudioFormat, 3198 writeMode == WRITE_BLOCKING); 3199 } 3200 3201 if ((mDataLoadMode == MODE_STATIC) 3202 && (mState == STATE_NO_STATIC_DATA) 3203 && (ret > 0)) { 3204 // benign race with respect to other APIs that read mState 3205 mState = STATE_INITIALIZED; 3206 } 3207 3208 if (ret > 0) { 3209 audioData.position(audioData.position() + ret); 3210 } 3211 3212 return ret; 3213 } 3214 3215 /** 3216 * Writes the audio data to the audio sink for playback in streaming mode on a HW_AV_SYNC track. 3217 * The blocking behavior will depend on the write mode. 3218 * @param audioData the buffer that holds the data to write, starting at the position reported 3219 * by <code>audioData.position()</code>. 3220 * <BR>Note that upon return, the buffer position (<code>audioData.position()</code>) will 3221 * have been advanced to reflect the amount of data that was successfully written to 3222 * the AudioTrack. 3223 * @param sizeInBytes number of bytes to write. It is recommended but not enforced 3224 * that the number of bytes requested be a multiple of the frame size (sample size in 3225 * bytes multiplied by the channel count). 3226 * <BR>Note this may differ from <code>audioData.remaining()</code>, but cannot exceed it. 3227 * @param writeMode one of {@link #WRITE_BLOCKING}, {@link #WRITE_NON_BLOCKING}. 3228 * <BR>With {@link #WRITE_BLOCKING}, the write will block until all data has been written 3229 * to the audio sink. 3230 * <BR>With {@link #WRITE_NON_BLOCKING}, the write will return immediately after 3231 * queuing as much audio data for playback as possible without blocking. 3232 * @param timestamp The timestamp, in nanoseconds, of the first decodable audio frame in the 3233 * provided audioData. 3234 * @return zero or the positive number of bytes that were written, or one of the following 3235 * error codes. 3236 * <ul> 3237 * <li>{@link #ERROR_INVALID_OPERATION} if the track isn't properly initialized</li> 3238 * <li>{@link #ERROR_BAD_VALUE} if the parameters don't resolve to valid data and indexes</li> 3239 * <li>{@link #ERROR_DEAD_OBJECT} if the AudioTrack is not valid anymore and 3240 * needs to be recreated. The dead object error code is not returned if some data was 3241 * successfully transferred. In this case, the error is returned at the next write()</li> 3242 * <li>{@link #ERROR} in case of other error</li> 3243 * </ul> 3244 */ write(@onNull ByteBuffer audioData, int sizeInBytes, @WriteMode int writeMode, long timestamp)3245 public int write(@NonNull ByteBuffer audioData, int sizeInBytes, 3246 @WriteMode int writeMode, long timestamp) { 3247 3248 if (mState == STATE_UNINITIALIZED) { 3249 Log.e(TAG, "AudioTrack.write() called in invalid state STATE_UNINITIALIZED"); 3250 return ERROR_INVALID_OPERATION; 3251 } 3252 3253 if ((writeMode != WRITE_BLOCKING) && (writeMode != WRITE_NON_BLOCKING)) { 3254 Log.e(TAG, "AudioTrack.write() called with invalid blocking mode"); 3255 return ERROR_BAD_VALUE; 3256 } 3257 3258 if (mDataLoadMode != MODE_STREAM) { 3259 Log.e(TAG, "AudioTrack.write() with timestamp called for non-streaming mode track"); 3260 return ERROR_INVALID_OPERATION; 3261 } 3262 3263 if ((mAttributes.getFlags() & AudioAttributes.FLAG_HW_AV_SYNC) == 0) { 3264 Log.d(TAG, "AudioTrack.write() called on a regular AudioTrack. Ignoring pts..."); 3265 return write(audioData, sizeInBytes, writeMode); 3266 } 3267 3268 if ((audioData == null) || (sizeInBytes < 0) || (sizeInBytes > audioData.remaining())) { 3269 Log.e(TAG, "AudioTrack.write() called with invalid size (" + sizeInBytes + ") value"); 3270 return ERROR_BAD_VALUE; 3271 } 3272 3273 if (!blockUntilOffloadDrain(writeMode)) { 3274 return 0; 3275 } 3276 3277 // create timestamp header if none exists 3278 if (mAvSyncHeader == null) { 3279 mAvSyncHeader = ByteBuffer.allocate(mOffset); 3280 mAvSyncHeader.order(ByteOrder.BIG_ENDIAN); 3281 mAvSyncHeader.putInt(0x55550002); 3282 } 3283 3284 if (mAvSyncBytesRemaining == 0) { 3285 mAvSyncHeader.putInt(4, sizeInBytes); 3286 mAvSyncHeader.putLong(8, timestamp); 3287 mAvSyncHeader.putInt(16, mOffset); 3288 mAvSyncHeader.position(0); 3289 mAvSyncBytesRemaining = sizeInBytes; 3290 } 3291 3292 // write timestamp header if not completely written already 3293 int ret = 0; 3294 if (mAvSyncHeader.remaining() != 0) { 3295 ret = write(mAvSyncHeader, mAvSyncHeader.remaining(), writeMode); 3296 if (ret < 0) { 3297 Log.e(TAG, "AudioTrack.write() could not write timestamp header!"); 3298 mAvSyncHeader = null; 3299 mAvSyncBytesRemaining = 0; 3300 return ret; 3301 } 3302 if (mAvSyncHeader.remaining() > 0) { 3303 Log.v(TAG, "AudioTrack.write() partial timestamp header written."); 3304 return 0; 3305 } 3306 } 3307 3308 // write audio data 3309 int sizeToWrite = Math.min(mAvSyncBytesRemaining, sizeInBytes); 3310 ret = write(audioData, sizeToWrite, writeMode); 3311 if (ret < 0) { 3312 Log.e(TAG, "AudioTrack.write() could not write audio data!"); 3313 mAvSyncHeader = null; 3314 mAvSyncBytesRemaining = 0; 3315 return ret; 3316 } 3317 3318 mAvSyncBytesRemaining -= ret; 3319 3320 return ret; 3321 } 3322 3323 3324 /** 3325 * Sets the playback head position within the static buffer to zero, 3326 * that is it rewinds to start of static buffer. 3327 * The track must be stopped or paused, and 3328 * the track's creation mode must be {@link #MODE_STATIC}. 3329 * <p> 3330 * As of {@link android.os.Build.VERSION_CODES#M}, also resets the value returned by 3331 * {@link #getPlaybackHeadPosition()} to zero. 3332 * For earlier API levels, the reset behavior is unspecified. 3333 * <p> 3334 * Use {@link #setPlaybackHeadPosition(int)} with a zero position 3335 * if the reset of <code>getPlaybackHeadPosition()</code> is not needed. 3336 * @return error code or success, see {@link #SUCCESS}, {@link #ERROR_BAD_VALUE}, 3337 * {@link #ERROR_INVALID_OPERATION} 3338 */ reloadStaticData()3339 public int reloadStaticData() { 3340 if (mDataLoadMode == MODE_STREAM || mState != STATE_INITIALIZED) { 3341 return ERROR_INVALID_OPERATION; 3342 } 3343 return native_reload_static(); 3344 } 3345 3346 /** 3347 * When an AudioTrack in offload mode is in STOPPING play state, wait until event STREAM_END is 3348 * received if blocking write or return with 0 frames written if non blocking mode. 3349 */ blockUntilOffloadDrain(int writeMode)3350 private boolean blockUntilOffloadDrain(int writeMode) { 3351 synchronized (mPlayStateLock) { 3352 while (mPlayState == PLAYSTATE_STOPPING || mPlayState == PLAYSTATE_PAUSED_STOPPING) { 3353 if (writeMode == WRITE_NON_BLOCKING) { 3354 return false; 3355 } 3356 try { 3357 mPlayStateLock.wait(); 3358 } catch (InterruptedException e) { 3359 } 3360 } 3361 return true; 3362 } 3363 } 3364 3365 //-------------------------------------------------------------------------- 3366 // Audio effects management 3367 //-------------------- 3368 3369 /** 3370 * Attaches an auxiliary effect to the audio track. A typical auxiliary 3371 * effect is a reverberation effect which can be applied on any sound source 3372 * that directs a certain amount of its energy to this effect. This amount 3373 * is defined by setAuxEffectSendLevel(). 3374 * {@see #setAuxEffectSendLevel(float)}. 3375 * <p>After creating an auxiliary effect (e.g. 3376 * {@link android.media.audiofx.EnvironmentalReverb}), retrieve its ID with 3377 * {@link android.media.audiofx.AudioEffect#getId()} and use it when calling 3378 * this method to attach the audio track to the effect. 3379 * <p>To detach the effect from the audio track, call this method with a 3380 * null effect id. 3381 * 3382 * @param effectId system wide unique id of the effect to attach 3383 * @return error code or success, see {@link #SUCCESS}, 3384 * {@link #ERROR_INVALID_OPERATION}, {@link #ERROR_BAD_VALUE} 3385 */ attachAuxEffect(int effectId)3386 public int attachAuxEffect(int effectId) { 3387 if (mState == STATE_UNINITIALIZED) { 3388 return ERROR_INVALID_OPERATION; 3389 } 3390 return native_attachAuxEffect(effectId); 3391 } 3392 3393 /** 3394 * Sets the send level of the audio track to the attached auxiliary effect 3395 * {@link #attachAuxEffect(int)}. Effect levels 3396 * are clamped to the closed interval [0.0, max] where 3397 * max is the value of {@link #getMaxVolume}. 3398 * A value of 0.0 results in no effect, and a value of 1.0 is full send. 3399 * <p>By default the send level is 0.0f, so even if an effect is attached to the player 3400 * this method must be called for the effect to be applied. 3401 * <p>Note that the passed level value is a linear scalar. UI controls should be scaled 3402 * logarithmically: the gain applied by audio framework ranges from -72dB to at least 0dB, 3403 * so an appropriate conversion from linear UI input x to level is: 3404 * x == 0 -> level = 0 3405 * 0 < x <= R -> level = 10^(72*(x-R)/20/R) 3406 * 3407 * @param level linear send level 3408 * @return error code or success, see {@link #SUCCESS}, 3409 * {@link #ERROR_INVALID_OPERATION}, {@link #ERROR} 3410 */ setAuxEffectSendLevel(@loatRangefrom = 0.0) float level)3411 public int setAuxEffectSendLevel(@FloatRange(from = 0.0) float level) { 3412 if (mState == STATE_UNINITIALIZED) { 3413 return ERROR_INVALID_OPERATION; 3414 } 3415 return baseSetAuxEffectSendLevel(level); 3416 } 3417 3418 @Override playerSetAuxEffectSendLevel(boolean muting, float level)3419 int playerSetAuxEffectSendLevel(boolean muting, float level) { 3420 level = clampGainOrLevel(muting ? 0.0f : level); 3421 int err = native_setAuxEffectSendLevel(level); 3422 return err == 0 ? SUCCESS : ERROR; 3423 } 3424 3425 //-------------------------------------------------------------------------- 3426 // Explicit Routing 3427 //-------------------- 3428 private AudioDeviceInfo mPreferredDevice = null; 3429 3430 /** 3431 * Specifies an audio device (via an {@link AudioDeviceInfo} object) to route 3432 * the output from this AudioTrack. 3433 * @param deviceInfo The {@link AudioDeviceInfo} specifying the audio sink. 3434 * If deviceInfo is null, default routing is restored. 3435 * @return true if succesful, false if the specified {@link AudioDeviceInfo} is non-null and 3436 * does not correspond to a valid audio output device. 3437 */ 3438 @Override setPreferredDevice(AudioDeviceInfo deviceInfo)3439 public boolean setPreferredDevice(AudioDeviceInfo deviceInfo) { 3440 // Do some validation.... 3441 if (deviceInfo != null && !deviceInfo.isSink()) { 3442 return false; 3443 } 3444 int preferredDeviceId = deviceInfo != null ? deviceInfo.getId() : 0; 3445 boolean status = native_setOutputDevice(preferredDeviceId); 3446 if (status == true) { 3447 synchronized (this) { 3448 mPreferredDevice = deviceInfo; 3449 } 3450 } 3451 return status; 3452 } 3453 3454 /** 3455 * Returns the selected output specified by {@link #setPreferredDevice}. Note that this 3456 * is not guaranteed to correspond to the actual device being used for playback. 3457 */ 3458 @Override getPreferredDevice()3459 public AudioDeviceInfo getPreferredDevice() { 3460 synchronized (this) { 3461 return mPreferredDevice; 3462 } 3463 } 3464 3465 /** 3466 * Returns an {@link AudioDeviceInfo} identifying the current routing of this AudioTrack. 3467 * Note: The query is only valid if the AudioTrack is currently playing. If it is not, 3468 * <code>getRoutedDevice()</code> will return null. 3469 */ 3470 @Override getRoutedDevice()3471 public AudioDeviceInfo getRoutedDevice() { 3472 int deviceId = native_getRoutedDeviceId(); 3473 if (deviceId == 0) { 3474 return null; 3475 } 3476 AudioDeviceInfo[] devices = 3477 AudioManager.getDevicesStatic(AudioManager.GET_DEVICES_OUTPUTS); 3478 for (int i = 0; i < devices.length; i++) { 3479 if (devices[i].getId() == deviceId) { 3480 return devices[i]; 3481 } 3482 } 3483 return null; 3484 } 3485 3486 /* 3487 * Call BEFORE adding a routing callback handler. 3488 */ 3489 @GuardedBy("mRoutingChangeListeners") testEnableNativeRoutingCallbacksLocked()3490 private void testEnableNativeRoutingCallbacksLocked() { 3491 if (mRoutingChangeListeners.size() == 0) { 3492 native_enableDeviceCallback(); 3493 } 3494 } 3495 3496 /* 3497 * Call AFTER removing a routing callback handler. 3498 */ 3499 @GuardedBy("mRoutingChangeListeners") testDisableNativeRoutingCallbacksLocked()3500 private void testDisableNativeRoutingCallbacksLocked() { 3501 if (mRoutingChangeListeners.size() == 0) { 3502 native_disableDeviceCallback(); 3503 } 3504 } 3505 3506 //-------------------------------------------------------------------------- 3507 // (Re)Routing Info 3508 //-------------------- 3509 /** 3510 * The list of AudioRouting.OnRoutingChangedListener interfaces added (with 3511 * {@link #addOnRoutingChangedListener(android.media.AudioRouting.OnRoutingChangedListener, Handler)} 3512 * by an app to receive (re)routing notifications. 3513 */ 3514 @GuardedBy("mRoutingChangeListeners") 3515 private ArrayMap<AudioRouting.OnRoutingChangedListener, 3516 NativeRoutingEventHandlerDelegate> mRoutingChangeListeners = new ArrayMap<>(); 3517 3518 /** 3519 * Adds an {@link AudioRouting.OnRoutingChangedListener} to receive notifications of routing 3520 * changes on this AudioTrack. 3521 * @param listener The {@link AudioRouting.OnRoutingChangedListener} interface to receive 3522 * notifications of rerouting events. 3523 * @param handler Specifies the {@link Handler} object for the thread on which to execute 3524 * the callback. If <code>null</code>, the {@link Handler} associated with the main 3525 * {@link Looper} will be used. 3526 */ 3527 @Override addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener, Handler handler)3528 public void addOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener, 3529 Handler handler) { 3530 synchronized (mRoutingChangeListeners) { 3531 if (listener != null && !mRoutingChangeListeners.containsKey(listener)) { 3532 testEnableNativeRoutingCallbacksLocked(); 3533 mRoutingChangeListeners.put( 3534 listener, new NativeRoutingEventHandlerDelegate(this, listener, 3535 handler != null ? handler : new Handler(mInitializationLooper))); 3536 } 3537 } 3538 } 3539 3540 /** 3541 * Removes an {@link AudioRouting.OnRoutingChangedListener} which has been previously added 3542 * to receive rerouting notifications. 3543 * @param listener The previously added {@link AudioRouting.OnRoutingChangedListener} interface 3544 * to remove. 3545 */ 3546 @Override removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener)3547 public void removeOnRoutingChangedListener(AudioRouting.OnRoutingChangedListener listener) { 3548 synchronized (mRoutingChangeListeners) { 3549 if (mRoutingChangeListeners.containsKey(listener)) { 3550 mRoutingChangeListeners.remove(listener); 3551 } 3552 testDisableNativeRoutingCallbacksLocked(); 3553 } 3554 } 3555 3556 //-------------------------------------------------------------------------- 3557 // (Re)Routing Info 3558 //-------------------- 3559 /** 3560 * Defines the interface by which applications can receive notifications of 3561 * routing changes for the associated {@link AudioTrack}. 3562 * 3563 * @deprecated users should switch to the general purpose 3564 * {@link AudioRouting.OnRoutingChangedListener} class instead. 3565 */ 3566 @Deprecated 3567 public interface OnRoutingChangedListener extends AudioRouting.OnRoutingChangedListener { 3568 /** 3569 * Called when the routing of an AudioTrack changes from either and 3570 * explicit or policy rerouting. Use {@link #getRoutedDevice()} to 3571 * retrieve the newly routed-to device. 3572 */ onRoutingChanged(AudioTrack audioTrack)3573 public void onRoutingChanged(AudioTrack audioTrack); 3574 3575 @Override onRoutingChanged(AudioRouting router)3576 default public void onRoutingChanged(AudioRouting router) { 3577 if (router instanceof AudioTrack) { 3578 onRoutingChanged((AudioTrack) router); 3579 } 3580 } 3581 } 3582 3583 /** 3584 * Adds an {@link OnRoutingChangedListener} to receive notifications of routing changes 3585 * on this AudioTrack. 3586 * @param listener The {@link OnRoutingChangedListener} interface to receive notifications 3587 * of rerouting events. 3588 * @param handler Specifies the {@link Handler} object for the thread on which to execute 3589 * the callback. If <code>null</code>, the {@link Handler} associated with the main 3590 * {@link Looper} will be used. 3591 * @deprecated users should switch to the general purpose 3592 * {@link AudioRouting.OnRoutingChangedListener} class instead. 3593 */ 3594 @Deprecated addOnRoutingChangedListener(OnRoutingChangedListener listener, android.os.Handler handler)3595 public void addOnRoutingChangedListener(OnRoutingChangedListener listener, 3596 android.os.Handler handler) { 3597 addOnRoutingChangedListener((AudioRouting.OnRoutingChangedListener) listener, handler); 3598 } 3599 3600 /** 3601 * Removes an {@link OnRoutingChangedListener} which has been previously added 3602 * to receive rerouting notifications. 3603 * @param listener The previously added {@link OnRoutingChangedListener} interface to remove. 3604 * @deprecated users should switch to the general purpose 3605 * {@link AudioRouting.OnRoutingChangedListener} class instead. 3606 */ 3607 @Deprecated removeOnRoutingChangedListener(OnRoutingChangedListener listener)3608 public void removeOnRoutingChangedListener(OnRoutingChangedListener listener) { 3609 removeOnRoutingChangedListener((AudioRouting.OnRoutingChangedListener) listener); 3610 } 3611 3612 /** 3613 * Sends device list change notification to all listeners. 3614 */ broadcastRoutingChange()3615 private void broadcastRoutingChange() { 3616 AudioManager.resetAudioPortGeneration(); 3617 synchronized (mRoutingChangeListeners) { 3618 for (NativeRoutingEventHandlerDelegate delegate : mRoutingChangeListeners.values()) { 3619 delegate.notifyClient(); 3620 } 3621 } 3622 } 3623 3624 //-------------------------------------------------------------------------- 3625 // Codec notifications 3626 //-------------------- 3627 3628 // OnCodecFormatChangedListener notifications uses an instance 3629 // of ListenerList to manage its listeners. 3630 3631 private final Utils.ListenerList<AudioMetadataReadMap> mCodecFormatChangedListeners = 3632 new Utils.ListenerList(); 3633 3634 /** 3635 * Interface definition for a listener for codec format changes. 3636 */ 3637 public interface OnCodecFormatChangedListener { 3638 /** 3639 * Called when the compressed codec format changes. 3640 * 3641 * @param audioTrack is the {@code AudioTrack} instance associated with the codec. 3642 * @param info is a {@link AudioMetadataReadMap} of values which contains decoded format 3643 * changes reported by the codec. Not all hardware 3644 * codecs indicate codec format changes. Acceptable keys are taken from 3645 * {@code AudioMetadata.Format.KEY_*} range, with the associated value type. 3646 */ onCodecFormatChanged( @onNull AudioTrack audioTrack, @Nullable AudioMetadataReadMap info)3647 void onCodecFormatChanged( 3648 @NonNull AudioTrack audioTrack, @Nullable AudioMetadataReadMap info); 3649 } 3650 3651 /** 3652 * Adds an {@link OnCodecFormatChangedListener} to receive notifications of 3653 * codec format change events on this {@code AudioTrack}. 3654 * 3655 * @param executor Specifies the {@link Executor} object to control execution. 3656 * 3657 * @param listener The {@link OnCodecFormatChangedListener} interface to receive 3658 * notifications of codec events. 3659 */ addOnCodecFormatChangedListener( @onNull @allbackExecutor Executor executor, @NonNull OnCodecFormatChangedListener listener)3660 public void addOnCodecFormatChangedListener( 3661 @NonNull @CallbackExecutor Executor executor, 3662 @NonNull OnCodecFormatChangedListener listener) { // NPE checks done by ListenerList. 3663 mCodecFormatChangedListeners.add( 3664 listener, /* key for removal */ 3665 executor, 3666 (int eventCode, AudioMetadataReadMap readMap) -> { 3667 // eventCode is unused by this implementation. 3668 listener.onCodecFormatChanged(this, readMap); 3669 } 3670 ); 3671 } 3672 3673 /** 3674 * Removes an {@link OnCodecFormatChangedListener} which has been previously added 3675 * to receive codec format change events. 3676 * 3677 * @param listener The previously added {@link OnCodecFormatChangedListener} interface 3678 * to remove. 3679 */ removeOnCodecFormatChangedListener( @onNull OnCodecFormatChangedListener listener)3680 public void removeOnCodecFormatChangedListener( 3681 @NonNull OnCodecFormatChangedListener listener) { 3682 mCodecFormatChangedListeners.remove(listener); // NPE checks done by ListenerList. 3683 } 3684 3685 //--------------------------------------------------------- 3686 // Interface definitions 3687 //-------------------- 3688 /** 3689 * Interface definition for a callback to be invoked when the playback head position of 3690 * an AudioTrack has reached a notification marker or has increased by a certain period. 3691 */ 3692 public interface OnPlaybackPositionUpdateListener { 3693 /** 3694 * Called on the listener to notify it that the previously set marker has been reached 3695 * by the playback head. 3696 */ onMarkerReached(AudioTrack track)3697 void onMarkerReached(AudioTrack track); 3698 3699 /** 3700 * Called on the listener to periodically notify it that the playback head has reached 3701 * a multiple of the notification period. 3702 */ onPeriodicNotification(AudioTrack track)3703 void onPeriodicNotification(AudioTrack track); 3704 } 3705 3706 /** 3707 * Abstract class to receive event notifications about the stream playback in offloaded mode. 3708 * See {@link AudioTrack#registerStreamEventCallback(Executor, StreamEventCallback)} to register 3709 * the callback on the given {@link AudioTrack} instance. 3710 */ 3711 public abstract static class StreamEventCallback { 3712 /** 3713 * Called when an offloaded track is no longer valid and has been discarded by the system. 3714 * An example of this happening is when an offloaded track has been paused too long, and 3715 * gets invalidated by the system to prevent any other offload. 3716 * @param track the {@link AudioTrack} on which the event happened. 3717 */ onTearDown(@onNull AudioTrack track)3718 public void onTearDown(@NonNull AudioTrack track) { } 3719 /** 3720 * Called when all the buffers of an offloaded track that were queued in the audio system 3721 * (e.g. the combination of the Android audio framework and the device's audio hardware) 3722 * have been played after {@link AudioTrack#stop()} has been called. 3723 * @param track the {@link AudioTrack} on which the event happened. 3724 */ onPresentationEnded(@onNull AudioTrack track)3725 public void onPresentationEnded(@NonNull AudioTrack track) { } 3726 /** 3727 * Called when more audio data can be written without blocking on an offloaded track. 3728 * @param track the {@link AudioTrack} on which the event happened. 3729 * @param sizeInFrames the number of frames available to write without blocking. 3730 * Note that the frame size of a compressed stream is 1 byte. 3731 */ onDataRequest(@onNull AudioTrack track, @IntRange(from = 0) int sizeInFrames)3732 public void onDataRequest(@NonNull AudioTrack track, @IntRange(from = 0) int sizeInFrames) { 3733 } 3734 } 3735 3736 /** 3737 * Registers a callback for the notification of stream events. 3738 * This callback can only be registered for instances operating in offloaded mode 3739 * (see {@link AudioTrack.Builder#setOffloadedPlayback(boolean)} and 3740 * {@link AudioManager#isOffloadedPlaybackSupported(AudioFormat,AudioAttributes)} for 3741 * more details). 3742 * @param executor {@link Executor} to handle the callbacks. 3743 * @param eventCallback the callback to receive the stream event notifications. 3744 */ registerStreamEventCallback(@onNull @allbackExecutor Executor executor, @NonNull StreamEventCallback eventCallback)3745 public void registerStreamEventCallback(@NonNull @CallbackExecutor Executor executor, 3746 @NonNull StreamEventCallback eventCallback) { 3747 if (eventCallback == null) { 3748 throw new IllegalArgumentException("Illegal null StreamEventCallback"); 3749 } 3750 if (!mOffloaded) { 3751 throw new IllegalStateException( 3752 "Cannot register StreamEventCallback on non-offloaded AudioTrack"); 3753 } 3754 if (executor == null) { 3755 throw new IllegalArgumentException("Illegal null Executor for the StreamEventCallback"); 3756 } 3757 synchronized (mStreamEventCbLock) { 3758 // check if eventCallback already in list 3759 for (StreamEventCbInfo seci : mStreamEventCbInfoList) { 3760 if (seci.mStreamEventCb == eventCallback) { 3761 throw new IllegalArgumentException( 3762 "StreamEventCallback already registered"); 3763 } 3764 } 3765 beginStreamEventHandling(); 3766 mStreamEventCbInfoList.add(new StreamEventCbInfo(executor, eventCallback)); 3767 } 3768 } 3769 3770 /** 3771 * Unregisters the callback for notification of stream events, previously registered 3772 * with {@link #registerStreamEventCallback(Executor, StreamEventCallback)}. 3773 * @param eventCallback the callback to unregister. 3774 */ unregisterStreamEventCallback(@onNull StreamEventCallback eventCallback)3775 public void unregisterStreamEventCallback(@NonNull StreamEventCallback eventCallback) { 3776 if (eventCallback == null) { 3777 throw new IllegalArgumentException("Illegal null StreamEventCallback"); 3778 } 3779 if (!mOffloaded) { 3780 throw new IllegalStateException("No StreamEventCallback on non-offloaded AudioTrack"); 3781 } 3782 synchronized (mStreamEventCbLock) { 3783 StreamEventCbInfo seciToRemove = null; 3784 for (StreamEventCbInfo seci : mStreamEventCbInfoList) { 3785 if (seci.mStreamEventCb == eventCallback) { 3786 // ok to remove while iterating over list as we exit iteration 3787 mStreamEventCbInfoList.remove(seci); 3788 if (mStreamEventCbInfoList.size() == 0) { 3789 endStreamEventHandling(); 3790 } 3791 return; 3792 } 3793 } 3794 throw new IllegalArgumentException("StreamEventCallback was not registered"); 3795 } 3796 } 3797 3798 //--------------------------------------------------------- 3799 // Offload 3800 //-------------------- 3801 private static class StreamEventCbInfo { 3802 final Executor mStreamEventExec; 3803 final StreamEventCallback mStreamEventCb; 3804 StreamEventCbInfo(Executor e, StreamEventCallback cb)3805 StreamEventCbInfo(Executor e, StreamEventCallback cb) { 3806 mStreamEventExec = e; 3807 mStreamEventCb = cb; 3808 } 3809 } 3810 3811 private final Object mStreamEventCbLock = new Object(); 3812 @GuardedBy("mStreamEventCbLock") 3813 @NonNull private LinkedList<StreamEventCbInfo> mStreamEventCbInfoList = 3814 new LinkedList<StreamEventCbInfo>(); 3815 /** 3816 * Dedicated thread for handling the StreamEvent callbacks 3817 */ 3818 private @Nullable HandlerThread mStreamEventHandlerThread; 3819 private @Nullable volatile StreamEventHandler mStreamEventHandler; 3820 3821 /** 3822 * Called from native AudioTrack callback thread, filter messages if necessary 3823 * and repost event on AudioTrack message loop to prevent blocking native thread. 3824 * @param what event code received from native 3825 * @param arg optional argument for event 3826 */ handleStreamEventFromNative(int what, int arg)3827 void handleStreamEventFromNative(int what, int arg) { 3828 if (mStreamEventHandler == null) { 3829 return; 3830 } 3831 switch (what) { 3832 case NATIVE_EVENT_CAN_WRITE_MORE_DATA: 3833 // replace previous CAN_WRITE_MORE_DATA messages with the latest value 3834 mStreamEventHandler.removeMessages(NATIVE_EVENT_CAN_WRITE_MORE_DATA); 3835 mStreamEventHandler.sendMessage( 3836 mStreamEventHandler.obtainMessage( 3837 NATIVE_EVENT_CAN_WRITE_MORE_DATA, arg, 0/*ignored*/)); 3838 break; 3839 case NATIVE_EVENT_NEW_IAUDIOTRACK: 3840 mStreamEventHandler.sendMessage( 3841 mStreamEventHandler.obtainMessage(NATIVE_EVENT_NEW_IAUDIOTRACK)); 3842 break; 3843 case NATIVE_EVENT_STREAM_END: 3844 mStreamEventHandler.sendMessage( 3845 mStreamEventHandler.obtainMessage(NATIVE_EVENT_STREAM_END)); 3846 break; 3847 } 3848 } 3849 3850 private class StreamEventHandler extends Handler { 3851 StreamEventHandler(Looper looper)3852 StreamEventHandler(Looper looper) { 3853 super(looper); 3854 } 3855 3856 @Override handleMessage(Message msg)3857 public void handleMessage(Message msg) { 3858 final LinkedList<StreamEventCbInfo> cbInfoList; 3859 synchronized (mStreamEventCbLock) { 3860 if (msg.what == NATIVE_EVENT_STREAM_END) { 3861 synchronized (mPlayStateLock) { 3862 if (mPlayState == PLAYSTATE_STOPPING) { 3863 if (mOffloadEosPending) { 3864 native_start(); 3865 mPlayState = PLAYSTATE_PLAYING; 3866 } else { 3867 mAvSyncHeader = null; 3868 mAvSyncBytesRemaining = 0; 3869 mPlayState = PLAYSTATE_STOPPED; 3870 } 3871 mOffloadEosPending = false; 3872 mPlayStateLock.notify(); 3873 } 3874 } 3875 } 3876 if (mStreamEventCbInfoList.size() == 0) { 3877 return; 3878 } 3879 cbInfoList = new LinkedList<StreamEventCbInfo>(mStreamEventCbInfoList); 3880 } 3881 3882 final long identity = Binder.clearCallingIdentity(); 3883 try { 3884 for (StreamEventCbInfo cbi : cbInfoList) { 3885 switch (msg.what) { 3886 case NATIVE_EVENT_CAN_WRITE_MORE_DATA: 3887 cbi.mStreamEventExec.execute(() -> 3888 cbi.mStreamEventCb.onDataRequest(AudioTrack.this, msg.arg1)); 3889 break; 3890 case NATIVE_EVENT_NEW_IAUDIOTRACK: 3891 // TODO also release track as it's not longer usable 3892 cbi.mStreamEventExec.execute(() -> 3893 cbi.mStreamEventCb.onTearDown(AudioTrack.this)); 3894 break; 3895 case NATIVE_EVENT_STREAM_END: 3896 cbi.mStreamEventExec.execute(() -> 3897 cbi.mStreamEventCb.onPresentationEnded(AudioTrack.this)); 3898 break; 3899 } 3900 } 3901 } finally { 3902 Binder.restoreCallingIdentity(identity); 3903 } 3904 } 3905 } 3906 3907 @GuardedBy("mStreamEventCbLock") beginStreamEventHandling()3908 private void beginStreamEventHandling() { 3909 if (mStreamEventHandlerThread == null) { 3910 mStreamEventHandlerThread = new HandlerThread(TAG + ".StreamEvent"); 3911 mStreamEventHandlerThread.start(); 3912 final Looper looper = mStreamEventHandlerThread.getLooper(); 3913 if (looper != null) { 3914 mStreamEventHandler = new StreamEventHandler(looper); 3915 } 3916 } 3917 } 3918 3919 @GuardedBy("mStreamEventCbLock") endStreamEventHandling()3920 private void endStreamEventHandling() { 3921 if (mStreamEventHandlerThread != null) { 3922 mStreamEventHandlerThread.quit(); 3923 mStreamEventHandlerThread = null; 3924 } 3925 } 3926 3927 //--------------------------------------------------------- 3928 // Inner classes 3929 //-------------------- 3930 /** 3931 * Helper class to handle the forwarding of native events to the appropriate listener 3932 * (potentially) handled in a different thread 3933 */ 3934 private class NativePositionEventHandlerDelegate { 3935 private final Handler mHandler; 3936 NativePositionEventHandlerDelegate(final AudioTrack track, final OnPlaybackPositionUpdateListener listener, Handler handler)3937 NativePositionEventHandlerDelegate(final AudioTrack track, 3938 final OnPlaybackPositionUpdateListener listener, 3939 Handler handler) { 3940 // find the looper for our new event handler 3941 Looper looper; 3942 if (handler != null) { 3943 looper = handler.getLooper(); 3944 } else { 3945 // no given handler, use the looper the AudioTrack was created in 3946 looper = mInitializationLooper; 3947 } 3948 3949 // construct the event handler with this looper 3950 if (looper != null) { 3951 // implement the event handler delegate 3952 mHandler = new Handler(looper) { 3953 @Override 3954 public void handleMessage(Message msg) { 3955 if (track == null) { 3956 return; 3957 } 3958 switch(msg.what) { 3959 case NATIVE_EVENT_MARKER: 3960 if (listener != null) { 3961 listener.onMarkerReached(track); 3962 } 3963 break; 3964 case NATIVE_EVENT_NEW_POS: 3965 if (listener != null) { 3966 listener.onPeriodicNotification(track); 3967 } 3968 break; 3969 default: 3970 loge("Unknown native event type: " + msg.what); 3971 break; 3972 } 3973 } 3974 }; 3975 } else { 3976 mHandler = null; 3977 } 3978 } 3979 getHandler()3980 Handler getHandler() { 3981 return mHandler; 3982 } 3983 } 3984 3985 //--------------------------------------------------------- 3986 // Methods for IPlayer interface 3987 //-------------------- 3988 @Override playerStart()3989 void playerStart() { 3990 play(); 3991 } 3992 3993 @Override playerPause()3994 void playerPause() { 3995 pause(); 3996 } 3997 3998 @Override playerStop()3999 void playerStop() { 4000 stop(); 4001 } 4002 4003 //--------------------------------------------------------- 4004 // Java methods called from the native side 4005 //-------------------- 4006 @SuppressWarnings("unused") 4007 @UnsupportedAppUsage postEventFromNative(Object audiotrack_ref, int what, int arg1, int arg2, Object obj)4008 private static void postEventFromNative(Object audiotrack_ref, 4009 int what, int arg1, int arg2, Object obj) { 4010 //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2); 4011 final AudioTrack track = (AudioTrack) ((WeakReference) audiotrack_ref).get(); 4012 if (track == null) { 4013 return; 4014 } 4015 4016 if (what == AudioSystem.NATIVE_EVENT_ROUTING_CHANGE) { 4017 track.broadcastRoutingChange(); 4018 return; 4019 } 4020 4021 if (what == NATIVE_EVENT_CODEC_FORMAT_CHANGE) { 4022 ByteBuffer buffer = (ByteBuffer) obj; 4023 buffer.order(ByteOrder.nativeOrder()); 4024 buffer.rewind(); 4025 AudioMetadataReadMap audioMetaData = AudioMetadata.fromByteBuffer(buffer); 4026 if (audioMetaData == null) { 4027 Log.e(TAG, "Unable to get audio metadata from byte buffer"); 4028 return; 4029 } 4030 track.mCodecFormatChangedListeners.notify(0 /* eventCode, unused */, audioMetaData); 4031 return; 4032 } 4033 4034 if (what == NATIVE_EVENT_CAN_WRITE_MORE_DATA 4035 || what == NATIVE_EVENT_NEW_IAUDIOTRACK 4036 || what == NATIVE_EVENT_STREAM_END) { 4037 track.handleStreamEventFromNative(what, arg1); 4038 return; 4039 } 4040 4041 NativePositionEventHandlerDelegate delegate = track.mEventHandlerDelegate; 4042 if (delegate != null) { 4043 Handler handler = delegate.getHandler(); 4044 if (handler != null) { 4045 Message m = handler.obtainMessage(what, arg1, arg2, obj); 4046 handler.sendMessage(m); 4047 } 4048 } 4049 } 4050 4051 //--------------------------------------------------------- 4052 // Native methods called from the Java side 4053 //-------------------- 4054 native_is_direct_output_supported(int encoding, int sampleRate, int channelMask, int channelIndexMask, int contentType, int usage, int flags)4055 private static native boolean native_is_direct_output_supported(int encoding, int sampleRate, 4056 int channelMask, int channelIndexMask, int contentType, int usage, int flags); 4057 4058 // post-condition: mStreamType is overwritten with a value 4059 // that reflects the audio attributes (e.g. an AudioAttributes object with a usage of 4060 // AudioAttributes.USAGE_MEDIA will map to AudioManager.STREAM_MUSIC native_setup(Object audiotrack_this, Object attributes, int[] sampleRate, int channelMask, int channelIndexMask, int audioFormat, int buffSizeInBytes, int mode, int[] sessionId, long nativeAudioTrack, boolean offload, int encapsulationMode, Object tunerConfiguration)4061 private native final int native_setup(Object /*WeakReference<AudioTrack>*/ audiotrack_this, 4062 Object /*AudioAttributes*/ attributes, 4063 int[] sampleRate, int channelMask, int channelIndexMask, int audioFormat, 4064 int buffSizeInBytes, int mode, int[] sessionId, long nativeAudioTrack, 4065 boolean offload, int encapsulationMode, Object tunerConfiguration); 4066 native_finalize()4067 private native final void native_finalize(); 4068 4069 /** 4070 * @hide 4071 */ 4072 @UnsupportedAppUsage native_release()4073 public native final void native_release(); 4074 native_start()4075 private native final void native_start(); 4076 native_stop()4077 private native final void native_stop(); 4078 native_pause()4079 private native final void native_pause(); 4080 native_flush()4081 private native final void native_flush(); 4082 native_write_byte(byte[] audioData, int offsetInBytes, int sizeInBytes, int format, boolean isBlocking)4083 private native final int native_write_byte(byte[] audioData, 4084 int offsetInBytes, int sizeInBytes, int format, 4085 boolean isBlocking); 4086 native_write_short(short[] audioData, int offsetInShorts, int sizeInShorts, int format, boolean isBlocking)4087 private native final int native_write_short(short[] audioData, 4088 int offsetInShorts, int sizeInShorts, int format, 4089 boolean isBlocking); 4090 native_write_float(float[] audioData, int offsetInFloats, int sizeInFloats, int format, boolean isBlocking)4091 private native final int native_write_float(float[] audioData, 4092 int offsetInFloats, int sizeInFloats, int format, 4093 boolean isBlocking); 4094 native_write_native_bytes(ByteBuffer audioData, int positionInBytes, int sizeInBytes, int format, boolean blocking)4095 private native final int native_write_native_bytes(ByteBuffer audioData, 4096 int positionInBytes, int sizeInBytes, int format, boolean blocking); 4097 native_reload_static()4098 private native final int native_reload_static(); 4099 native_get_buffer_size_frames()4100 private native final int native_get_buffer_size_frames(); native_set_buffer_size_frames(int bufferSizeInFrames)4101 private native final int native_set_buffer_size_frames(int bufferSizeInFrames); native_get_buffer_capacity_frames()4102 private native final int native_get_buffer_capacity_frames(); 4103 native_setVolume(float leftVolume, float rightVolume)4104 private native final void native_setVolume(float leftVolume, float rightVolume); 4105 native_set_playback_rate(int sampleRateInHz)4106 private native final int native_set_playback_rate(int sampleRateInHz); native_get_playback_rate()4107 private native final int native_get_playback_rate(); 4108 native_set_playback_params(@onNull PlaybackParams params)4109 private native final void native_set_playback_params(@NonNull PlaybackParams params); native_get_playback_params()4110 private native final @NonNull PlaybackParams native_get_playback_params(); 4111 native_set_marker_pos(int marker)4112 private native final int native_set_marker_pos(int marker); native_get_marker_pos()4113 private native final int native_get_marker_pos(); 4114 native_set_pos_update_period(int updatePeriod)4115 private native final int native_set_pos_update_period(int updatePeriod); native_get_pos_update_period()4116 private native final int native_get_pos_update_period(); 4117 native_set_position(int position)4118 private native final int native_set_position(int position); native_get_position()4119 private native final int native_get_position(); 4120 native_get_latency()4121 private native final int native_get_latency(); 4122 native_get_underrun_count()4123 private native final int native_get_underrun_count(); 4124 native_get_flags()4125 private native final int native_get_flags(); 4126 4127 // longArray must be a non-null array of length >= 2 4128 // [0] is assigned the frame position 4129 // [1] is assigned the time in CLOCK_MONOTONIC nanoseconds native_get_timestamp(long[] longArray)4130 private native final int native_get_timestamp(long[] longArray); 4131 native_set_loop(int start, int end, int loopCount)4132 private native final int native_set_loop(int start, int end, int loopCount); 4133 native_get_output_sample_rate(int streamType)4134 static private native final int native_get_output_sample_rate(int streamType); native_get_min_buff_size( int sampleRateInHz, int channelConfig, int audioFormat)4135 static private native final int native_get_min_buff_size( 4136 int sampleRateInHz, int channelConfig, int audioFormat); 4137 native_attachAuxEffect(int effectId)4138 private native final int native_attachAuxEffect(int effectId); native_setAuxEffectSendLevel(float level)4139 private native final int native_setAuxEffectSendLevel(float level); 4140 native_setOutputDevice(int deviceId)4141 private native final boolean native_setOutputDevice(int deviceId); native_getRoutedDeviceId()4142 private native final int native_getRoutedDeviceId(); native_enableDeviceCallback()4143 private native final void native_enableDeviceCallback(); native_disableDeviceCallback()4144 private native final void native_disableDeviceCallback(); 4145 native_applyVolumeShaper( @onNull VolumeShaper.Configuration configuration, @NonNull VolumeShaper.Operation operation)4146 private native int native_applyVolumeShaper( 4147 @NonNull VolumeShaper.Configuration configuration, 4148 @NonNull VolumeShaper.Operation operation); 4149 native_getVolumeShaperState(int id)4150 private native @Nullable VolumeShaper.State native_getVolumeShaperState(int id); native_setPresentation(int presentationId, int programId)4151 private native final int native_setPresentation(int presentationId, int programId); 4152 native_getPortId()4153 private native int native_getPortId(); 4154 native_set_delay_padding(int delayInFrames, int paddingInFrames)4155 private native void native_set_delay_padding(int delayInFrames, int paddingInFrames); 4156 native_set_audio_description_mix_level_db(float level)4157 private native int native_set_audio_description_mix_level_db(float level); native_get_audio_description_mix_level_db(float[] level)4158 private native int native_get_audio_description_mix_level_db(float[] level); native_set_dual_mono_mode(int dualMonoMode)4159 private native int native_set_dual_mono_mode(int dualMonoMode); native_get_dual_mono_mode(int[] dualMonoMode)4160 private native int native_get_dual_mono_mode(int[] dualMonoMode); 4161 4162 //--------------------------------------------------------- 4163 // Utility methods 4164 //------------------ 4165 logd(String msg)4166 private static void logd(String msg) { 4167 Log.d(TAG, msg); 4168 } 4169 loge(String msg)4170 private static void loge(String msg) { 4171 Log.e(TAG, msg); 4172 } 4173 4174 public final static class MetricsConstants 4175 { MetricsConstants()4176 private MetricsConstants() {} 4177 4178 // MM_PREFIX is slightly different than TAG, used to avoid cut-n-paste errors. 4179 private static final String MM_PREFIX = "android.media.audiotrack."; 4180 4181 /** 4182 * Key to extract the stream type for this track 4183 * from the {@link AudioTrack#getMetrics} return value. 4184 * This value may not exist in API level {@link android.os.Build.VERSION_CODES#P}. 4185 * The value is a {@code String}. 4186 */ 4187 public static final String STREAMTYPE = MM_PREFIX + "streamtype"; 4188 4189 /** 4190 * Key to extract the attribute content type for this track 4191 * from the {@link AudioTrack#getMetrics} return value. 4192 * The value is a {@code String}. 4193 */ 4194 public static final String CONTENTTYPE = MM_PREFIX + "type"; 4195 4196 /** 4197 * Key to extract the attribute usage for this track 4198 * from the {@link AudioTrack#getMetrics} return value. 4199 * The value is a {@code String}. 4200 */ 4201 public static final String USAGE = MM_PREFIX + "usage"; 4202 4203 /** 4204 * Key to extract the sample rate for this track in Hz 4205 * from the {@link AudioTrack#getMetrics} return value. 4206 * The value is an {@code int}. 4207 * @deprecated This does not work. Use {@link AudioTrack#getSampleRate()} instead. 4208 */ 4209 @Deprecated 4210 public static final String SAMPLERATE = "android.media.audiorecord.samplerate"; 4211 4212 /** 4213 * Key to extract the native channel mask information for this track 4214 * from the {@link AudioTrack#getMetrics} return value. 4215 * 4216 * The value is a {@code long}. 4217 * @deprecated This does not work. Use {@link AudioTrack#getFormat()} and read from 4218 * the returned format instead. 4219 */ 4220 @Deprecated 4221 public static final String CHANNELMASK = "android.media.audiorecord.channelmask"; 4222 4223 /** 4224 * Use for testing only. Do not expose. 4225 * The current sample rate. 4226 * The value is an {@code int}. 4227 * @hide 4228 */ 4229 @TestApi 4230 public static final String SAMPLE_RATE = MM_PREFIX + "sampleRate"; 4231 4232 /** 4233 * Use for testing only. Do not expose. 4234 * The native channel mask. 4235 * The value is a {@code long}. 4236 * @hide 4237 */ 4238 @TestApi 4239 public static final String CHANNEL_MASK = MM_PREFIX + "channelMask"; 4240 4241 /** 4242 * Use for testing only. Do not expose. 4243 * The output audio data encoding. 4244 * The value is a {@code String}. 4245 * @hide 4246 */ 4247 @TestApi 4248 public static final String ENCODING = MM_PREFIX + "encoding"; 4249 4250 /** 4251 * Use for testing only. Do not expose. 4252 * The port id of this track port in audioserver. 4253 * The value is an {@code int}. 4254 * @hide 4255 */ 4256 @TestApi 4257 public static final String PORT_ID = MM_PREFIX + "portId"; 4258 4259 /** 4260 * Use for testing only. Do not expose. 4261 * The buffer frameCount. 4262 * The value is an {@code int}. 4263 * @hide 4264 */ 4265 @TestApi 4266 public static final String FRAME_COUNT = MM_PREFIX + "frameCount"; 4267 4268 /** 4269 * Use for testing only. Do not expose. 4270 * The actual track attributes used. 4271 * The value is a {@code String}. 4272 * @hide 4273 */ 4274 @TestApi 4275 public static final String ATTRIBUTES = MM_PREFIX + "attributes"; 4276 } 4277 } 4278