• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.IntDef;
20 import android.annotation.IntRange;
21 import android.annotation.NonNull;
22 import android.annotation.TestApi;
23 import android.annotation.UnsupportedAppUsage;
24 import android.os.Parcel;
25 import android.os.Parcelable;
26 
27 import java.lang.annotation.Retention;
28 import java.lang.annotation.RetentionPolicy;
29 import java.util.Arrays;
30 import java.util.Objects;
31 
32 /**
33  * The {@link AudioFormat} class is used to access a number of audio format and
34  * channel configuration constants. They are for instance used
35  * in {@link AudioTrack} and {@link AudioRecord}, as valid values in individual parameters of
36  * constructors like {@link AudioTrack#AudioTrack(int, int, int, int, int, int)}, where the fourth
37  * parameter is one of the <code>AudioFormat.ENCODING_*</code> constants.
38  * The <code>AudioFormat</code> constants are also used in {@link MediaFormat} to specify
39  * audio related values commonly used in media, such as for {@link MediaFormat#KEY_CHANNEL_MASK}.
40  * <p>The {@link AudioFormat.Builder} class can be used to create instances of
41  * the <code>AudioFormat</code> format class.
42  * Refer to
43  * {@link AudioFormat.Builder} for documentation on the mechanics of the configuration and building
44  * of such instances. Here we describe the main concepts that the <code>AudioFormat</code> class
45  * allow you to convey in each instance, they are:
46  * <ol>
47  * <li><a href="#sampleRate">sample rate</a>
48  * <li><a href="#encoding">encoding</a>
49  * <li><a href="#channelMask">channel masks</a>
50  * </ol>
51  * <p>Closely associated with the <code>AudioFormat</code> is the notion of an
52  * <a href="#audioFrame">audio frame</a>, which is used throughout the documentation
53  * to represent the minimum size complete unit of audio data.
54  *
55  * <h4 id="sampleRate">Sample rate</h4>
56  * <p>Expressed in Hz, the sample rate in an <code>AudioFormat</code> instance expresses the number
57  * of audio samples for each channel per second in the content you are playing or recording. It is
58  * not the sample rate
59  * at which content is rendered or produced. For instance a sound at a media sample rate of 8000Hz
60  * can be played on a device operating at a sample rate of 48000Hz; the sample rate conversion is
61  * automatically handled by the platform, it will not play at 6x speed.
62  *
63  * <p>As of API {@link android.os.Build.VERSION_CODES#M},
64  * sample rates up to 192kHz are supported
65  * for <code>AudioRecord</code> and <code>AudioTrack</code>, with sample rate conversion
66  * performed as needed.
67  * To improve efficiency and avoid lossy conversions, it is recommended to match the sample rate
68  * for <code>AudioRecord</code> and <code>AudioTrack</code> to the endpoint device
69  * sample rate, and limit the sample rate to no more than 48kHz unless there are special
70  * device capabilities that warrant a higher rate.
71  *
72  * <h4 id="encoding">Encoding</h4>
73  * <p>Audio encoding is used to describe the bit representation of audio data, which can be
74  * either linear PCM or compressed audio, such as AC3 or DTS.
75  * <p>For linear PCM, the audio encoding describes the sample size, 8 bits, 16 bits, or 32 bits,
76  * and the sample representation, integer or float.
77  * <ul>
78  * <li> {@link #ENCODING_PCM_8BIT}: The audio sample is a 8 bit unsigned integer in the
79  * range [0, 255], with a 128 offset for zero. This is typically stored as a Java byte in a
80  * byte array or ByteBuffer. Since the Java byte is <em>signed</em>,
81  * be careful with math operations and conversions as the most significant bit is inverted.
82  * </li>
83  * <li> {@link #ENCODING_PCM_16BIT}: The audio sample is a 16 bit signed integer
84  * typically stored as a Java short in a short array, but when the short
85  * is stored in a ByteBuffer, it is native endian (as compared to the default Java big endian).
86  * The short has full range from [-32768, 32767],
87  * and is sometimes interpreted as fixed point Q.15 data.
88  * </li>
89  * <li> {@link #ENCODING_PCM_FLOAT}: Introduced in
90  * API {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this encoding specifies that
91  * the audio sample is a 32 bit IEEE single precision float. The sample can be
92  * manipulated as a Java float in a float array, though within a ByteBuffer
93  * it is stored in native endian byte order.
94  * The nominal range of <code>ENCODING_PCM_FLOAT</code> audio data is [-1.0, 1.0].
95  * It is implementation dependent whether the positive maximum of 1.0 is included
96  * in the interval. Values outside of the nominal range are clamped before
97  * sending to the endpoint device. Beware that
98  * the handling of NaN is undefined; subnormals may be treated as zero; and
99  * infinities are generally clamped just like other values for <code>AudioTrack</code>
100  * &ndash; try to avoid infinities because they can easily generate a NaN.
101  * <br>
102  * To achieve higher audio bit depth than a signed 16 bit integer short,
103  * it is recommended to use <code>ENCODING_PCM_FLOAT</code> for audio capture, processing,
104  * and playback.
105  * Floats are efficiently manipulated by modern CPUs,
106  * have greater precision than 24 bit signed integers,
107  * and have greater dynamic range than 32 bit signed integers.
108  * <code>AudioRecord</code> as of API {@link android.os.Build.VERSION_CODES#M} and
109  * <code>AudioTrack</code> as of API {@link android.os.Build.VERSION_CODES#LOLLIPOP}
110  * support <code>ENCODING_PCM_FLOAT</code>.
111  * </li>
112  * </ul>
113  * <p>For compressed audio, the encoding specifies the method of compression,
114  * for example {@link #ENCODING_AC3} and {@link #ENCODING_DTS}. The compressed
115  * audio data is typically stored as bytes in
116  * a byte array or ByteBuffer. When a compressed audio encoding is specified
117  * for an <code>AudioTrack</code>, it creates a direct (non-mixed) track
118  * for output to an endpoint (such as HDMI) capable of decoding the compressed audio.
119  * For (most) other endpoints, which are not capable of decoding such compressed audio,
120  * you will need to decode the data first, typically by creating a {@link MediaCodec}.
121  * Alternatively, one may use {@link MediaPlayer} for playback of compressed
122  * audio files or streams.
123  * <p>When compressed audio is sent out through a direct <code>AudioTrack</code>,
124  * it need not be written in exact multiples of the audio access unit;
125  * this differs from <code>MediaCodec</code> input buffers.
126  *
127  * <h4 id="channelMask">Channel mask</h4>
128  * <p>Channel masks are used in <code>AudioTrack</code> and <code>AudioRecord</code> to describe
129  * the samples and their arrangement in the audio frame. They are also used in the endpoint (e.g.
130  * a USB audio interface, a DAC connected to headphones) to specify allowable configurations of a
131  * particular device.
132  * <br>As of API {@link android.os.Build.VERSION_CODES#M}, there are two types of channel masks:
133  * channel position masks and channel index masks.
134  *
135  * <h5 id="channelPositionMask">Channel position masks</h5>
136  * Channel position masks are the original Android channel masks, and are used since API
137  * {@link android.os.Build.VERSION_CODES#BASE}.
138  * For input and output, they imply a positional nature - the location of a speaker or a microphone
139  * for recording or playback.
140  * <br>For a channel position mask, each allowed channel position corresponds to a bit in the
141  * channel mask. If that channel position is present in the audio frame, that bit is set,
142  * otherwise it is zero. The order of the bits (from lsb to msb) corresponds to the order of that
143  * position's sample in the audio frame.
144  * <br>The canonical channel position masks by channel count are as follows:
145  * <br><table>
146  * <tr><td>channel count</td><td>channel position mask</td></tr>
147  * <tr><td>1</td><td>{@link #CHANNEL_OUT_MONO}</td></tr>
148  * <tr><td>2</td><td>{@link #CHANNEL_OUT_STEREO}</td></tr>
149  * <tr><td>3</td><td>{@link #CHANNEL_OUT_STEREO} | {@link #CHANNEL_OUT_FRONT_CENTER}</td></tr>
150  * <tr><td>4</td><td>{@link #CHANNEL_OUT_QUAD}</td></tr>
151  * <tr><td>5</td><td>{@link #CHANNEL_OUT_QUAD} | {@link #CHANNEL_OUT_FRONT_CENTER}</td></tr>
152  * <tr><td>6</td><td>{@link #CHANNEL_OUT_5POINT1}</td></tr>
153  * <tr><td>7</td><td>{@link #CHANNEL_OUT_5POINT1} | {@link #CHANNEL_OUT_BACK_CENTER}</td></tr>
154  * <tr><td>8</td><td>{@link #CHANNEL_OUT_7POINT1_SURROUND}</td></tr>
155  * </table>
156  * <br>These masks are an ORed composite of individual channel masks. For example
157  * {@link #CHANNEL_OUT_STEREO} is composed of {@link #CHANNEL_OUT_FRONT_LEFT} and
158  * {@link #CHANNEL_OUT_FRONT_RIGHT}.
159  *
160  * <h5 id="channelIndexMask">Channel index masks</h5>
161  * Channel index masks are introduced in API {@link android.os.Build.VERSION_CODES#M}. They allow
162  * the selection of a particular channel from the source or sink endpoint by number, i.e. the first
163  * channel, the second channel, and so forth. This avoids problems with artificially assigning
164  * positions to channels of an endpoint, or figuring what the i<sup>th</sup> position bit is within
165  * an endpoint's channel position mask etc.
166  * <br>Here's an example where channel index masks address this confusion: dealing with a 4 channel
167  * USB device. Using a position mask, and based on the channel count, this would be a
168  * {@link #CHANNEL_OUT_QUAD} device, but really one is only interested in channel 0
169  * through channel 3. The USB device would then have the following individual bit channel masks:
170  * {@link #CHANNEL_OUT_FRONT_LEFT},
171  * {@link #CHANNEL_OUT_FRONT_RIGHT}, {@link #CHANNEL_OUT_BACK_LEFT}
172  * and {@link #CHANNEL_OUT_BACK_RIGHT}. But which is channel 0 and which is
173  * channel 3?
174  * <br>For a channel index mask, each channel number is represented as a bit in the mask, from the
175  * lsb (channel 0) upwards to the msb, numerically this bit value is
176  * <code>1 << channelNumber</code>.
177  * A set bit indicates that channel is present in the audio frame, otherwise it is cleared.
178  * The order of the bits also correspond to that channel number's sample order in the audio frame.
179  * <br>For the previous 4 channel USB device example, the device would have a channel index mask
180  * <code>0xF</code>. Suppose we wanted to select only the first and the third channels; this would
181  * correspond to a channel index mask <code>0x5</code> (the first and third bits set). If an
182  * <code>AudioTrack</code> uses this channel index mask, the audio frame would consist of two
183  * samples, the first sample of each frame routed to channel 0, and the second sample of each frame
184  * routed to channel 2.
185  * The canonical channel index masks by channel count are given by the formula
186  * <code>(1 << channelCount) - 1</code>.
187  *
188  * <h5>Use cases</h5>
189  * <ul>
190  * <li><i>Channel position mask for an endpoint:</i> <code>CHANNEL_OUT_FRONT_LEFT</code>,
191  *  <code>CHANNEL_OUT_FRONT_CENTER</code>, etc. for HDMI home theater purposes.
192  * <li><i>Channel position mask for an audio stream:</i> Creating an <code>AudioTrack</code>
193  *  to output movie content, where 5.1 multichannel output is to be written.
194  * <li><i>Channel index mask for an endpoint:</i> USB devices for which input and output do not
195  *  correspond to left or right speaker or microphone.
196  * <li><i>Channel index mask for an audio stream:</i> An <code>AudioRecord</code> may only want the
197  *  third and fourth audio channels of the endpoint (i.e. the second channel pair), and not care the
198  *  about position it corresponds to, in which case the channel index mask is <code>0xC</code>.
199  *  Multichannel <code>AudioRecord</code> sessions should use channel index masks.
200  * </ul>
201  * <h4 id="audioFrame">Audio Frame</h4>
202  * <p>For linear PCM, an audio frame consists of a set of samples captured at the same time,
203  * whose count and
204  * channel association are given by the <a href="#channelMask">channel mask</a>,
205  * and whose sample contents are specified by the <a href="#encoding">encoding</a>.
206  * For example, a stereo 16 bit PCM frame consists of
207  * two 16 bit linear PCM samples, with a frame size of 4 bytes.
208  * For compressed audio, an audio frame may alternately
209  * refer to an access unit of compressed data bytes that is logically grouped together for
210  * decoding and bitstream access (e.g. {@link MediaCodec}),
211  * or a single byte of compressed data (e.g. {@link AudioTrack#getBufferSizeInFrames()
212  * AudioTrack.getBufferSizeInFrames()}),
213  * or the linear PCM frame result from decoding the compressed data
214  * (e.g.{@link AudioTrack#getPlaybackHeadPosition()
215  * AudioTrack.getPlaybackHeadPosition()}),
216  * depending on the context where audio frame is used.
217  * For the purposes of {@link AudioFormat#getFrameSizeInBytes()}, a compressed data format
218  * returns a frame size of 1 byte.
219  */
220 public final class AudioFormat implements Parcelable {
221 
222     //---------------------------------------------------------
223     // Constants
224     //--------------------
225     /** Invalid audio data format */
226     public static final int ENCODING_INVALID = 0;
227     /** Default audio data format */
228     public static final int ENCODING_DEFAULT = 1;
229 
230     // These values must be kept in sync with core/jni/android_media_AudioFormat.h
231     // Also sync av/services/audiopolicy/managerdefault/ConfigParsingUtils.h
232     /** Audio data format: PCM 16 bit per sample. Guaranteed to be supported by devices. */
233     public static final int ENCODING_PCM_16BIT = 2;
234     /** Audio data format: PCM 8 bit per sample. Not guaranteed to be supported by devices. */
235     public static final int ENCODING_PCM_8BIT = 3;
236     /** Audio data format: single-precision floating-point per sample */
237     public static final int ENCODING_PCM_FLOAT = 4;
238     /** Audio data format: AC-3 compressed */
239     public static final int ENCODING_AC3 = 5;
240     /** Audio data format: E-AC-3 compressed */
241     public static final int ENCODING_E_AC3 = 6;
242     /** Audio data format: DTS compressed */
243     public static final int ENCODING_DTS = 7;
244     /** Audio data format: DTS HD compressed */
245     public static final int ENCODING_DTS_HD = 8;
246     /** Audio data format: MP3 compressed */
247     public static final int ENCODING_MP3 = 9;
248     /** Audio data format: AAC LC compressed */
249     public static final int ENCODING_AAC_LC = 10;
250     /** Audio data format: AAC HE V1 compressed */
251     public static final int ENCODING_AAC_HE_V1 = 11;
252     /** Audio data format: AAC HE V2 compressed */
253     public static final int ENCODING_AAC_HE_V2 = 12;
254 
255     /** Audio data format: compressed audio wrapped in PCM for HDMI
256      * or S/PDIF passthrough.
257      * IEC61937 uses a stereo stream of 16-bit samples as the wrapper.
258      * So the channel mask for the track must be {@link #CHANNEL_OUT_STEREO}.
259      * Data should be written to the stream in a short[] array.
260      * If the data is written in a byte[] array then there may be endian problems
261      * on some platforms when converting to short internally.
262      */
263     public static final int ENCODING_IEC61937 = 13;
264     /** Audio data format: DOLBY TRUEHD compressed
265      **/
266     public static final int ENCODING_DOLBY_TRUEHD = 14;
267     /** Audio data format: AAC ELD compressed */
268     public static final int ENCODING_AAC_ELD = 15;
269     /** Audio data format: AAC xHE compressed */
270     public static final int ENCODING_AAC_XHE = 16;
271     /** Audio data format: AC-4 sync frame transport format */
272     public static final int ENCODING_AC4 = 17;
273     /** Audio data format: E-AC-3-JOC compressed
274      * E-AC-3-JOC streams can be decoded by downstream devices supporting {@link #ENCODING_E_AC3}.
275      * Use {@link #ENCODING_E_AC3} as the AudioTrack encoding when the downstream device
276      * supports {@link #ENCODING_E_AC3} but not {@link #ENCODING_E_AC3_JOC}.
277      **/
278     public static final int ENCODING_E_AC3_JOC = 18;
279     /** Audio data format: Dolby MAT (Metadata-enhanced Audio Transmission)
280      * Dolby MAT bitstreams are used to transmit Dolby TrueHD, channel-based PCM, or PCM with
281      * metadata (object audio) over HDMI (e.g. Dolby Atmos content).
282      **/
283     public static final int ENCODING_DOLBY_MAT = 19;
284 
285     /** @hide */
toLogFriendlyEncoding(int enc)286     public static String toLogFriendlyEncoding(int enc) {
287         switch(enc) {
288             case ENCODING_INVALID:
289                 return "ENCODING_INVALID";
290             case ENCODING_PCM_16BIT:
291                 return "ENCODING_PCM_16BIT";
292             case ENCODING_PCM_8BIT:
293                 return "ENCODING_PCM_8BIT";
294             case ENCODING_PCM_FLOAT:
295                 return "ENCODING_PCM_FLOAT";
296             case ENCODING_AC3:
297                 return "ENCODING_AC3";
298             case ENCODING_E_AC3:
299                 return "ENCODING_E_AC3";
300             case ENCODING_DTS:
301                 return "ENCODING_DTS";
302             case ENCODING_DTS_HD:
303                 return "ENCODING_DTS_HD";
304             case ENCODING_MP3:
305                 return "ENCODING_MP3";
306             case ENCODING_AAC_LC:
307                 return "ENCODING_AAC_LC";
308             case ENCODING_AAC_HE_V1:
309                 return "ENCODING_AAC_HE_V1";
310             case ENCODING_AAC_HE_V2:
311                 return "ENCODING_AAC_HE_V2";
312             case ENCODING_IEC61937:
313                 return "ENCODING_IEC61937";
314             case ENCODING_DOLBY_TRUEHD:
315                 return "ENCODING_DOLBY_TRUEHD";
316             case ENCODING_AAC_ELD:
317                 return "ENCODING_AAC_ELD";
318             case ENCODING_AAC_XHE:
319                 return "ENCODING_AAC_XHE";
320             case ENCODING_AC4:
321                 return "ENCODING_AC4";
322             case ENCODING_E_AC3_JOC:
323                 return "ENCODING_E_AC3_JOC";
324             case ENCODING_DOLBY_MAT:
325                 return "ENCODING_DOLBY_MAT";
326             default :
327                 return "invalid encoding " + enc;
328         }
329     }
330 
331     /** Invalid audio channel configuration */
332     /** @deprecated Use {@link #CHANNEL_INVALID} instead.  */
333     @Deprecated    public static final int CHANNEL_CONFIGURATION_INVALID   = 0;
334     /** Default audio channel configuration */
335     /** @deprecated Use {@link #CHANNEL_OUT_DEFAULT} or {@link #CHANNEL_IN_DEFAULT} instead.  */
336     @Deprecated    public static final int CHANNEL_CONFIGURATION_DEFAULT   = 1;
337     /** Mono audio configuration */
338     /** @deprecated Use {@link #CHANNEL_OUT_MONO} or {@link #CHANNEL_IN_MONO} instead.  */
339     @Deprecated    public static final int CHANNEL_CONFIGURATION_MONO      = 2;
340     /** Stereo (2 channel) audio configuration */
341     /** @deprecated Use {@link #CHANNEL_OUT_STEREO} or {@link #CHANNEL_IN_STEREO} instead.  */
342     @Deprecated    public static final int CHANNEL_CONFIGURATION_STEREO    = 3;
343 
344     /** Invalid audio channel mask */
345     public static final int CHANNEL_INVALID = 0;
346     /** Default audio channel mask */
347     public static final int CHANNEL_OUT_DEFAULT = 1;
348 
349     // Output channel mask definitions below are translated to the native values defined in
350     //  in /system/media/audio/include/system/audio.h in the JNI code of AudioTrack
351     public static final int CHANNEL_OUT_FRONT_LEFT = 0x4;
352     public static final int CHANNEL_OUT_FRONT_RIGHT = 0x8;
353     public static final int CHANNEL_OUT_FRONT_CENTER = 0x10;
354     public static final int CHANNEL_OUT_LOW_FREQUENCY = 0x20;
355     public static final int CHANNEL_OUT_BACK_LEFT = 0x40;
356     public static final int CHANNEL_OUT_BACK_RIGHT = 0x80;
357     public static final int CHANNEL_OUT_FRONT_LEFT_OF_CENTER = 0x100;
358     public static final int CHANNEL_OUT_FRONT_RIGHT_OF_CENTER = 0x200;
359     public static final int CHANNEL_OUT_BACK_CENTER = 0x400;
360     public static final int CHANNEL_OUT_SIDE_LEFT =         0x800;
361     public static final int CHANNEL_OUT_SIDE_RIGHT =       0x1000;
362     /** @hide */
363     public static final int CHANNEL_OUT_TOP_CENTER =       0x2000;
364     /** @hide */
365     public static final int CHANNEL_OUT_TOP_FRONT_LEFT =   0x4000;
366     /** @hide */
367     public static final int CHANNEL_OUT_TOP_FRONT_CENTER = 0x8000;
368     /** @hide */
369     public static final int CHANNEL_OUT_TOP_FRONT_RIGHT = 0x10000;
370     /** @hide */
371     public static final int CHANNEL_OUT_TOP_BACK_LEFT =   0x20000;
372     /** @hide */
373     public static final int CHANNEL_OUT_TOP_BACK_CENTER = 0x40000;
374     /** @hide */
375     public static final int CHANNEL_OUT_TOP_BACK_RIGHT =  0x80000;
376 
377     public static final int CHANNEL_OUT_MONO = CHANNEL_OUT_FRONT_LEFT;
378     public static final int CHANNEL_OUT_STEREO = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT);
379     // aka QUAD_BACK
380     public static final int CHANNEL_OUT_QUAD = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
381             CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT);
382     /** @hide */
383     public static final int CHANNEL_OUT_QUAD_SIDE = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
384             CHANNEL_OUT_SIDE_LEFT | CHANNEL_OUT_SIDE_RIGHT);
385     public static final int CHANNEL_OUT_SURROUND = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
386             CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_BACK_CENTER);
387     // aka 5POINT1_BACK
388     public static final int CHANNEL_OUT_5POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
389             CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT);
390     /** @hide */
391     public static final int CHANNEL_OUT_5POINT1_SIDE = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
392             CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY |
393             CHANNEL_OUT_SIDE_LEFT | CHANNEL_OUT_SIDE_RIGHT);
394     // different from AUDIO_CHANNEL_OUT_7POINT1 used internally, and not accepted by AudioRecord.
395     /** @deprecated Not the typical 7.1 surround configuration. Use {@link #CHANNEL_OUT_7POINT1_SURROUND} instead. */
396     @Deprecated    public static final int CHANNEL_OUT_7POINT1 = (CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_RIGHT |
397             CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_LOW_FREQUENCY | CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
398             CHANNEL_OUT_FRONT_LEFT_OF_CENTER | CHANNEL_OUT_FRONT_RIGHT_OF_CENTER);
399     // matches AUDIO_CHANNEL_OUT_7POINT1
400     public static final int CHANNEL_OUT_7POINT1_SURROUND = (
401             CHANNEL_OUT_FRONT_LEFT | CHANNEL_OUT_FRONT_CENTER | CHANNEL_OUT_FRONT_RIGHT |
402             CHANNEL_OUT_SIDE_LEFT | CHANNEL_OUT_SIDE_RIGHT |
403             CHANNEL_OUT_BACK_LEFT | CHANNEL_OUT_BACK_RIGHT |
404             CHANNEL_OUT_LOW_FREQUENCY);
405     // CHANNEL_OUT_ALL is not yet defined; if added then it should match AUDIO_CHANNEL_OUT_ALL
406 
407     /** Minimum value for sample rate,
408      *  assuming AudioTrack and AudioRecord share the same limitations.
409      * @hide
410      */
411     // never unhide
412     public static final int SAMPLE_RATE_HZ_MIN = 4000;
413     /** Maximum value for sample rate,
414      *  assuming AudioTrack and AudioRecord share the same limitations.
415      * @hide
416      */
417     // never unhide
418     public static final int SAMPLE_RATE_HZ_MAX = 192000;
419     /** Sample rate will be a route-dependent value.
420      * For AudioTrack, it is usually the sink sample rate,
421      * and for AudioRecord it is usually the source sample rate.
422      */
423     public static final int SAMPLE_RATE_UNSPECIFIED = 0;
424 
425     /**
426      * @hide
427      * Return the input channel mask corresponding to an output channel mask.
428      * This can be used for submix rerouting for the mask of the recorder to map to that of the mix.
429      * @param outMask a combination of the CHANNEL_OUT_* definitions, but not CHANNEL_OUT_DEFAULT
430      * @return a combination of CHANNEL_IN_* definitions matching an output channel mask
431      * @throws IllegalArgumentException
432      */
inChannelMaskFromOutChannelMask(int outMask)433     public static int inChannelMaskFromOutChannelMask(int outMask) throws IllegalArgumentException {
434         if (outMask == CHANNEL_OUT_DEFAULT) {
435             throw new IllegalArgumentException(
436                     "Illegal CHANNEL_OUT_DEFAULT channel mask for input.");
437         }
438         switch (channelCountFromOutChannelMask(outMask)) {
439             case 1:
440                 return CHANNEL_IN_MONO;
441             case 2:
442                 return CHANNEL_IN_STEREO;
443             default:
444                 throw new IllegalArgumentException("Unsupported channel configuration for input.");
445         }
446     }
447 
448     /**
449      * @hide
450      * Return the number of channels from an input channel mask
451      * @param mask a combination of the CHANNEL_IN_* definitions, even CHANNEL_IN_DEFAULT
452      * @return number of channels for the mask
453      */
454     @TestApi
channelCountFromInChannelMask(int mask)455     public static int channelCountFromInChannelMask(int mask) {
456         return Integer.bitCount(mask);
457     }
458     /**
459      * @hide
460      * Return the number of channels from an output channel mask
461      * @param mask a combination of the CHANNEL_OUT_* definitions, but not CHANNEL_OUT_DEFAULT
462      * @return number of channels for the mask
463      */
464     @TestApi
channelCountFromOutChannelMask(int mask)465     public static int channelCountFromOutChannelMask(int mask) {
466         return Integer.bitCount(mask);
467     }
468     /**
469      * @hide
470      * Return a channel mask ready to be used by native code
471      * @param mask a combination of the CHANNEL_OUT_* definitions, but not CHANNEL_OUT_DEFAULT
472      * @return a native channel mask
473      */
convertChannelOutMaskToNativeMask(int javaMask)474     public static int convertChannelOutMaskToNativeMask(int javaMask) {
475         return (javaMask >> 2);
476     }
477 
478     /**
479      * @hide
480      * Return a java output channel mask
481      * @param mask a native channel mask
482      * @return a combination of the CHANNEL_OUT_* definitions
483      */
convertNativeChannelMaskToOutMask(int nativeMask)484     public static int convertNativeChannelMaskToOutMask(int nativeMask) {
485         return (nativeMask << 2);
486     }
487 
488     public static final int CHANNEL_IN_DEFAULT = 1;
489     // These directly match native
490     public static final int CHANNEL_IN_LEFT = 0x4;
491     public static final int CHANNEL_IN_RIGHT = 0x8;
492     public static final int CHANNEL_IN_FRONT = 0x10;
493     public static final int CHANNEL_IN_BACK = 0x20;
494     public static final int CHANNEL_IN_LEFT_PROCESSED = 0x40;
495     public static final int CHANNEL_IN_RIGHT_PROCESSED = 0x80;
496     public static final int CHANNEL_IN_FRONT_PROCESSED = 0x100;
497     public static final int CHANNEL_IN_BACK_PROCESSED = 0x200;
498     public static final int CHANNEL_IN_PRESSURE = 0x400;
499     public static final int CHANNEL_IN_X_AXIS = 0x800;
500     public static final int CHANNEL_IN_Y_AXIS = 0x1000;
501     public static final int CHANNEL_IN_Z_AXIS = 0x2000;
502     public static final int CHANNEL_IN_VOICE_UPLINK = 0x4000;
503     public static final int CHANNEL_IN_VOICE_DNLINK = 0x8000;
504     public static final int CHANNEL_IN_MONO = CHANNEL_IN_FRONT;
505     public static final int CHANNEL_IN_STEREO = (CHANNEL_IN_LEFT | CHANNEL_IN_RIGHT);
506     /** @hide */
507     public static final int CHANNEL_IN_FRONT_BACK = CHANNEL_IN_FRONT | CHANNEL_IN_BACK;
508     // CHANNEL_IN_ALL is not yet defined; if added then it should match AUDIO_CHANNEL_IN_ALL
509 
510     /** @hide */
511     @TestApi
getBytesPerSample(int audioFormat)512     public static int getBytesPerSample(int audioFormat)
513     {
514         switch (audioFormat) {
515         case ENCODING_PCM_8BIT:
516             return 1;
517         case ENCODING_PCM_16BIT:
518         case ENCODING_IEC61937:
519         case ENCODING_DEFAULT:
520             return 2;
521         case ENCODING_PCM_FLOAT:
522             return 4;
523         case ENCODING_INVALID:
524         default:
525             throw new IllegalArgumentException("Bad audio format " + audioFormat);
526         }
527     }
528 
529     /** @hide */
isValidEncoding(int audioFormat)530     public static boolean isValidEncoding(int audioFormat)
531     {
532         switch (audioFormat) {
533             case ENCODING_PCM_16BIT:
534             case ENCODING_PCM_8BIT:
535             case ENCODING_PCM_FLOAT:
536             case ENCODING_AC3:
537             case ENCODING_E_AC3:
538             case ENCODING_DTS:
539             case ENCODING_DTS_HD:
540             case ENCODING_MP3:
541             case ENCODING_AAC_LC:
542             case ENCODING_AAC_HE_V1:
543             case ENCODING_AAC_HE_V2:
544             case ENCODING_IEC61937:
545             case ENCODING_DOLBY_TRUEHD:
546             case ENCODING_AAC_ELD:
547             case ENCODING_AAC_XHE:
548             case ENCODING_AC4:
549             case ENCODING_E_AC3_JOC:
550             case ENCODING_DOLBY_MAT:
551                 return true;
552             default:
553                 return false;
554         }
555     }
556 
557     /** @hide */
isPublicEncoding(int audioFormat)558     public static boolean isPublicEncoding(int audioFormat)
559     {
560         switch (audioFormat) {
561             case ENCODING_PCM_16BIT:
562             case ENCODING_PCM_8BIT:
563             case ENCODING_PCM_FLOAT:
564             case ENCODING_AC3:
565             case ENCODING_E_AC3:
566             case ENCODING_DTS:
567             case ENCODING_DTS_HD:
568             case ENCODING_MP3:
569             case ENCODING_AAC_LC:
570             case ENCODING_AAC_HE_V1:
571             case ENCODING_AAC_HE_V2:
572             case ENCODING_IEC61937:
573             case ENCODING_DOLBY_TRUEHD:
574             case ENCODING_AAC_ELD:
575             case ENCODING_AAC_XHE:
576             case ENCODING_AC4:
577             case ENCODING_E_AC3_JOC:
578             case ENCODING_DOLBY_MAT:
579                 return true;
580             default:
581                 return false;
582         }
583     }
584 
585     /** @hide */
586     @TestApi
isEncodingLinearPcm(int audioFormat)587     public static boolean isEncodingLinearPcm(int audioFormat)
588     {
589         switch (audioFormat) {
590             case ENCODING_PCM_16BIT:
591             case ENCODING_PCM_8BIT:
592             case ENCODING_PCM_FLOAT:
593             case ENCODING_DEFAULT:
594                 return true;
595             case ENCODING_AC3:
596             case ENCODING_E_AC3:
597             case ENCODING_DTS:
598             case ENCODING_DTS_HD:
599             case ENCODING_MP3:
600             case ENCODING_AAC_LC:
601             case ENCODING_AAC_HE_V1:
602             case ENCODING_AAC_HE_V2:
603             case ENCODING_IEC61937: // wrapped in PCM but compressed
604             case ENCODING_DOLBY_TRUEHD:
605             case ENCODING_AAC_ELD:
606             case ENCODING_AAC_XHE:
607             case ENCODING_AC4:
608             case ENCODING_E_AC3_JOC:
609             case ENCODING_DOLBY_MAT:
610                 return false;
611             case ENCODING_INVALID:
612             default:
613                 throw new IllegalArgumentException("Bad audio format " + audioFormat);
614         }
615     }
616 
617     /** @hide */
isEncodingLinearFrames(int audioFormat)618     public static boolean isEncodingLinearFrames(int audioFormat)
619     {
620         switch (audioFormat) {
621             case ENCODING_PCM_16BIT:
622             case ENCODING_PCM_8BIT:
623             case ENCODING_PCM_FLOAT:
624             case ENCODING_IEC61937: // same size as stereo PCM
625             case ENCODING_DEFAULT:
626                 return true;
627             case ENCODING_AC3:
628             case ENCODING_E_AC3:
629             case ENCODING_DTS:
630             case ENCODING_DTS_HD:
631             case ENCODING_MP3:
632             case ENCODING_AAC_LC:
633             case ENCODING_AAC_HE_V1:
634             case ENCODING_AAC_HE_V2:
635             case ENCODING_DOLBY_TRUEHD:
636             case ENCODING_AAC_ELD:
637             case ENCODING_AAC_XHE:
638             case ENCODING_AC4:
639             case ENCODING_E_AC3_JOC:
640             case ENCODING_DOLBY_MAT:
641                 return false;
642             case ENCODING_INVALID:
643             default:
644                 throw new IllegalArgumentException("Bad audio format " + audioFormat);
645         }
646     }
647     /**
648      * Returns an array of public encoding values extracted from an array of
649      * encoding values.
650      * @hide
651      */
filterPublicFormats(int[] formats)652     public static int[] filterPublicFormats(int[] formats) {
653         if (formats == null) {
654             return null;
655         }
656         int[] myCopy = Arrays.copyOf(formats, formats.length);
657         int size = 0;
658         for (int i = 0; i < myCopy.length; i++) {
659             if (isPublicEncoding(myCopy[i])) {
660                 if (size != i) {
661                     myCopy[size] = myCopy[i];
662                 }
663                 size++;
664             }
665         }
666         return Arrays.copyOf(myCopy, size);
667     }
668 
669     /** @removed */
AudioFormat()670     public AudioFormat()
671     {
672         throw new UnsupportedOperationException("There is no valid usage of this constructor");
673     }
674 
675     /**
676      * Constructor used by the JNI.  Parameters are not checked for validity.
677      */
678     // Update sound trigger JNI in core/jni/android_hardware_SoundTrigger.cpp when modifying this
679     // constructor
680     @UnsupportedAppUsage
AudioFormat(int encoding, int sampleRate, int channelMask, int channelIndexMask)681     private AudioFormat(int encoding, int sampleRate, int channelMask, int channelIndexMask) {
682         this(
683              AUDIO_FORMAT_HAS_PROPERTY_ENCODING
684              | AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE
685              | AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK
686              | AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK,
687              encoding, sampleRate, channelMask, channelIndexMask
688              );
689     }
690 
AudioFormat(int propertySetMask, int encoding, int sampleRate, int channelMask, int channelIndexMask)691     private AudioFormat(int propertySetMask,
692             int encoding, int sampleRate, int channelMask, int channelIndexMask) {
693         mPropertySetMask = propertySetMask;
694         mEncoding = (propertySetMask & AUDIO_FORMAT_HAS_PROPERTY_ENCODING) != 0
695                 ? encoding : ENCODING_INVALID;
696         mSampleRate = (propertySetMask & AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE) != 0
697                 ? sampleRate : SAMPLE_RATE_UNSPECIFIED;
698         mChannelMask = (propertySetMask & AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK) != 0
699                 ? channelMask : CHANNEL_INVALID;
700         mChannelIndexMask = (propertySetMask & AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK) != 0
701                 ? channelIndexMask : CHANNEL_INVALID;
702 
703         // Compute derived values.
704 
705         final int channelIndexCount = Integer.bitCount(getChannelIndexMask());
706         int channelCount = channelCountFromOutChannelMask(getChannelMask());
707         if (channelCount == 0) {
708             channelCount = channelIndexCount;
709         } else if (channelCount != channelIndexCount && channelIndexCount != 0) {
710             channelCount = 0; // position and index channel count mismatch
711         }
712         mChannelCount = channelCount;
713 
714         int frameSizeInBytes = 1;
715         try {
716             frameSizeInBytes = getBytesPerSample(mEncoding) * channelCount;
717         } catch (IllegalArgumentException iae) {
718             // ignored
719         }
720         // it is possible that channel count is 0, so ensure we return 1 for
721         // mFrameSizeInBytes for consistency.
722         mFrameSizeInBytes = frameSizeInBytes != 0 ? frameSizeInBytes : 1;
723     }
724 
725     /** @hide */
726     public final static int AUDIO_FORMAT_HAS_PROPERTY_NONE = 0x0;
727     /** @hide */
728     public final static int AUDIO_FORMAT_HAS_PROPERTY_ENCODING = 0x1 << 0;
729     /** @hide */
730     public final static int AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE = 0x1 << 1;
731     /** @hide */
732     public final static int AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK = 0x1 << 2;
733     /** @hide */
734     public final static int AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK = 0x1 << 3;
735 
736     // This is an immutable class, all member variables are final.
737 
738     // Essential values.
739     @UnsupportedAppUsage
740     private final int mEncoding;
741     @UnsupportedAppUsage
742     private final int mSampleRate;
743     @UnsupportedAppUsage
744     private final int mChannelMask;
745     private final int mChannelIndexMask;
746     private final int mPropertySetMask;
747 
748     // Derived values computed in the constructor, cached here.
749     private final int mChannelCount;
750     private final int mFrameSizeInBytes;
751 
752     /**
753      * Return the encoding.
754      * See the section on <a href="#encoding">encodings</a> for more information about the different
755      * types of supported audio encoding.
756      * @return one of the values that can be set in {@link Builder#setEncoding(int)} or
757      * {@link AudioFormat#ENCODING_INVALID} if not set.
758      */
getEncoding()759     public int getEncoding() {
760         return mEncoding;
761     }
762 
763     /**
764      * Return the sample rate.
765      * @return one of the values that can be set in {@link Builder#setSampleRate(int)} or
766      * {@link #SAMPLE_RATE_UNSPECIFIED} if not set.
767      */
getSampleRate()768     public int getSampleRate() {
769         return mSampleRate;
770     }
771 
772     /**
773      * Return the channel mask.
774      * See the section on <a href="#channelMask">channel masks</a> for more information about
775      * the difference between index-based masks(as returned by {@link #getChannelIndexMask()}) and
776      * the position-based mask returned by this function.
777      * @return one of the values that can be set in {@link Builder#setChannelMask(int)} or
778      * {@link AudioFormat#CHANNEL_INVALID} if not set.
779      */
getChannelMask()780     public int getChannelMask() {
781         return mChannelMask;
782     }
783 
784     /**
785      * Return the channel index mask.
786      * See the section on <a href="#channelMask">channel masks</a> for more information about
787      * the difference between index-based masks, and position-based masks (as returned
788      * by {@link #getChannelMask()}).
789      * @return one of the values that can be set in {@link Builder#setChannelIndexMask(int)} or
790      * {@link AudioFormat#CHANNEL_INVALID} if not set or an invalid mask was used.
791      */
getChannelIndexMask()792     public int getChannelIndexMask() {
793         return mChannelIndexMask;
794     }
795 
796     /**
797      * Return the channel count.
798      * @return the channel count derived from the channel position mask or the channel index mask.
799      * Zero is returned if both the channel position mask and the channel index mask are not set.
800      */
getChannelCount()801     public int getChannelCount() {
802         return mChannelCount;
803     }
804 
805     /**
806      * Return the frame size in bytes.
807      *
808      * For PCM or PCM packed compressed data this is the size of a sample multiplied
809      * by the channel count. For all other cases, including invalid/unset channel masks,
810      * this will return 1 byte.
811      * As an example, a stereo 16-bit PCM format would have a frame size of 4 bytes,
812      * an 8 channel float PCM format would have a frame size of 32 bytes,
813      * and a compressed data format (not packed in PCM) would have a frame size of 1 byte.
814      *
815      * Both {@link AudioRecord} or {@link AudioTrack} process data in multiples of
816      * this frame size.
817      *
818      * @return The audio frame size in bytes corresponding to the encoding and the channel mask.
819      */
getFrameSizeInBytes()820     public @IntRange(from = 1) int getFrameSizeInBytes() {
821         return mFrameSizeInBytes;
822     }
823 
824     /** @hide */
getPropertySetMask()825     public int getPropertySetMask() {
826         return mPropertySetMask;
827     }
828 
829     /** @hide */
toLogFriendlyString()830     public String toLogFriendlyString() {
831         return String.format("%dch %dHz %s",
832                 mChannelCount, mSampleRate, toLogFriendlyEncoding(mEncoding));
833     }
834 
835     /**
836      * Builder class for {@link AudioFormat} objects.
837      * Use this class to configure and create an AudioFormat instance. By setting format
838      * characteristics such as audio encoding, channel mask or sample rate, you indicate which
839      * of those are to vary from the default behavior on this device wherever this audio format
840      * is used. See {@link AudioFormat} for a complete description of the different parameters that
841      * can be used to configure an <code>AudioFormat</code> instance.
842      * <p>{@link AudioFormat} is for instance used in
843      * {@link AudioTrack#AudioTrack(AudioAttributes, AudioFormat, int, int, int)}. In this
844      * constructor, every format characteristic set on the <code>Builder</code> (e.g. with
845      * {@link #setSampleRate(int)}) will alter the default values used by an
846      * <code>AudioTrack</code>. In this case for audio playback with <code>AudioTrack</code>, the
847      * sample rate set in the <code>Builder</code> would override the platform output sample rate
848      * which would otherwise be selected by default.
849      */
850     public static class Builder {
851         private int mEncoding = ENCODING_INVALID;
852         private int mSampleRate = SAMPLE_RATE_UNSPECIFIED;
853         private int mChannelMask = CHANNEL_INVALID;
854         private int mChannelIndexMask = 0;
855         private int mPropertySetMask = AUDIO_FORMAT_HAS_PROPERTY_NONE;
856 
857         /**
858          * Constructs a new Builder with none of the format characteristics set.
859          */
Builder()860         public Builder() {
861         }
862 
863         /**
864          * Constructs a new Builder from a given {@link AudioFormat}.
865          * @param af the {@link AudioFormat} object whose data will be reused in the new Builder.
866          */
Builder(AudioFormat af)867         public Builder(AudioFormat af) {
868             mEncoding = af.mEncoding;
869             mSampleRate = af.mSampleRate;
870             mChannelMask = af.mChannelMask;
871             mChannelIndexMask = af.mChannelIndexMask;
872             mPropertySetMask = af.mPropertySetMask;
873         }
874 
875         /**
876          * Combines all of the format characteristics that have been set and return a new
877          * {@link AudioFormat} object.
878          * @return a new {@link AudioFormat} object
879          */
build()880         public AudioFormat build() {
881             AudioFormat af = new AudioFormat(
882                     mPropertySetMask,
883                     mEncoding,
884                     mSampleRate,
885                     mChannelMask,
886                     mChannelIndexMask
887                     );
888             return af;
889         }
890 
891         /**
892          * Sets the data encoding format.
893          * @param encoding the specified encoding or default.
894          * @return the same Builder instance.
895          * @throws java.lang.IllegalArgumentException
896          */
setEncoding(@ncoding int encoding)897         public Builder setEncoding(@Encoding int encoding) throws IllegalArgumentException {
898             switch (encoding) {
899                 case ENCODING_DEFAULT:
900                     mEncoding = ENCODING_PCM_16BIT;
901                     break;
902                 case ENCODING_PCM_16BIT:
903                 case ENCODING_PCM_8BIT:
904                 case ENCODING_PCM_FLOAT:
905                 case ENCODING_AC3:
906                 case ENCODING_E_AC3:
907                 case ENCODING_DTS:
908                 case ENCODING_DTS_HD:
909                 case ENCODING_MP3:
910                 case ENCODING_AAC_LC:
911                 case ENCODING_AAC_HE_V1:
912                 case ENCODING_AAC_HE_V2:
913                 case ENCODING_IEC61937:
914                 case ENCODING_DOLBY_TRUEHD:
915                 case ENCODING_AAC_ELD:
916                 case ENCODING_AAC_XHE:
917                 case ENCODING_AC4:
918                 case ENCODING_E_AC3_JOC:
919                 case ENCODING_DOLBY_MAT:
920                     mEncoding = encoding;
921                     break;
922                 case ENCODING_INVALID:
923                 default:
924                     throw new IllegalArgumentException("Invalid encoding " + encoding);
925             }
926             mPropertySetMask |= AUDIO_FORMAT_HAS_PROPERTY_ENCODING;
927             return this;
928         }
929 
930         /**
931          * Sets the channel position mask.
932          * The channel position mask specifies the association between audio samples in a frame
933          * with named endpoint channels. The samples in the frame correspond to the
934          * named set bits in the channel position mask, in ascending bit order.
935          * See {@link #setChannelIndexMask(int)} to specify channels
936          * based on endpoint numbered channels. This <a href="#channelPositionMask>description of
937          * channel position masks</a> covers the concept in more details.
938          * @param channelMask describes the configuration of the audio channels.
939          *    <p> For output, the channelMask can be an OR-ed combination of
940          *    channel position masks, e.g.
941          *    {@link AudioFormat#CHANNEL_OUT_FRONT_LEFT},
942          *    {@link AudioFormat#CHANNEL_OUT_FRONT_RIGHT},
943          *    {@link AudioFormat#CHANNEL_OUT_FRONT_CENTER},
944          *    {@link AudioFormat#CHANNEL_OUT_LOW_FREQUENCY}
945          *    {@link AudioFormat#CHANNEL_OUT_BACK_LEFT},
946          *    {@link AudioFormat#CHANNEL_OUT_BACK_RIGHT},
947          *    {@link AudioFormat#CHANNEL_OUT_BACK_CENTER},
948          *    {@link AudioFormat#CHANNEL_OUT_SIDE_LEFT},
949          *    {@link AudioFormat#CHANNEL_OUT_SIDE_RIGHT}.
950          *    <p> For a valid {@link AudioTrack} channel position mask,
951          *    the following conditions apply:
952          *    <br> (1) at most eight channel positions may be used;
953          *    <br> (2) right/left pairs should be matched.
954          *    <p> For input or {@link AudioRecord}, the mask should be
955          *    {@link AudioFormat#CHANNEL_IN_MONO} or
956          *    {@link AudioFormat#CHANNEL_IN_STEREO}.  {@link AudioFormat#CHANNEL_IN_MONO} is
957          *    guaranteed to work on all devices.
958          * @return the same <code>Builder</code> instance.
959          * @throws IllegalArgumentException if the channel mask is invalid or
960          *    if both channel index mask and channel position mask
961          *    are specified but do not have the same channel count.
962          */
setChannelMask(int channelMask)963         public @NonNull Builder setChannelMask(int channelMask) {
964             if (channelMask == CHANNEL_INVALID) {
965                 throw new IllegalArgumentException("Invalid zero channel mask");
966             } else if (/* channelMask != 0 && */ mChannelIndexMask != 0 &&
967                     Integer.bitCount(channelMask) != Integer.bitCount(mChannelIndexMask)) {
968                 throw new IllegalArgumentException("Mismatched channel count for mask " +
969                         Integer.toHexString(channelMask).toUpperCase());
970             }
971             mChannelMask = channelMask;
972             mPropertySetMask |= AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK;
973             return this;
974         }
975 
976         /**
977          * Sets the channel index mask.
978          * A channel index mask specifies the association of audio samples in the frame
979          * with numbered endpoint channels. The i-th bit in the channel index
980          * mask corresponds to the i-th endpoint channel.
981          * For example, an endpoint with four channels is represented
982          * as index mask bits 0 through 3. This <a href="#channelIndexMask>description of channel
983          * index masks</a> covers the concept in more details.
984          * See {@link #setChannelMask(int)} for a positional mask interpretation.
985          * <p> Both {@link AudioTrack} and {@link AudioRecord} support
986          * a channel index mask.
987          * If a channel index mask is specified it is used,
988          * otherwise the channel position mask specified
989          * by <code>setChannelMask</code> is used.
990          * For <code>AudioTrack</code> and <code>AudioRecord</code>,
991          * a channel position mask is not required if a channel index mask is specified.
992          *
993          * @param channelIndexMask describes the configuration of the audio channels.
994          *    <p> For output, the <code>channelIndexMask</code> is an OR-ed combination of
995          *    bits representing the mapping of <code>AudioTrack</code> write samples
996          *    to output sink channels.
997          *    For example, a mask of <code>0xa</code>, or binary <code>1010</code>,
998          *    means the <code>AudioTrack</code> write frame consists of two samples,
999          *    which are routed to the second and the fourth channels of the output sink.
1000          *    Unmatched output sink channels are zero filled and unmatched
1001          *    <code>AudioTrack</code> write samples are dropped.
1002          *    <p> For input, the <code>channelIndexMask</code> is an OR-ed combination of
1003          *    bits representing the mapping of input source channels to
1004          *    <code>AudioRecord</code> read samples.
1005          *    For example, a mask of <code>0x5</code>, or binary
1006          *    <code>101</code>, will read from the first and third channel of the input
1007          *    source device and store them in the first and second sample of the
1008          *    <code>AudioRecord</code> read frame.
1009          *    Unmatched input source channels are dropped and
1010          *    unmatched <code>AudioRecord</code> read samples are zero filled.
1011          * @return the same <code>Builder</code> instance.
1012          * @throws IllegalArgumentException if the channel index mask is invalid or
1013          *    if both channel index mask and channel position mask
1014          *    are specified but do not have the same channel count.
1015          */
setChannelIndexMask(int channelIndexMask)1016         public @NonNull Builder setChannelIndexMask(int channelIndexMask) {
1017             if (channelIndexMask == 0) {
1018                 throw new IllegalArgumentException("Invalid zero channel index mask");
1019             } else if (/* channelIndexMask != 0 && */ mChannelMask != 0 &&
1020                     Integer.bitCount(channelIndexMask) != Integer.bitCount(mChannelMask)) {
1021                 throw new IllegalArgumentException("Mismatched channel count for index mask " +
1022                         Integer.toHexString(channelIndexMask).toUpperCase());
1023             }
1024             mChannelIndexMask = channelIndexMask;
1025             mPropertySetMask |= AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK;
1026             return this;
1027         }
1028 
1029         /**
1030          * Sets the sample rate.
1031          * @param sampleRate the sample rate expressed in Hz
1032          * @return the same Builder instance.
1033          * @throws java.lang.IllegalArgumentException
1034          */
setSampleRate(int sampleRate)1035         public Builder setSampleRate(int sampleRate) throws IllegalArgumentException {
1036             // TODO Consider whether to keep the MIN and MAX range checks here.
1037             // It is not necessary and poses the problem of defining the limits independently from
1038             // native implementation or platform capabilities.
1039             if (((sampleRate < SAMPLE_RATE_HZ_MIN) || (sampleRate > SAMPLE_RATE_HZ_MAX)) &&
1040                     sampleRate != SAMPLE_RATE_UNSPECIFIED) {
1041                 throw new IllegalArgumentException("Invalid sample rate " + sampleRate);
1042             }
1043             mSampleRate = sampleRate;
1044             mPropertySetMask |= AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE;
1045             return this;
1046         }
1047     }
1048 
1049     @Override
equals(Object o)1050     public boolean equals(Object o) {
1051         if (this == o) return true;
1052         if (o == null || getClass() != o.getClass()) return false;
1053 
1054         AudioFormat that = (AudioFormat) o;
1055 
1056         if (mPropertySetMask != that.mPropertySetMask) return false;
1057 
1058         // return false if any of the properties is set and the values differ
1059         return !((((mPropertySetMask & AUDIO_FORMAT_HAS_PROPERTY_ENCODING) != 0)
1060                             && (mEncoding != that.mEncoding))
1061                     || (((mPropertySetMask & AUDIO_FORMAT_HAS_PROPERTY_SAMPLE_RATE) != 0)
1062                             && (mSampleRate != that.mSampleRate))
1063                     || (((mPropertySetMask & AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_MASK) != 0)
1064                             && (mChannelMask != that.mChannelMask))
1065                     || (((mPropertySetMask & AUDIO_FORMAT_HAS_PROPERTY_CHANNEL_INDEX_MASK) != 0)
1066                             && (mChannelIndexMask != that.mChannelIndexMask)));
1067     }
1068 
1069     @Override
hashCode()1070     public int hashCode() {
1071         return Objects.hash(mPropertySetMask, mSampleRate, mEncoding, mChannelMask,
1072                 mChannelIndexMask);
1073     }
1074 
1075     @Override
describeContents()1076     public int describeContents() {
1077         return 0;
1078     }
1079 
1080     @Override
writeToParcel(Parcel dest, int flags)1081     public void writeToParcel(Parcel dest, int flags) {
1082         dest.writeInt(mPropertySetMask);
1083         dest.writeInt(mEncoding);
1084         dest.writeInt(mSampleRate);
1085         dest.writeInt(mChannelMask);
1086         dest.writeInt(mChannelIndexMask);
1087     }
1088 
AudioFormat(Parcel in)1089     private AudioFormat(Parcel in) {
1090         this(
1091              in.readInt(), // propertySetMask
1092              in.readInt(), // encoding
1093              in.readInt(), // sampleRate
1094              in.readInt(), // channelMask
1095              in.readInt()  // channelIndexMask
1096             );
1097     }
1098 
1099     public static final @android.annotation.NonNull Parcelable.Creator<AudioFormat> CREATOR =
1100             new Parcelable.Creator<AudioFormat>() {
1101         public AudioFormat createFromParcel(Parcel p) {
1102             return new AudioFormat(p);
1103         }
1104         public AudioFormat[] newArray(int size) {
1105             return new AudioFormat[size];
1106         }
1107     };
1108 
1109     @Override
toString()1110     public String toString () {
1111         return new String("AudioFormat:"
1112                 + " props=" + mPropertySetMask
1113                 + " enc=" + mEncoding
1114                 + " chan=0x" + Integer.toHexString(mChannelMask).toUpperCase()
1115                 + " chan_index=0x" + Integer.toHexString(mChannelIndexMask).toUpperCase()
1116                 + " rate=" + mSampleRate);
1117     }
1118 
1119     /** @hide */
1120     @IntDef(flag = false, prefix = "ENCODING", value = {
1121         ENCODING_DEFAULT,
1122         ENCODING_PCM_16BIT,
1123         ENCODING_PCM_8BIT,
1124         ENCODING_PCM_FLOAT,
1125         ENCODING_AC3,
1126         ENCODING_E_AC3,
1127         ENCODING_DTS,
1128         ENCODING_DTS_HD,
1129         ENCODING_MP3,
1130         ENCODING_AAC_LC,
1131         ENCODING_AAC_HE_V1,
1132         ENCODING_AAC_HE_V2,
1133         ENCODING_IEC61937,
1134         ENCODING_DOLBY_TRUEHD,
1135         ENCODING_AAC_ELD,
1136         ENCODING_AAC_XHE,
1137         ENCODING_AC4,
1138         ENCODING_E_AC3_JOC,
1139         ENCODING_DOLBY_MAT }
1140     )
1141     @Retention(RetentionPolicy.SOURCE)
1142     public @interface Encoding {}
1143 
1144     /** @hide */
1145     public static final int[] SURROUND_SOUND_ENCODING = {
1146             ENCODING_AC3,
1147             ENCODING_E_AC3,
1148             ENCODING_DTS,
1149             ENCODING_DTS_HD,
1150             ENCODING_AAC_LC,
1151             ENCODING_DOLBY_TRUEHD,
1152             ENCODING_AC4,
1153             ENCODING_E_AC3_JOC,
1154             ENCODING_DOLBY_MAT,
1155     };
1156 
1157     /** @hide */
1158     @IntDef(flag = false, prefix = "ENCODING", value = {
1159             ENCODING_AC3,
1160             ENCODING_E_AC3,
1161             ENCODING_DTS,
1162             ENCODING_DTS_HD,
1163             ENCODING_AAC_LC,
1164             ENCODING_DOLBY_TRUEHD,
1165             ENCODING_AC4,
1166             ENCODING_E_AC3_JOC,
1167             ENCODING_DOLBY_MAT }
1168     )
1169     @Retention(RetentionPolicy.SOURCE)
1170     public @interface SurroundSoundEncoding {}
1171 
1172     /**
1173      * @hide
1174      *
1175      * Return default name for a surround format. This is not an International name.
1176      * It is just a default to use if an international name is not available.
1177      *
1178      * @param audioFormat a surround format
1179      * @return short default name for the format.
1180      */
toDisplayName(@urroundSoundEncoding int audioFormat)1181     public static String toDisplayName(@SurroundSoundEncoding int audioFormat) {
1182         switch (audioFormat) {
1183             case ENCODING_AC3:
1184                 return "Dolby Digital";
1185             case ENCODING_E_AC3:
1186                 return "Dolby Digital Plus";
1187             case ENCODING_DTS:
1188                 return "DTS";
1189             case ENCODING_DTS_HD:
1190                 return "DTS HD";
1191             case ENCODING_AAC_LC:
1192                 return "AAC";
1193             case ENCODING_DOLBY_TRUEHD:
1194                 return "Dolby TrueHD";
1195             case ENCODING_AC4:
1196                 return "Dolby AC-4";
1197             case ENCODING_E_AC3_JOC:
1198                 return "Dolby Atmos in Dolby Digital Plus";
1199             case ENCODING_DOLBY_MAT:
1200                 return "Dolby MAT";
1201             default:
1202                 return "Unknown surround sound format";
1203         }
1204     }
1205 
1206 }
1207