• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2006 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.NonNull;
21 import android.annotation.Nullable;
22 import android.annotation.RequiresPermission;
23 import android.annotation.TestApi;
24 import android.bluetooth.BluetoothCodecConfig;
25 import android.bluetooth.BluetoothLeAudioCodecConfig;
26 import android.compat.annotation.UnsupportedAppUsage;
27 import android.content.Context;
28 import android.content.pm.PackageManager;
29 import android.media.audio.common.AidlConversion;
30 import android.media.audiofx.AudioEffect;
31 import android.media.audiopolicy.AudioMix;
32 import android.media.audiopolicy.AudioProductStrategy;
33 import android.os.Build;
34 import android.os.IBinder;
35 import android.os.Parcel;
36 import android.os.Vibrator;
37 import android.telephony.TelephonyManager;
38 import android.util.Log;
39 import android.util.Pair;
40 
41 import com.android.internal.annotations.GuardedBy;
42 
43 import java.lang.annotation.Retention;
44 import java.lang.annotation.RetentionPolicy;
45 import java.util.ArrayList;
46 import java.util.HashSet;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Objects;
50 import java.util.Set;
51 import java.util.TreeSet;
52 
53 /* IF YOU CHANGE ANY OF THE CONSTANTS IN THIS FILE, DO NOT FORGET
54  * TO UPDATE THE CORRESPONDING NATIVE GLUE AND AudioManager.java.
55  * THANK YOU FOR YOUR COOPERATION.
56  */
57 
58 /**
59  * @hide
60  */
61 @TestApi
62 public class AudioSystem
63 {
64     private static final boolean DEBUG_VOLUME = false;
65 
66     private static final String TAG = "AudioSystem";
67 
68     // private constructor to prevent instantiating AudioSystem
AudioSystem()69     private AudioSystem() {
70         throw new UnsupportedOperationException("Trying to instantiate AudioSystem");
71     }
72 
73     /* These values must be kept in sync with system/media/audio/include/system/audio-hal-enums.h */
74     /*
75      * If these are modified, please also update Settings.System.VOLUME_SETTINGS
76      * and attrs.xml and AudioManager.java.
77      */
78     /** @hide Used to identify the default audio stream volume */
79     @TestApi
80     public static final int STREAM_DEFAULT = -1;
81     /** @hide Used to identify the volume of audio streams for phone calls */
82     public static final int STREAM_VOICE_CALL = 0;
83     /** @hide Used to identify the volume of audio streams for system sounds */
84     public static final int STREAM_SYSTEM = 1;
85     /** @hide Used to identify the volume of audio streams for the phone ring and message alerts */
86     public static final int STREAM_RING = 2;
87     /** @hide Used to identify the volume of audio streams for music playback */
88     public static final int STREAM_MUSIC = 3;
89     /** @hide Used to identify the volume of audio streams for alarms */
90     public static final int STREAM_ALARM = 4;
91     /** @hide Used to identify the volume of audio streams for notifications */
92     public static final int STREAM_NOTIFICATION = 5;
93     /** @hide
94      *  Used to identify the volume of audio streams for phone calls when connected on bluetooth */
95     public static final int STREAM_BLUETOOTH_SCO = 6;
96     /** @hide Used to identify the volume of audio streams for enforced system sounds in certain
97      * countries (e.g camera in Japan) */
98     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
99     public static final int STREAM_SYSTEM_ENFORCED = 7;
100     /** @hide Used to identify the volume of audio streams for DTMF tones */
101     public static final int STREAM_DTMF = 8;
102     /** @hide Used to identify the volume of audio streams exclusively transmitted through the
103      *  speaker (TTS) of the device */
104     public static final int STREAM_TTS = 9;
105     /** @hide Used to identify the volume of audio streams for accessibility prompts */
106     public static final int STREAM_ACCESSIBILITY = 10;
107     /** @hide Used to identify the volume of audio streams for virtual assistant */
108     public static final int STREAM_ASSISTANT = 11;
109     /**
110      * @hide
111      * @deprecated Use {@link #numStreamTypes() instead}
112      */
113     public static final int NUM_STREAMS = 5;
114 
115     /*
116      * Framework static final constants that are primitives or Strings
117      * accessed by CTS tests or internal applications must be set from methods
118      * (or in a static block) to prevent Java compile-time replacement.
119      * We set them from methods so they are read from the device framework.
120      * Do not un-hide or change to a numeric literal.
121      */
122 
123     /** Maximum value for AudioTrack channel count
124      * @hide
125      */
126     public static final int OUT_CHANNEL_COUNT_MAX = native_getMaxChannelCount();
native_getMaxChannelCount()127     private static native int native_getMaxChannelCount();
128 
129     /** Maximum value for sample rate, used by AudioFormat.
130      * @hide
131      */
132     public static final int SAMPLE_RATE_HZ_MAX = native_getMaxSampleRate();
native_getMaxSampleRate()133     private static native int native_getMaxSampleRate();
134 
135     /** Minimum value for sample rate, used by AudioFormat.
136      * @hide
137      */
138     public static final int SAMPLE_RATE_HZ_MIN = native_getMinSampleRate();
native_getMinSampleRate()139     private static native int native_getMinSampleRate();
140 
141     /** @hide */
142     public static final int FCC_24 = 24; // fixed channel count 24; do not change.
143 
144     // Expose only the getter method publicly so we can change it in the future
145     private static final int NUM_STREAM_TYPES = 12;
146 
147     /**
148      * @hide
149      * @return total number of stream types
150      */
151     @UnsupportedAppUsage
152     @TestApi
getNumStreamTypes()153     public static final int getNumStreamTypes() { return NUM_STREAM_TYPES; }
154 
155     /** @hide */
156     public static final String[] STREAM_NAMES = new String[] {
157         "STREAM_VOICE_CALL",
158         "STREAM_SYSTEM",
159         "STREAM_RING",
160         "STREAM_MUSIC",
161         "STREAM_ALARM",
162         "STREAM_NOTIFICATION",
163         "STREAM_BLUETOOTH_SCO",
164         "STREAM_SYSTEM_ENFORCED",
165         "STREAM_DTMF",
166         "STREAM_TTS",
167         "STREAM_ACCESSIBILITY",
168         "STREAM_ASSISTANT"
169     };
170 
171     /**
172      * @hide
173      * Sets the microphone mute on or off.
174      *
175      * @param on set <var>true</var> to mute the microphone;
176      *           <var>false</var> to turn mute off
177      * @return command completion status see AUDIO_STATUS_OK, see AUDIO_STATUS_ERROR
178      */
179     @UnsupportedAppUsage
muteMicrophone(boolean on)180     public static native int muteMicrophone(boolean on);
181 
182     /**
183      * @hide
184      * Checks whether the microphone mute is on or off.
185      *
186      * @return true if microphone is muted, false if it's not
187      */
188     @UnsupportedAppUsage
isMicrophoneMuted()189     public static native boolean isMicrophoneMuted();
190 
191     /* modes for setPhoneState, must match AudioSystem.h audio_mode */
192     /** @hide */
193     public static final int MODE_INVALID            = -2;
194     /** @hide */
195     public static final int MODE_CURRENT            = -1;
196     /** @hide */
197     public static final int MODE_NORMAL             = 0;
198     /** @hide */
199     public static final int MODE_RINGTONE           = 1;
200     /** @hide */
201     public static final int MODE_IN_CALL            = 2;
202     /** @hide */
203     public static final int MODE_IN_COMMUNICATION   = 3;
204     /** @hide */
205     public static final int MODE_CALL_SCREENING     = 4;
206     /** @hide */
207     public static final int MODE_CALL_REDIRECT     = 5;
208     /** @hide */
209     public static final int MODE_COMMUNICATION_REDIRECT  = 6;
210     /** @hide */
211     public static final int NUM_MODES               = 7;
212 
213     /** @hide */
modeToString(int mode)214     public static String modeToString(int mode) {
215         switch (mode) {
216             case MODE_CURRENT: return "MODE_CURRENT";
217             case MODE_IN_CALL: return "MODE_IN_CALL";
218             case MODE_IN_COMMUNICATION: return "MODE_IN_COMMUNICATION";
219             case MODE_INVALID: return "MODE_INVALID";
220             case MODE_NORMAL: return "MODE_NORMAL";
221             case MODE_RINGTONE: return "MODE_RINGTONE";
222             case MODE_CALL_SCREENING: return "MODE_CALL_SCREENING";
223             case MODE_CALL_REDIRECT: return "MODE_CALL_REDIRECT";
224             case MODE_COMMUNICATION_REDIRECT: return "MODE_COMMUNICATION_REDIRECT";
225             default: return "unknown mode (" + mode + ")";
226         }
227     }
228 
229     /* Formats for A2DP codecs, must match system/audio-base.h audio_format_t */
230     /** @hide */
231     public static final int AUDIO_FORMAT_INVALID        = 0xFFFFFFFF;
232     /** @hide */
233     public static final int AUDIO_FORMAT_DEFAULT        = 0;
234     /** @hide */
235     public static final int AUDIO_FORMAT_AAC            = 0x04000000;
236     /** @hide */
237     public static final int AUDIO_FORMAT_SBC            = 0x1F000000;
238     /** @hide */
239     public static final int AUDIO_FORMAT_APTX           = 0x20000000;
240     /** @hide */
241     public static final int AUDIO_FORMAT_APTX_HD        = 0x21000000;
242     /** @hide */
243     public static final int AUDIO_FORMAT_LDAC           = 0x23000000;
244     /** @hide */
245     public static final int AUDIO_FORMAT_LC3            = 0x2B000000;
246     /** @hide */
247     public static final int AUDIO_FORMAT_OPUS           = 0x08000000;
248 
249 
250     /** @hide */
251     @IntDef(flag = false, prefix = "AUDIO_FORMAT_", value = {
252             AUDIO_FORMAT_INVALID,
253             AUDIO_FORMAT_DEFAULT,
254             AUDIO_FORMAT_AAC,
255             AUDIO_FORMAT_SBC,
256             AUDIO_FORMAT_APTX,
257             AUDIO_FORMAT_APTX_HD,
258             AUDIO_FORMAT_LDAC,
259             AUDIO_FORMAT_LC3,
260             AUDIO_FORMAT_OPUS
261            }
262     )
263     @Retention(RetentionPolicy.SOURCE)
264     public @interface AudioFormatNativeEnumForBtCodec {}
265 
266     /** @hide */
267     @IntDef(flag = false, prefix = "AUDIO_FORMAT_", value = {
268         AUDIO_FORMAT_LC3}
269     )
270     @Retention(RetentionPolicy.SOURCE)
271     public @interface AudioFormatNativeEnumForBtLeAudioCodec {}
272 
273     /** @hide */
274     @IntDef(flag = false, prefix = "DEVICE_", value = {
275             DEVICE_OUT_BLUETOOTH_A2DP,
276             DEVICE_OUT_BLE_HEADSET,
277             DEVICE_OUT_BLE_BROADCAST}
278     )
279     @Retention(RetentionPolicy.SOURCE)
280     public @interface BtOffloadDeviceType {}
281 
282     /**
283      * @hide
284      * Convert audio format enum values to Bluetooth codec values
285      */
audioFormatToBluetoothSourceCodec( @udioFormatNativeEnumForBtCodec int audioFormat)286     public static int audioFormatToBluetoothSourceCodec(
287             @AudioFormatNativeEnumForBtCodec int audioFormat) {
288         switch (audioFormat) {
289             case AUDIO_FORMAT_AAC: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC;
290             case AUDIO_FORMAT_SBC: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC;
291             case AUDIO_FORMAT_APTX: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX;
292             case AUDIO_FORMAT_APTX_HD: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD;
293             case AUDIO_FORMAT_LDAC: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC;
294             case AUDIO_FORMAT_LC3: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_LC3;
295             case AUDIO_FORMAT_OPUS: return BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS;
296             default:
297                 Log.e(TAG, "Unknown audio format 0x" + Integer.toHexString(audioFormat)
298                         + " for conversion to BT codec");
299                 return BluetoothCodecConfig.SOURCE_CODEC_TYPE_INVALID;
300         }
301     }
302 
303     /**
304      * @hide
305      * Convert audio format enum values to Bluetooth LE audio codec values
306      */
audioFormatToBluetoothLeAudioSourceCodec( @udioFormatNativeEnumForBtLeAudioCodec int audioFormat)307     public static int audioFormatToBluetoothLeAudioSourceCodec(
308             @AudioFormatNativeEnumForBtLeAudioCodec int audioFormat) {
309         switch (audioFormat) {
310             case AUDIO_FORMAT_LC3: return BluetoothLeAudioCodecConfig.SOURCE_CODEC_TYPE_LC3;
311             default:
312                 Log.e(TAG, "Unknown audio format 0x" + Integer.toHexString(audioFormat)
313                         + " for conversion to BT LE audio codec");
314                 return BluetoothLeAudioCodecConfig.SOURCE_CODEC_TYPE_INVALID;
315         }
316     }
317 
318     /**
319      * @hide
320      * Convert a Bluetooth codec to an audio format enum
321      * @param btCodec the codec to convert.
322      * @return the audio format, or {@link #AUDIO_FORMAT_DEFAULT} if unknown
323      */
bluetoothCodecToAudioFormat(int btCodec)324     public static @AudioFormatNativeEnumForBtCodec int bluetoothCodecToAudioFormat(int btCodec) {
325         switch (btCodec) {
326             case BluetoothCodecConfig.SOURCE_CODEC_TYPE_SBC:
327                 return AudioSystem.AUDIO_FORMAT_SBC;
328             case BluetoothCodecConfig.SOURCE_CODEC_TYPE_AAC:
329                 return AudioSystem.AUDIO_FORMAT_AAC;
330             case BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX:
331                 return AudioSystem.AUDIO_FORMAT_APTX;
332             case BluetoothCodecConfig.SOURCE_CODEC_TYPE_APTX_HD:
333                 return AudioSystem.AUDIO_FORMAT_APTX_HD;
334             case BluetoothCodecConfig.SOURCE_CODEC_TYPE_LDAC:
335                 return AudioSystem.AUDIO_FORMAT_LDAC;
336             case BluetoothCodecConfig.SOURCE_CODEC_TYPE_LC3:
337                 return AudioSystem.AUDIO_FORMAT_LC3;
338             case BluetoothCodecConfig.SOURCE_CODEC_TYPE_OPUS:
339                 return AudioSystem.AUDIO_FORMAT_OPUS;
340             default:
341                 Log.e(TAG, "Unknown BT codec 0x" + Integer.toHexString(btCodec)
342                         + " for conversion to audio format");
343                 // TODO returning DEFAULT is the current behavior, should this return INVALID?
344                 return AudioSystem.AUDIO_FORMAT_DEFAULT;
345         }
346     }
347 
348     /**
349      * @hide
350      * Convert a native audio format integer constant to a string.
351      */
audioFormatToString(int audioFormat)352     public static String audioFormatToString(int audioFormat) {
353         switch (audioFormat) {
354             case /* AUDIO_FORMAT_INVALID         */ 0xFFFFFFFF:
355                 return "AUDIO_FORMAT_INVALID";
356             case /* AUDIO_FORMAT_DEFAULT         */ 0:
357                 return "AUDIO_FORMAT_DEFAULT";
358             case /* AUDIO_FORMAT_MP3             */ 0x01000000:
359                 return "AUDIO_FORMAT_MP3";
360             case /* AUDIO_FORMAT_AMR_NB          */ 0x02000000:
361                 return "AUDIO_FORMAT_AMR_NB";
362             case /* AUDIO_FORMAT_AMR_WB          */ 0x03000000:
363                 return "AUDIO_FORMAT_AMR_WB";
364             case /* AUDIO_FORMAT_AAC             */ 0x04000000:
365                 return "AUDIO_FORMAT_AAC";
366             case /* AUDIO_FORMAT_HE_AAC_V1       */ 0x05000000:
367                 return "AUDIO_FORMAT_HE_AAC_V1";
368             case /* AUDIO_FORMAT_HE_AAC_V2       */ 0x06000000:
369                 return "AUDIO_FORMAT_HE_AAC_V2";
370             case /* AUDIO_FORMAT_VORBIS          */ 0x07000000:
371                 return "AUDIO_FORMAT_VORBIS";
372             case /* AUDIO_FORMAT_OPUS            */ 0x08000000:
373                 return "AUDIO_FORMAT_OPUS";
374             case /* AUDIO_FORMAT_AC3             */ 0x09000000:
375                 return "AUDIO_FORMAT_AC3";
376             case /* AUDIO_FORMAT_E_AC3           */ 0x0A000000:
377                 return "AUDIO_FORMAT_E_AC3";
378             case /* AUDIO_FORMAT_DTS             */ 0x0B000000:
379                 return "AUDIO_FORMAT_DTS";
380             case /* AUDIO_FORMAT_DTS_HD          */ 0x0C000000:
381                 return "AUDIO_FORMAT_DTS_HD";
382             case /* AUDIO_FORMAT_IEC61937        */ 0x0D000000:
383                 return "AUDIO_FORMAT_IEC61937";
384             case /* AUDIO_FORMAT_DOLBY_TRUEHD    */ 0x0E000000:
385                 return "AUDIO_FORMAT_DOLBY_TRUEHD";
386             case /* AUDIO_FORMAT_EVRC            */ 0x10000000:
387                 return "AUDIO_FORMAT_EVRC";
388             case /* AUDIO_FORMAT_EVRCB           */ 0x11000000:
389                 return "AUDIO_FORMAT_EVRCB";
390             case /* AUDIO_FORMAT_EVRCWB          */ 0x12000000:
391                 return "AUDIO_FORMAT_EVRCWB";
392             case /* AUDIO_FORMAT_EVRCNW          */ 0x13000000:
393                 return "AUDIO_FORMAT_EVRCNW";
394             case /* AUDIO_FORMAT_AAC_ADIF        */ 0x14000000:
395                 return "AUDIO_FORMAT_AAC_ADIF";
396             case /* AUDIO_FORMAT_WMA             */ 0x15000000:
397                 return "AUDIO_FORMAT_WMA";
398             case /* AUDIO_FORMAT_WMA_PRO         */ 0x16000000:
399                 return "AUDIO_FORMAT_WMA_PRO";
400             case /* AUDIO_FORMAT_AMR_WB_PLUS     */ 0x17000000:
401                 return "AUDIO_FORMAT_AMR_WB_PLUS";
402             case /* AUDIO_FORMAT_MP2             */ 0x18000000:
403                 return "AUDIO_FORMAT_MP2";
404             case /* AUDIO_FORMAT_QCELP           */ 0x19000000:
405                 return "AUDIO_FORMAT_QCELP";
406             case /* AUDIO_FORMAT_DSD             */ 0x1A000000:
407                 return "AUDIO_FORMAT_DSD";
408             case /* AUDIO_FORMAT_FLAC            */ 0x1B000000:
409                 return "AUDIO_FORMAT_FLAC";
410             case /* AUDIO_FORMAT_ALAC            */ 0x1C000000:
411                 return "AUDIO_FORMAT_ALAC";
412             case /* AUDIO_FORMAT_APE             */ 0x1D000000:
413                 return "AUDIO_FORMAT_APE";
414             case /* AUDIO_FORMAT_AAC_ADTS        */ 0x1E000000:
415                 return "AUDIO_FORMAT_AAC_ADTS";
416             case /* AUDIO_FORMAT_SBC             */ 0x1F000000:
417                 return "AUDIO_FORMAT_SBC";
418             case /* AUDIO_FORMAT_APTX            */ 0x20000000:
419                 return "AUDIO_FORMAT_APTX";
420             case /* AUDIO_FORMAT_APTX_HD         */ 0x21000000:
421                 return "AUDIO_FORMAT_APTX_HD";
422             case /* AUDIO_FORMAT_AC4             */ 0x22000000:
423                 return "AUDIO_FORMAT_AC4";
424             case /* AUDIO_FORMAT_LDAC            */ 0x23000000:
425                 return "AUDIO_FORMAT_LDAC";
426             case /* AUDIO_FORMAT_MAT             */ 0x24000000:
427                 return "AUDIO_FORMAT_MAT";
428             case /* AUDIO_FORMAT_AAC_LATM        */ 0x25000000:
429                 return "AUDIO_FORMAT_AAC_LATM";
430             case /* AUDIO_FORMAT_CELT            */ 0x26000000:
431                 return "AUDIO_FORMAT_CELT";
432             case /* AUDIO_FORMAT_APTX_ADAPTIVE   */ 0x27000000:
433                 return "AUDIO_FORMAT_APTX_ADAPTIVE";
434             case /* AUDIO_FORMAT_LHDC            */ 0x28000000:
435                 return "AUDIO_FORMAT_LHDC";
436             case /* AUDIO_FORMAT_LHDC_LL         */ 0x29000000:
437                 return "AUDIO_FORMAT_LHDC_LL";
438             case /* AUDIO_FORMAT_APTX_TWSP       */ 0x2A000000:
439                 return "AUDIO_FORMAT_APTX_TWSP";
440             case /* AUDIO_FORMAT_LC3             */ 0x2B000000:
441                 return "AUDIO_FORMAT_LC3";
442             case /* AUDIO_FORMAT_MPEGH           */ 0x2C000000:
443                 return "AUDIO_FORMAT_MPEGH";
444             case /* AUDIO_FORMAT_IEC60958        */ 0x2D000000:
445                 return "AUDIO_FORMAT_IEC60958";
446             case /* AUDIO_FORMAT_DTS_UHD         */ 0x2E000000:
447                 return "AUDIO_FORMAT_DTS_UHD";
448             case /* AUDIO_FORMAT_DRA             */ 0x2F000000:
449                 return "AUDIO_FORMAT_DRA";
450             case /* AUDIO_FORMAT_APTX_ADAPTIVE_QLEA */ 0x30000000:
451                 return "AUDIO_FORMAT_APTX_ADAPTIVE_QLEA";
452             case /* AUDIO_FORMAT_APTX_ADAPTIVE_R4   */ 0x31000000:
453                 return "AUDIO_FORMAT_APTX_ADAPTIVE_R4";
454             case /* AUDIO_FORMAT_DTS_HD_MA       */ 0x32000000:
455                 return "AUDIO_FORMAT_DTS_HD_MA";
456             case /* AUDIO_FORMAT_DTS_UHD_P2      */ 0x33000000:
457                 return "AUDIO_FORMAT_DTS_UHD_P2";
458 
459             /* Aliases */
460             case /* AUDIO_FORMAT_PCM_16_BIT        */ 0x1:
461                 return "AUDIO_FORMAT_PCM_16_BIT";        // (PCM | PCM_SUB_16_BIT)
462             case /* AUDIO_FORMAT_PCM_8_BIT         */ 0x2:
463                 return "AUDIO_FORMAT_PCM_8_BIT";        // (PCM | PCM_SUB_8_BIT)
464             case /* AUDIO_FORMAT_PCM_32_BIT        */ 0x3:
465                 return "AUDIO_FORMAT_PCM_32_BIT";        // (PCM | PCM_SUB_32_BIT)
466             case /* AUDIO_FORMAT_PCM_8_24_BIT      */ 0x4:
467                 return "AUDIO_FORMAT_PCM_8_24_BIT";        // (PCM | PCM_SUB_8_24_BIT)
468             case /* AUDIO_FORMAT_PCM_FLOAT         */ 0x5:
469                 return "AUDIO_FORMAT_PCM_FLOAT";        // (PCM | PCM_SUB_FLOAT)
470             case /* AUDIO_FORMAT_PCM_24_BIT_PACKED */ 0x6:
471                 return "AUDIO_FORMAT_PCM_24_BIT_PACKED";        // (PCM | PCM_SUB_24_BIT_PACKED)
472             case /* AUDIO_FORMAT_AAC_MAIN          */ 0x4000001:
473                 return "AUDIO_FORMAT_AAC_MAIN";  // (AAC | AAC_SUB_MAIN)
474             case /* AUDIO_FORMAT_AAC_LC            */ 0x4000002:
475                 return "AUDIO_FORMAT_AAC_LC";  // (AAC | AAC_SUB_LC)
476             case /* AUDIO_FORMAT_AAC_SSR           */ 0x4000004:
477                 return "AUDIO_FORMAT_AAC_SSR";  // (AAC | AAC_SUB_SSR)
478             case /* AUDIO_FORMAT_AAC_LTP           */ 0x4000008:
479                 return "AUDIO_FORMAT_AAC_LTP";  // (AAC | AAC_SUB_LTP)
480             case /* AUDIO_FORMAT_AAC_HE_V1         */ 0x4000010:
481                 return "AUDIO_FORMAT_AAC_HE_V1";  // (AAC | AAC_SUB_HE_V1)
482             case /* AUDIO_FORMAT_AAC_SCALABLE      */ 0x4000020:
483                 return "AUDIO_FORMAT_AAC_SCALABLE";  // (AAC | AAC_SUB_SCALABLE)
484             case /* AUDIO_FORMAT_AAC_ERLC          */ 0x4000040:
485                 return "AUDIO_FORMAT_AAC_ERLC";  // (AAC | AAC_SUB_ERLC)
486             case /* AUDIO_FORMAT_AAC_LD            */ 0x4000080:
487                 return "AUDIO_FORMAT_AAC_LD";  // (AAC | AAC_SUB_LD)
488             case /* AUDIO_FORMAT_AAC_HE_V2         */ 0x4000100:
489                 return "AUDIO_FORMAT_AAC_HE_V2";  // (AAC | AAC_SUB_HE_V2)
490             case /* AUDIO_FORMAT_AAC_ELD           */ 0x4000200:
491                 return "AUDIO_FORMAT_AAC_ELD";  // (AAC | AAC_SUB_ELD)
492             case /* AUDIO_FORMAT_AAC_XHE           */ 0x4000300:
493                 return "AUDIO_FORMAT_AAC_XHE";  // (AAC | AAC_SUB_XHE)
494             case /* AUDIO_FORMAT_AAC_ADTS_MAIN     */ 0x1e000001:
495                 return "AUDIO_FORMAT_AAC_ADTS_MAIN"; // (AAC_ADTS | AAC_SUB_MAIN)
496             case /* AUDIO_FORMAT_AAC_ADTS_LC       */ 0x1e000002:
497                 return "AUDIO_FORMAT_AAC_ADTS_LC"; // (AAC_ADTS | AAC_SUB_LC)
498             case /* AUDIO_FORMAT_AAC_ADTS_SSR      */ 0x1e000004:
499                 return "AUDIO_FORMAT_AAC_ADTS_SSR"; // (AAC_ADTS | AAC_SUB_SSR)
500             case /* AUDIO_FORMAT_AAC_ADTS_LTP      */ 0x1e000008:
501                 return "AUDIO_FORMAT_AAC_ADTS_LTP"; // (AAC_ADTS | AAC_SUB_LTP)
502             case /* AUDIO_FORMAT_AAC_ADTS_HE_V1    */ 0x1e000010:
503                 return "AUDIO_FORMAT_AAC_ADTS_HE_V1"; // (AAC_ADTS | AAC_SUB_HE_V1)
504             case /* AUDIO_FORMAT_AAC_ADTS_SCALABLE */ 0x1e000020:
505                 return "AUDIO_FORMAT_AAC_ADTS_SCALABLE"; // (AAC_ADTS | AAC_SUB_SCALABLE)
506             case /* AUDIO_FORMAT_AAC_ADTS_ERLC     */ 0x1e000040:
507                 return "AUDIO_FORMAT_AAC_ADTS_ERLC"; // (AAC_ADTS | AAC_SUB_ERLC)
508             case /* AUDIO_FORMAT_AAC_ADTS_LD       */ 0x1e000080:
509                 return "AUDIO_FORMAT_AAC_ADTS_LD"; // (AAC_ADTS | AAC_SUB_LD)
510             case /* AUDIO_FORMAT_AAC_ADTS_HE_V2    */ 0x1e000100:
511                 return "AUDIO_FORMAT_AAC_ADTS_HE_V2"; // (AAC_ADTS | AAC_SUB_HE_V2)
512             case /* AUDIO_FORMAT_AAC_ADTS_ELD      */ 0x1e000200:
513                 return "AUDIO_FORMAT_AAC_ADTS_ELD"; // (AAC_ADTS | AAC_SUB_ELD)
514             case /* AUDIO_FORMAT_AAC_ADTS_XHE      */ 0x1e000300:
515                 return "AUDIO_FORMAT_AAC_ADTS_XHE"; // (AAC_ADTS | AAC_SUB_XHE)
516             case /* AUDIO_FORMAT_AAC_LATM_LC       */ 0x25000002:
517                 return "AUDIO_FORMAT_AAC_LATM_LC"; // (AAC_LATM | AAC_SUB_LC)
518             case /* AUDIO_FORMAT_AAC_LATM_HE_V1    */ 0x25000010:
519                 return "AUDIO_FORMAT_AAC_LATM_HE_V1"; // (AAC_LATM | AAC_SUB_HE_V1)
520             case /* AUDIO_FORMAT_AAC_LATM_HE_V2    */ 0x25000100:
521                 return "AUDIO_FORMAT_AAC_LATM_HE_V2"; // (AAC_LATM | AAC_SUB_HE_V2)
522             case /* AUDIO_FORMAT_E_AC3_JOC         */ 0xA000001:
523                 return "AUDIO_FORMAT_E_AC3_JOC";  // (E_AC3 | E_AC3_SUB_JOC)
524             case /* AUDIO_FORMAT_MAT_1_0           */ 0x24000001:
525                 return "AUDIO_FORMAT_MAT_1_0"; // (MAT | MAT_SUB_1_0)
526             case /* AUDIO_FORMAT_MAT_2_0           */ 0x24000002:
527                 return "AUDIO_FORMAT_MAT_2_0"; // (MAT | MAT_SUB_2_0)
528             case /* AUDIO_FORMAT_MAT_2_1           */ 0x24000003:
529                 return "AUDIO_FORMAT_MAT_2_1"; // (MAT | MAT_SUB_2_1)
530             case /* AUDIO_FORMAT_MPEGH_SUB_BL_L3   */ 0x2C000013:
531                 return "AUDIO_FORMAT_MPEGH_SUB_BL_L3";
532             case /* AUDIO_FORMAT_MPEGH_SUB_BL_L4   */ 0x2C000014:
533                 return "AUDIO_FORMAT_MPEGH_SUB_BL_L4";
534             case /* AUDIO_FORMAT_MPEGH_SUB_LC_L3   */ 0x2C000023:
535                 return "AUDIO_FORMAT_MPEGH_SUB_LC_L3";
536             case /* AUDIO_FORMAT_MPEGH_SUB_LC_L4   */ 0x2C000024:
537                 return "AUDIO_FORMAT_MPEGH_SUB_LC_L4";
538             default:
539                 return "AUDIO_FORMAT_(" + audioFormat + ")";
540         }
541     }
542 
543     /* Routing bits for the former setRouting/getRouting API */
544     /** @hide @deprecated */
545     @Deprecated public static final int ROUTE_EARPIECE          = (1 << 0);
546     /** @hide @deprecated */
547     @Deprecated public static final int ROUTE_SPEAKER           = (1 << 1);
548     /** @hide @deprecated use {@link #ROUTE_BLUETOOTH_SCO} */
549     @Deprecated public static final int ROUTE_BLUETOOTH = (1 << 2);
550     /** @hide @deprecated */
551     @Deprecated public static final int ROUTE_BLUETOOTH_SCO     = (1 << 2);
552     /** @hide @deprecated */
553     @Deprecated public static final int ROUTE_HEADSET           = (1 << 3);
554     /** @hide @deprecated */
555     @Deprecated public static final int ROUTE_BLUETOOTH_A2DP    = (1 << 4);
556     /** @hide @deprecated */
557     @Deprecated public static final int ROUTE_ALL               = 0xFFFFFFFF;
558 
559     // Keep in sync with system/media/audio/include/system/audio.h
560     /**  @hide */
561     public static final int AUDIO_SESSION_ALLOCATE = 0;
562 
563     /**
564      * @hide
565      * Checks whether the specified stream type is active.
566      *
567      * return true if any track playing on this stream is active.
568      */
569     @UnsupportedAppUsage
isStreamActive(int stream, int inPastMs)570     public static native boolean isStreamActive(int stream, int inPastMs);
571 
572     /**
573      * @hide
574      * Checks whether the specified stream type is active on a remotely connected device. The notion
575      * of what constitutes a remote device is enforced by the audio policy manager of the platform.
576      *
577      * return true if any track playing on this stream is active on a remote device.
578      */
isStreamActiveRemotely(int stream, int inPastMs)579     public static native boolean isStreamActiveRemotely(int stream, int inPastMs);
580 
581     /**
582      * @hide
583      * Checks whether the specified audio source is active.
584      *
585      * return true if any recorder using this source is currently recording
586      */
587     @UnsupportedAppUsage
isSourceActive(int source)588     public static native boolean isSourceActive(int source);
589 
590     /**
591      * @hide
592      * Returns a new unused audio session ID
593      */
newAudioSessionId()594     public static native int newAudioSessionId();
595 
596     /**
597      * @hide
598      * Returns a new unused audio player ID
599      */
newAudioPlayerId()600     public static native int newAudioPlayerId();
601 
602     /**
603      * @hide
604      * Returns a new unused audio recorder ID
605      */
newAudioRecorderId()606     public static native int newAudioRecorderId();
607 
608 
609     /**
610      * @hide
611      * Sets a group generic audio configuration parameters. The use of these parameters
612      * are platform dependent, see libaudio
613      *
614      * param keyValuePairs  list of parameters key value pairs in the form:
615      *    key1=value1;key2=value2;...
616      */
617     @UnsupportedAppUsage
setParameters(String keyValuePairs)618     public static native int setParameters(String keyValuePairs);
619 
620     /**
621      * @hide
622      * Gets a group generic audio configuration parameters. The use of these parameters
623      * are platform dependent, see libaudio
624      *
625      * param keys  list of parameters
626      * return value: list of parameters key value pairs in the form:
627      *    key1=value1;key2=value2;...
628      */
629     @UnsupportedAppUsage
getParameters(String keys)630     public static native String getParameters(String keys);
631 
632     // These match the enum AudioError in frameworks/base/core/jni/android_media_AudioSystem.cpp
633     /** @hide Command successful or Media server restarted. see ErrorCallback */
634     public static final int AUDIO_STATUS_OK = 0;
635     /** @hide Command failed or unspecified audio error.  see ErrorCallback */
636     public static final int AUDIO_STATUS_ERROR = 1;
637     /** @hide Media server died. see ErrorCallback */
638     public static final int AUDIO_STATUS_SERVER_DIED = 100;
639 
640     // all accesses must be synchronized (AudioSystem.class)
641     private static ErrorCallback sErrorCallback;
642 
643     /** @hide
644      * Handles the audio error callback.
645      */
646     public interface ErrorCallback
647     {
648         /*
649          * Callback for audio server errors.
650          * param error   error code:
651          * - AUDIO_STATUS_OK
652          * - AUDIO_STATUS_SERVER_DIED
653          * - AUDIO_STATUS_ERROR
654          */
onError(int error)655         void onError(int error);
656     };
657 
658     /**
659      * @hide
660      * Registers a callback to be invoked when an error occurs.
661      * @param cb the callback to run
662      */
663     @UnsupportedAppUsage
setErrorCallback(ErrorCallback cb)664     public static void setErrorCallback(ErrorCallback cb)
665     {
666         synchronized (AudioSystem.class) {
667             sErrorCallback = cb;
668             if (cb != null) {
669                 cb.onError(checkAudioFlinger());
670             }
671         }
672     }
673 
674     @UnsupportedAppUsage
errorCallbackFromNative(int error)675     private static void errorCallbackFromNative(int error)
676     {
677         ErrorCallback errorCallback;
678         synchronized (AudioSystem.class) {
679             errorCallback = sErrorCallback;
680         }
681         if (errorCallback != null) {
682             errorCallback.onError(error);
683         }
684     }
685 
686     /**
687      * @hide
688      * Handles events from the audio policy manager about dynamic audio policies
689      * @see android.media.audiopolicy.AudioPolicy
690      */
691     public interface DynamicPolicyCallback
692     {
onDynamicPolicyMixStateUpdate(String regId, int state)693         void onDynamicPolicyMixStateUpdate(String regId, int state);
694     }
695 
696     //keep in sync with include/media/AudioPolicy.h
697     private final static int DYNAMIC_POLICY_EVENT_MIX_STATE_UPDATE = 0;
698 
699     // all accesses must be synchronized (AudioSystem.class)
700     private static DynamicPolicyCallback sDynPolicyCallback;
701 
702     /** @hide */
setDynamicPolicyCallback(DynamicPolicyCallback cb)703     public static void setDynamicPolicyCallback(DynamicPolicyCallback cb)
704     {
705         synchronized (AudioSystem.class) {
706             sDynPolicyCallback = cb;
707             native_register_dynamic_policy_callback();
708         }
709     }
710 
711     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
dynamicPolicyCallbackFromNative(int event, String regId, int val)712     private static void dynamicPolicyCallbackFromNative(int event, String regId, int val)
713     {
714         DynamicPolicyCallback cb;
715         synchronized (AudioSystem.class) {
716             cb = sDynPolicyCallback;
717         }
718         if (cb != null) {
719             switch(event) {
720                 case DYNAMIC_POLICY_EVENT_MIX_STATE_UPDATE:
721                     cb.onDynamicPolicyMixStateUpdate(regId, val);
722                     break;
723                 default:
724                     Log.e(TAG, "dynamicPolicyCallbackFromNative: unknown event " + event);
725             }
726         }
727     }
728 
729     /**
730      * @hide
731      * Handles events from the audio policy manager about recording events
732      * @see android.media.AudioManager.AudioRecordingCallback
733      */
734     public interface AudioRecordingCallback
735     {
736         /**
737          * Callback for recording activity notifications events
738          * @param event
739          * @param riid recording identifier
740          * @param uid uid of the client app performing the recording
741          * @param session
742          * @param source
743          * @param recordingFormat an array of ints containing respectively the client and device
744          *    recording configurations (2*3 ints), followed by the patch handle:
745          *    index 0: client format
746          *          1: client channel mask
747          *          2: client sample rate
748          *          3: device format
749          *          4: device channel mask
750          *          5: device sample rate
751          *          6: patch handle
752          * @param packName package name of the client app performing the recording. NOT SUPPORTED
753          */
onRecordingConfigurationChanged(int event, int riid, int uid, int session, int source, int portId, boolean silenced, int[] recordingFormat, AudioEffect.Descriptor[] clienteffects, AudioEffect.Descriptor[] effects, int activeSource, String packName)754         void onRecordingConfigurationChanged(int event, int riid, int uid, int session, int source,
755                         int portId, boolean silenced, int[] recordingFormat,
756                         AudioEffect.Descriptor[] clienteffects, AudioEffect.Descriptor[] effects,
757                         int activeSource, String packName);
758     }
759 
760     // all accesses must be synchronized (AudioSystem.class)
761     private static AudioRecordingCallback sRecordingCallback;
762 
763     /** @hide */
setRecordingCallback(AudioRecordingCallback cb)764     public static void setRecordingCallback(AudioRecordingCallback cb) {
765         synchronized (AudioSystem.class) {
766             sRecordingCallback = cb;
767             native_register_recording_callback();
768         }
769     }
770 
771     /**
772      * Callback from native for recording configuration updates.
773      * @param event
774      * @param riid
775      * @param uid
776      * @param session
777      * @param source
778      * @param portId
779      * @param silenced
780      * @param recordingFormat see
781      *     {@link AudioRecordingCallback#onRecordingConfigurationChanged(int, int, int, int, int, \
782      int, boolean, int[], AudioEffect.Descriptor[], AudioEffect.Descriptor[], int, String)}
783      *     for the description of the record format.
784      * @param cleintEffects
785      * @param effects
786      * @param activeSource
787      */
788     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
recordingCallbackFromNative(int event, int riid, int uid, int session, int source, int portId, boolean silenced, int[] recordingFormat, AudioEffect.Descriptor[] clientEffects, AudioEffect.Descriptor[] effects, int activeSource)789     private static void recordingCallbackFromNative(int event, int riid, int uid, int session,
790                           int source, int portId, boolean silenced, int[] recordingFormat,
791                           AudioEffect.Descriptor[] clientEffects, AudioEffect.Descriptor[] effects,
792                           int activeSource) {
793         AudioRecordingCallback cb;
794         synchronized (AudioSystem.class) {
795             cb = sRecordingCallback;
796         }
797 
798         String clientEffectName =  clientEffects.length == 0 ? "None" : clientEffects[0].name;
799         String effectName =  effects.length == 0 ? "None" : effects[0].name;
800 
801         if (cb != null) {
802             ArrayList<AudioPatch> audioPatches = new ArrayList<>();
803             if (AudioManager.listAudioPatches(audioPatches) == AudioManager.SUCCESS) {
804                 boolean patchFound = false;
805                 int patchHandle = recordingFormat[6];
806                 for (AudioPatch patch : audioPatches) {
807                     if (patch.id() == patchHandle) {
808                         patchFound = true;
809                         break;
810                     }
811                 }
812                 if (!patchFound) {
813                     // The cached audio patches in AudioManager is not up-to-date.
814                     // Reset audio port generation to ensure callback side can
815                     // get up-to-date audio port information.
816                     AudioManager.resetAudioPortGeneration();
817                 }
818             }
819             // TODO receive package name from native
820             cb.onRecordingConfigurationChanged(event, riid, uid, session, source, portId, silenced,
821                                         recordingFormat, clientEffects, effects, activeSource, "");
822         }
823     }
824 
825     /**
826      * @hide
827      * Handles events from the audio policy manager about routing events
828      */
829     public interface RoutingUpdateCallback {
830         /**
831          * Callback to notify a routing update event occurred
832          */
onRoutingUpdated()833         void onRoutingUpdated();
834     }
835 
836     @GuardedBy("AudioSystem.class")
837     private static RoutingUpdateCallback sRoutingUpdateCallback;
838 
839     /** @hide */
setRoutingCallback(RoutingUpdateCallback cb)840     public static void setRoutingCallback(RoutingUpdateCallback cb) {
841         synchronized (AudioSystem.class) {
842             sRoutingUpdateCallback = cb;
843             native_register_routing_callback();
844         }
845     }
846 
routingCallbackFromNative()847     private static void routingCallbackFromNative() {
848         final RoutingUpdateCallback cb;
849         synchronized (AudioSystem.class) {
850             cb = sRoutingUpdateCallback;
851         }
852         if (cb == null) {
853             Log.e(TAG, "routing update from APM was not captured");
854             return;
855         }
856         cb.onRoutingUpdated();
857     }
858 
859     /**
860      * @hide
861      * Handles requests from the audio policy manager to (re-)initialize the volume ranges
862      */
863     public interface VolumeRangeInitRequestCallback {
864         /**
865          * Callback to notify volume ranges need to be initialized
866          */
onVolumeRangeInitializationRequested()867         void onVolumeRangeInitializationRequested();
868     }
869 
870     @GuardedBy("AudioSystem.class")
871     private static VolumeRangeInitRequestCallback sVolRangeInitReqCallback;
872 
873     /** @hide */
setVolumeRangeInitRequestCallback(VolumeRangeInitRequestCallback cb)874     public static void setVolumeRangeInitRequestCallback(VolumeRangeInitRequestCallback cb) {
875         synchronized (AudioSystem.class) {
876             sVolRangeInitReqCallback = cb;
877             native_register_vol_range_init_req_callback();
878         }
879     }
880 
volRangeInitReqCallbackFromNative()881     private static void volRangeInitReqCallbackFromNative() {
882         final VolumeRangeInitRequestCallback cb;
883         synchronized (AudioSystem.class) {
884             cb = sVolRangeInitReqCallback;
885         }
886         if (cb == null) {
887             Log.e(TAG, "APM requested volume range initialization, but no callback found");
888             return;
889         }
890         cb.onVolumeRangeInitializationRequested();
891     }
892 
893     /*
894      * Error codes used by public APIs (AudioTrack, AudioRecord, AudioManager ...)
895      * Must be kept in sync with frameworks/base/core/jni/android_media_AudioErrors.h
896      */
897     /** @hide */
898     public static final int SUCCESS            = 0;
899     /** @hide */
900     public static final int ERROR              = -1;
901     /** @hide */
902     public static final int BAD_VALUE          = -2;
903     /** @hide */
904     public static final int INVALID_OPERATION  = -3;
905     /** @hide */
906     public static final int PERMISSION_DENIED  = -4;
907     /** @hide */
908     public static final int NO_INIT            = -5;
909     /** @hide */
910     public static final int DEAD_OBJECT        = -6;
911     /** @hide */
912     public static final int WOULD_BLOCK        = -7;
913 
914     /** @hide */
915     @IntDef({
916             SUCCESS,
917             ERROR,
918             BAD_VALUE,
919             INVALID_OPERATION,
920             PERMISSION_DENIED,
921             NO_INIT,
922             DEAD_OBJECT,
923             WOULD_BLOCK
924     })
925     @Retention(RetentionPolicy.SOURCE)
926     public @interface AudioSystemError {}
927 
928     /**
929      * @hide
930      * Convert an int error value to its String value for readability.
931      * Accepted error values are the java AudioSystem errors, matching android_media_AudioErrors.h,
932      * which map onto the native status_t type.
933      * @param error one of the java AudioSystem errors
934      * @return a human-readable string
935      */
audioSystemErrorToString(@udioSystemError int error)936     public static String audioSystemErrorToString(@AudioSystemError int error) {
937         switch(error) {
938             case SUCCESS:
939                 return "SUCCESS";
940             case ERROR:
941                 return "ERROR";
942             case BAD_VALUE:
943                 return "BAD_VALUE";
944             case INVALID_OPERATION:
945                 return "INVALID_OPERATION";
946             case PERMISSION_DENIED:
947                 return "PERMISSION_DENIED";
948             case NO_INIT:
949                 return "NO_INIT";
950             case DEAD_OBJECT:
951                 return "DEAD_OBJECT";
952             case WOULD_BLOCK:
953                 return "WOULD_BLOCK";
954             default:
955                 return ("unknown error:" + error);
956         }
957     }
958 
959     /*
960      * AudioPolicyService methods
961      */
962 
963     //
964     // audio device definitions: must be kept in sync with values
965     // in system/media/audio/include/system/audio-hal-enums.h
966     //
967     /** @hide */
968     public static final int DEVICE_NONE = 0x0;
969     // reserved bits
970     /** @hide */
971     public static final int DEVICE_BIT_IN = 0x80000000;
972     /** @hide */
973     public static final int DEVICE_BIT_DEFAULT = 0x40000000;
974     // output devices, be sure to update AudioManager.java also
975     /** @hide */
976     @UnsupportedAppUsage
977     public static final int DEVICE_OUT_EARPIECE = 0x1;
978     /** @hide */
979     @UnsupportedAppUsage
980     public static final int DEVICE_OUT_SPEAKER = 0x2;
981     /** @hide */
982     @UnsupportedAppUsage
983     public static final int DEVICE_OUT_WIRED_HEADSET = 0x4;
984     /** @hide */
985     @UnsupportedAppUsage
986     public static final int DEVICE_OUT_WIRED_HEADPHONE = 0x8;
987     /** @hide */
988     @UnsupportedAppUsage
989     public static final int DEVICE_OUT_BLUETOOTH_SCO = 0x10;
990     /** @hide */
991     @UnsupportedAppUsage
992     public static final int DEVICE_OUT_BLUETOOTH_SCO_HEADSET = 0x20;
993     /** @hide */
994     @UnsupportedAppUsage
995     public static final int DEVICE_OUT_BLUETOOTH_SCO_CARKIT = 0x40;
996     /** @hide */
997     @UnsupportedAppUsage
998     public static final int DEVICE_OUT_BLUETOOTH_A2DP = 0x80;
999     /** @hide */
1000     @UnsupportedAppUsage
1001     public static final int DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES = 0x100;
1002     /** @hide */
1003     @UnsupportedAppUsage
1004     public static final int DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER = 0x200;
1005     /** @hide */
1006     @UnsupportedAppUsage
1007     public static final int DEVICE_OUT_AUX_DIGITAL = 0x400;
1008     /** @hide */
1009     public static final int DEVICE_OUT_HDMI = DEVICE_OUT_AUX_DIGITAL;
1010     /** @hide */
1011     @UnsupportedAppUsage
1012     public static final int DEVICE_OUT_ANLG_DOCK_HEADSET = 0x800;
1013     /** @hide */
1014     @UnsupportedAppUsage
1015     public static final int DEVICE_OUT_DGTL_DOCK_HEADSET = 0x1000;
1016     /** @hide */
1017     @UnsupportedAppUsage
1018     public static final int DEVICE_OUT_USB_ACCESSORY = 0x2000;
1019     /** @hide */
1020     @UnsupportedAppUsage
1021     public static final int DEVICE_OUT_USB_DEVICE = 0x4000;
1022     /** @hide */
1023     @UnsupportedAppUsage
1024     public static final int DEVICE_OUT_REMOTE_SUBMIX = 0x8000;
1025     /** @hide */
1026     @UnsupportedAppUsage
1027     public static final int DEVICE_OUT_TELEPHONY_TX = 0x10000;
1028     /** @hide */
1029     public static final int DEVICE_OUT_LINE = 0x20000;
1030     /** @hide */
1031     public static final int DEVICE_OUT_HDMI_ARC = 0x40000;
1032     /** @hide */
1033     public static final int DEVICE_OUT_HDMI_EARC = 0x40001;
1034     /** @hide */
1035     public static final int DEVICE_OUT_SPDIF = 0x80000;
1036     /** @hide */
1037     @UnsupportedAppUsage
1038     public static final int DEVICE_OUT_FM = 0x100000;
1039     /** @hide */
1040     public static final int DEVICE_OUT_AUX_LINE = 0x200000;
1041     /** @hide */
1042     public static final int DEVICE_OUT_SPEAKER_SAFE = 0x400000;
1043     /** @hide */
1044     public static final int DEVICE_OUT_IP = 0x800000;
1045     /** @hide */
1046     public static final int DEVICE_OUT_BUS = 0x1000000;
1047     /** @hide */
1048     public static final int DEVICE_OUT_PROXY = 0x2000000;
1049     /** @hide */
1050     public static final int DEVICE_OUT_USB_HEADSET = 0x4000000;
1051     /** @hide */
1052     public static final int DEVICE_OUT_HEARING_AID = 0x8000000;
1053     /** @hide */
1054     public static final int DEVICE_OUT_ECHO_CANCELLER = 0x10000000;
1055     /** @hide */
1056     public static final int DEVICE_OUT_BLE_HEADSET = 0x20000000;
1057     /** @hide */
1058     public static final int DEVICE_OUT_BLE_SPEAKER = 0x20000001;
1059     /** @hide */
1060     public static final int DEVICE_OUT_BLE_BROADCAST = 0x20000002;
1061 
1062     /** @hide */
1063     public static final int DEVICE_OUT_DEFAULT = DEVICE_BIT_DEFAULT;
1064 
1065     // Deprecated in R because multiple device types are no longer accessed as a bit mask.
1066     // Removing this will get lint warning about changing hidden apis.
1067     /** @hide */
1068     @UnsupportedAppUsage
1069     public static final int DEVICE_OUT_ALL_USB = (DEVICE_OUT_USB_ACCESSORY |
1070                                                   DEVICE_OUT_USB_DEVICE |
1071                                                   DEVICE_OUT_USB_HEADSET);
1072 
1073     /** @hide */
1074     public static final Set<Integer> DEVICE_OUT_ALL_SET;
1075     /** @hide */
1076     public static final Set<Integer> DEVICE_OUT_ALL_A2DP_SET;
1077     /** @hide */
1078     public static final Set<Integer> DEVICE_OUT_ALL_SCO_SET;
1079     /** @hide */
1080     public static final Set<Integer> DEVICE_OUT_ALL_USB_SET;
1081     /** @hide */
1082     public static final Set<Integer> DEVICE_OUT_ALL_HDMI_SYSTEM_AUDIO_SET;
1083     /** @hide */
1084     public static final Set<Integer> DEVICE_ALL_HDMI_SYSTEM_AUDIO_AND_SPEAKER_SET;
1085     /** @hide */
1086     public static final Set<Integer> DEVICE_OUT_ALL_BLE_SET;
1087     static {
1088         DEVICE_OUT_ALL_SET = new HashSet<>();
1089         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_EARPIECE);
1090         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_SPEAKER);
1091         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_WIRED_HEADSET);
1092         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_WIRED_HEADPHONE);
1093         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLUETOOTH_SCO);
1094         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLUETOOTH_SCO_HEADSET);
1095         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLUETOOTH_SCO_CARKIT);
1096         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLUETOOTH_A2DP);
1097         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES);
1098         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER);
1099         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_HDMI);
1100         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_ANLG_DOCK_HEADSET);
1101         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_DGTL_DOCK_HEADSET);
1102         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_USB_ACCESSORY);
1103         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_USB_DEVICE);
1104         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_REMOTE_SUBMIX);
1105         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_TELEPHONY_TX);
1106         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_LINE);
1107         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_HDMI_ARC);
1108         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_HDMI_EARC);
1109         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_SPDIF);
1110         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_FM);
1111         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_AUX_LINE);
1112         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_SPEAKER_SAFE);
1113         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_IP);
1114         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BUS);
1115         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_PROXY);
1116         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_USB_HEADSET);
1117         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_HEARING_AID);
1118         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_ECHO_CANCELLER);
1119         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLE_HEADSET);
1120         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLE_SPEAKER);
1121         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_BLE_BROADCAST);
1122         DEVICE_OUT_ALL_SET.add(DEVICE_OUT_DEFAULT);
1123 
1124         DEVICE_OUT_ALL_A2DP_SET = new HashSet<>();
1125         DEVICE_OUT_ALL_A2DP_SET.add(DEVICE_OUT_BLUETOOTH_A2DP);
1126         DEVICE_OUT_ALL_A2DP_SET.add(DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES);
1127         DEVICE_OUT_ALL_A2DP_SET.add(DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER);
1128 
1129         DEVICE_OUT_ALL_SCO_SET = new HashSet<>();
1130         DEVICE_OUT_ALL_SCO_SET.add(DEVICE_OUT_BLUETOOTH_SCO);
1131         DEVICE_OUT_ALL_SCO_SET.add(DEVICE_OUT_BLUETOOTH_SCO_HEADSET);
1132         DEVICE_OUT_ALL_SCO_SET.add(DEVICE_OUT_BLUETOOTH_SCO_CARKIT);
1133 
1134         DEVICE_OUT_ALL_USB_SET = new HashSet<>();
1135         DEVICE_OUT_ALL_USB_SET.add(DEVICE_OUT_USB_ACCESSORY);
1136         DEVICE_OUT_ALL_USB_SET.add(DEVICE_OUT_USB_DEVICE);
1137         DEVICE_OUT_ALL_USB_SET.add(DEVICE_OUT_USB_HEADSET);
1138 
1139         DEVICE_OUT_ALL_HDMI_SYSTEM_AUDIO_SET = new HashSet<>();
1140         DEVICE_OUT_ALL_HDMI_SYSTEM_AUDIO_SET.add(DEVICE_OUT_AUX_LINE);
1141         DEVICE_OUT_ALL_HDMI_SYSTEM_AUDIO_SET.add(DEVICE_OUT_HDMI_ARC);
1142         DEVICE_OUT_ALL_HDMI_SYSTEM_AUDIO_SET.add(DEVICE_OUT_HDMI_EARC);
1143         DEVICE_OUT_ALL_HDMI_SYSTEM_AUDIO_SET.add(DEVICE_OUT_SPDIF);
1144 
1145         DEVICE_ALL_HDMI_SYSTEM_AUDIO_AND_SPEAKER_SET = new HashSet<>();
1146         DEVICE_ALL_HDMI_SYSTEM_AUDIO_AND_SPEAKER_SET.addAll(DEVICE_OUT_ALL_HDMI_SYSTEM_AUDIO_SET);
1147         DEVICE_ALL_HDMI_SYSTEM_AUDIO_AND_SPEAKER_SET.add(DEVICE_OUT_SPEAKER);
1148 
1149         DEVICE_OUT_ALL_BLE_SET = new HashSet<>();
1150         DEVICE_OUT_ALL_BLE_SET.add(DEVICE_OUT_BLE_HEADSET);
1151         DEVICE_OUT_ALL_BLE_SET.add(DEVICE_OUT_BLE_SPEAKER);
1152         DEVICE_OUT_ALL_BLE_SET.add(DEVICE_OUT_BLE_BROADCAST);
1153     }
1154 
1155     // input devices
1156     /** @hide */
1157     @UnsupportedAppUsage
1158     public static final int DEVICE_IN_COMMUNICATION = DEVICE_BIT_IN | 0x1;
1159     /** @hide */
1160     @UnsupportedAppUsage
1161     public static final int DEVICE_IN_AMBIENT = DEVICE_BIT_IN | 0x2;
1162     /** @hide */
1163     @UnsupportedAppUsage
1164     public static final int DEVICE_IN_BUILTIN_MIC = DEVICE_BIT_IN | 0x4;
1165     /** @hide */
1166     @UnsupportedAppUsage
1167     public static final int DEVICE_IN_BLUETOOTH_SCO_HEADSET = DEVICE_BIT_IN | 0x8;
1168     /** @hide */
1169     @UnsupportedAppUsage
1170     public static final int DEVICE_IN_WIRED_HEADSET = DEVICE_BIT_IN | 0x10;
1171     /** @hide */
1172     @UnsupportedAppUsage
1173     public static final int DEVICE_IN_AUX_DIGITAL = DEVICE_BIT_IN | 0x20;
1174     /** @hide */
1175     public static final int DEVICE_IN_HDMI = DEVICE_IN_AUX_DIGITAL;
1176     /** @hide */
1177     @UnsupportedAppUsage
1178     public static final int DEVICE_IN_VOICE_CALL = DEVICE_BIT_IN | 0x40;
1179     /** @hide */
1180     public static final int DEVICE_IN_TELEPHONY_RX = DEVICE_IN_VOICE_CALL;
1181     /** @hide */
1182     @UnsupportedAppUsage
1183     public static final int DEVICE_IN_BACK_MIC = DEVICE_BIT_IN | 0x80;
1184     /** @hide */
1185     @UnsupportedAppUsage
1186     public static final int DEVICE_IN_REMOTE_SUBMIX = DEVICE_BIT_IN | 0x100;
1187     /** @hide */
1188     @UnsupportedAppUsage
1189     public static final int DEVICE_IN_ANLG_DOCK_HEADSET = DEVICE_BIT_IN | 0x200;
1190     /** @hide */
1191     @UnsupportedAppUsage
1192     public static final int DEVICE_IN_DGTL_DOCK_HEADSET = DEVICE_BIT_IN | 0x400;
1193     /** @hide */
1194     @UnsupportedAppUsage
1195     public static final int DEVICE_IN_USB_ACCESSORY = DEVICE_BIT_IN | 0x800;
1196     /** @hide */
1197     @UnsupportedAppUsage
1198     public static final int DEVICE_IN_USB_DEVICE = DEVICE_BIT_IN | 0x1000;
1199     /** @hide */
1200     public static final int DEVICE_IN_FM_TUNER = DEVICE_BIT_IN | 0x2000;
1201     /** @hide */
1202     public static final int DEVICE_IN_TV_TUNER = DEVICE_BIT_IN | 0x4000;
1203     /** @hide */
1204     public static final int DEVICE_IN_LINE = DEVICE_BIT_IN | 0x8000;
1205     /** @hide */
1206     public static final int DEVICE_IN_SPDIF = DEVICE_BIT_IN | 0x10000;
1207     /** @hide */
1208     @UnsupportedAppUsage
1209     public static final int DEVICE_IN_BLUETOOTH_A2DP = DEVICE_BIT_IN | 0x20000;
1210     /** @hide */
1211     public static final int DEVICE_IN_LOOPBACK = DEVICE_BIT_IN | 0x40000;
1212     /** @hide */
1213     public static final int DEVICE_IN_IP = DEVICE_BIT_IN | 0x80000;
1214     /** @hide */
1215     public static final int DEVICE_IN_BUS = DEVICE_BIT_IN | 0x100000;
1216     /** @hide */
1217     public static final int DEVICE_IN_PROXY = DEVICE_BIT_IN | 0x1000000;
1218     /** @hide */
1219     public static final int DEVICE_IN_USB_HEADSET = DEVICE_BIT_IN | 0x2000000;
1220     /** @hide */
1221     public static final int DEVICE_IN_BLUETOOTH_BLE = DEVICE_BIT_IN | 0x4000000;
1222     /** @hide */
1223     public static final int DEVICE_IN_HDMI_ARC = DEVICE_BIT_IN | 0x8000000;
1224     /** @hide */
1225     public static final int DEVICE_IN_HDMI_EARC = DEVICE_BIT_IN | 0x8000001;
1226     /** @hide */
1227     public static final int DEVICE_IN_ECHO_REFERENCE = DEVICE_BIT_IN | 0x10000000;
1228     /** @hide */
1229     public static final int DEVICE_IN_BLE_HEADSET = DEVICE_BIT_IN | 0x20000000;
1230     /** @hide */
1231     @UnsupportedAppUsage
1232     public static final int DEVICE_IN_DEFAULT = DEVICE_BIT_IN | DEVICE_BIT_DEFAULT;
1233 
1234     /** @hide */
1235     public static final Set<Integer> DEVICE_IN_ALL_SET;
1236     /** @hide */
1237     public static final Set<Integer> DEVICE_IN_ALL_SCO_SET;
1238     /** @hide */
1239     public static final Set<Integer> DEVICE_IN_ALL_USB_SET;
1240     /** @hide */
1241     public static final Set<Integer> DEVICE_IN_ALL_BLE_SET;
1242 
1243     static {
1244         DEVICE_IN_ALL_SET = new HashSet<>();
1245         DEVICE_IN_ALL_SET.add(DEVICE_IN_COMMUNICATION);
1246         DEVICE_IN_ALL_SET.add(DEVICE_IN_AMBIENT);
1247         DEVICE_IN_ALL_SET.add(DEVICE_IN_BUILTIN_MIC);
1248         DEVICE_IN_ALL_SET.add(DEVICE_IN_BLUETOOTH_SCO_HEADSET);
1249         DEVICE_IN_ALL_SET.add(DEVICE_IN_WIRED_HEADSET);
1250         DEVICE_IN_ALL_SET.add(DEVICE_IN_HDMI);
1251         DEVICE_IN_ALL_SET.add(DEVICE_IN_TELEPHONY_RX);
1252         DEVICE_IN_ALL_SET.add(DEVICE_IN_BACK_MIC);
1253         DEVICE_IN_ALL_SET.add(DEVICE_IN_REMOTE_SUBMIX);
1254         DEVICE_IN_ALL_SET.add(DEVICE_IN_ANLG_DOCK_HEADSET);
1255         DEVICE_IN_ALL_SET.add(DEVICE_IN_DGTL_DOCK_HEADSET);
1256         DEVICE_IN_ALL_SET.add(DEVICE_IN_USB_ACCESSORY);
1257         DEVICE_IN_ALL_SET.add(DEVICE_IN_USB_DEVICE);
1258         DEVICE_IN_ALL_SET.add(DEVICE_IN_FM_TUNER);
1259         DEVICE_IN_ALL_SET.add(DEVICE_IN_TV_TUNER);
1260         DEVICE_IN_ALL_SET.add(DEVICE_IN_LINE);
1261         DEVICE_IN_ALL_SET.add(DEVICE_IN_SPDIF);
1262         DEVICE_IN_ALL_SET.add(DEVICE_IN_BLUETOOTH_A2DP);
1263         DEVICE_IN_ALL_SET.add(DEVICE_IN_LOOPBACK);
1264         DEVICE_IN_ALL_SET.add(DEVICE_IN_IP);
1265         DEVICE_IN_ALL_SET.add(DEVICE_IN_BUS);
1266         DEVICE_IN_ALL_SET.add(DEVICE_IN_PROXY);
1267         DEVICE_IN_ALL_SET.add(DEVICE_IN_USB_HEADSET);
1268         DEVICE_IN_ALL_SET.add(DEVICE_IN_BLUETOOTH_BLE);
1269         DEVICE_IN_ALL_SET.add(DEVICE_IN_HDMI_ARC);
1270         DEVICE_IN_ALL_SET.add(DEVICE_IN_HDMI_EARC);
1271         DEVICE_IN_ALL_SET.add(DEVICE_IN_ECHO_REFERENCE);
1272         DEVICE_IN_ALL_SET.add(DEVICE_IN_BLE_HEADSET);
1273         DEVICE_IN_ALL_SET.add(DEVICE_IN_DEFAULT);
1274 
1275         DEVICE_IN_ALL_SCO_SET = new HashSet<>();
1276         DEVICE_IN_ALL_SCO_SET.add(DEVICE_IN_BLUETOOTH_SCO_HEADSET);
1277 
1278         DEVICE_IN_ALL_USB_SET = new HashSet<>();
1279         DEVICE_IN_ALL_USB_SET.add(DEVICE_IN_USB_ACCESSORY);
1280         DEVICE_IN_ALL_USB_SET.add(DEVICE_IN_USB_DEVICE);
1281         DEVICE_IN_ALL_USB_SET.add(DEVICE_IN_USB_HEADSET);
1282 
1283         DEVICE_IN_ALL_BLE_SET = new HashSet<>();
1284         DEVICE_IN_ALL_BLE_SET.add(DEVICE_IN_BLE_HEADSET);
1285     }
1286 
1287     /** @hide */
isBluetoothDevice(int deviceType)1288     public static boolean isBluetoothDevice(int deviceType) {
1289         return isBluetoothA2dpOutDevice(deviceType)
1290                 || isBluetoothScoDevice(deviceType)
1291                 || isBluetoothLeDevice(deviceType);
1292     }
1293 
1294     /** @hide */
isBluetoothOutDevice(int deviceType)1295     public static boolean isBluetoothOutDevice(int deviceType) {
1296         return isBluetoothA2dpOutDevice(deviceType)
1297                 || isBluetoothScoOutDevice(deviceType)
1298                 || isBluetoothLeOutDevice(deviceType);
1299     }
1300 
1301     /** @hide */
isBluetoothInDevice(int deviceType)1302     public static boolean isBluetoothInDevice(int deviceType) {
1303         return isBluetoothScoInDevice(deviceType)
1304                 || isBluetoothLeInDevice(deviceType);
1305     }
1306 
1307     /** @hide */
isBluetoothA2dpOutDevice(int deviceType)1308     public static boolean isBluetoothA2dpOutDevice(int deviceType) {
1309         return DEVICE_OUT_ALL_A2DP_SET.contains(deviceType);
1310     }
1311 
1312     /** @hide */
isBluetoothScoOutDevice(int deviceType)1313     public static boolean isBluetoothScoOutDevice(int deviceType) {
1314         return DEVICE_OUT_ALL_SCO_SET.contains(deviceType);
1315     }
1316 
1317     /** @hide */
isBluetoothScoInDevice(int deviceType)1318     public static boolean isBluetoothScoInDevice(int deviceType) {
1319         return DEVICE_IN_ALL_SCO_SET.contains(deviceType);
1320     }
1321 
1322     /** @hide */
isBluetoothScoDevice(int deviceType)1323     public static boolean isBluetoothScoDevice(int deviceType) {
1324         return isBluetoothScoOutDevice(deviceType)
1325                 || isBluetoothScoInDevice(deviceType);
1326     }
1327 
1328     /** @hide */
isBluetoothLeOutDevice(int deviceType)1329     public static boolean isBluetoothLeOutDevice(int deviceType) {
1330         return DEVICE_OUT_ALL_BLE_SET.contains(deviceType);
1331     }
1332 
1333     /** @hide */
isBluetoothLeInDevice(int deviceType)1334     public static boolean isBluetoothLeInDevice(int deviceType) {
1335         return DEVICE_IN_ALL_BLE_SET.contains(deviceType);
1336     }
1337 
1338     /** @hide */
isBluetoothLeDevice(int deviceType)1339     public static boolean isBluetoothLeDevice(int deviceType) {
1340         return isBluetoothLeOutDevice(deviceType)
1341                 || isBluetoothLeInDevice(deviceType);
1342     }
1343 
1344     /** @hide */
1345     public static final String LEGACY_REMOTE_SUBMIX_ADDRESS = "0";
1346 
1347     // device states, must match AudioSystem::device_connection_state
1348     /** @hide */
1349     @UnsupportedAppUsage
1350     public static final int DEVICE_STATE_UNAVAILABLE = 0;
1351     /** @hide */
1352     @UnsupportedAppUsage
1353     public static final int DEVICE_STATE_AVAILABLE = 1;
1354     private static final int NUM_DEVICE_STATES = 1;
1355 
1356     /** @hide */
deviceStateToString(int state)1357     public static String deviceStateToString(int state) {
1358         switch (state) {
1359             case DEVICE_STATE_UNAVAILABLE: return "DEVICE_STATE_UNAVAILABLE";
1360             case DEVICE_STATE_AVAILABLE: return "DEVICE_STATE_AVAILABLE";
1361             default: return "unknown state (" + state + ")";
1362         }
1363     }
1364 
1365     /** @hide */ public static final String DEVICE_OUT_EARPIECE_NAME = "earpiece";
1366     /** @hide */ public static final String DEVICE_OUT_SPEAKER_NAME = "speaker";
1367     /** @hide */ public static final String DEVICE_OUT_WIRED_HEADSET_NAME = "headset";
1368     /** @hide */ public static final String DEVICE_OUT_WIRED_HEADPHONE_NAME = "headphone";
1369     /** @hide */ public static final String DEVICE_OUT_BLUETOOTH_SCO_NAME = "bt_sco";
1370     /** @hide */ public static final String DEVICE_OUT_BLUETOOTH_SCO_HEADSET_NAME = "bt_sco_hs";
1371     /** @hide */ public static final String DEVICE_OUT_BLUETOOTH_SCO_CARKIT_NAME = "bt_sco_carkit";
1372     /** @hide */ public static final String DEVICE_OUT_BLUETOOTH_A2DP_NAME = "bt_a2dp";
1373     /** @hide */
1374     public static final String DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES_NAME = "bt_a2dp_hp";
1375     /** @hide */ public static final String DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER_NAME = "bt_a2dp_spk";
1376     /** @hide */ public static final String DEVICE_OUT_AUX_DIGITAL_NAME = "aux_digital";
1377     /** @hide */ public static final String DEVICE_OUT_HDMI_NAME = "hdmi";
1378     /** @hide */ public static final String DEVICE_OUT_ANLG_DOCK_HEADSET_NAME = "analog_dock";
1379     /** @hide */ public static final String DEVICE_OUT_DGTL_DOCK_HEADSET_NAME = "digital_dock";
1380     /** @hide */ public static final String DEVICE_OUT_USB_ACCESSORY_NAME = "usb_accessory";
1381     /** @hide */ public static final String DEVICE_OUT_USB_DEVICE_NAME = "usb_device";
1382     /** @hide */ public static final String DEVICE_OUT_REMOTE_SUBMIX_NAME = "remote_submix";
1383     /** @hide */ public static final String DEVICE_OUT_TELEPHONY_TX_NAME = "telephony_tx";
1384     /** @hide */ public static final String DEVICE_OUT_LINE_NAME = "line";
1385     /** @hide */ public static final String DEVICE_OUT_HDMI_ARC_NAME = "hdmi_arc";
1386     /** @hide */ public static final String DEVICE_OUT_HDMI_EARC_NAME = "hdmi_earc";
1387     /** @hide */ public static final String DEVICE_OUT_SPDIF_NAME = "spdif";
1388     /** @hide */ public static final String DEVICE_OUT_FM_NAME = "fm_transmitter";
1389     /** @hide */ public static final String DEVICE_OUT_AUX_LINE_NAME = "aux_line";
1390     /** @hide */ public static final String DEVICE_OUT_SPEAKER_SAFE_NAME = "speaker_safe";
1391     /** @hide */ public static final String DEVICE_OUT_IP_NAME = "ip";
1392     /** @hide */ public static final String DEVICE_OUT_BUS_NAME = "bus";
1393     /** @hide */ public static final String DEVICE_OUT_PROXY_NAME = "proxy";
1394     /** @hide */ public static final String DEVICE_OUT_USB_HEADSET_NAME = "usb_headset";
1395     /** @hide */ public static final String DEVICE_OUT_HEARING_AID_NAME = "hearing_aid_out";
1396     /** @hide */ public static final String DEVICE_OUT_ECHO_CANCELLER_NAME = "echo_canceller";
1397     /** @hide */ public static final String DEVICE_OUT_BLE_HEADSET_NAME = "ble_headset";
1398     /** @hide */ public static final String DEVICE_OUT_BLE_SPEAKER_NAME = "ble_speaker";
1399     /** @hide */ public static final String DEVICE_OUT_BLE_BROADCAST_NAME = "ble_broadcast";
1400 
1401     /** @hide */ public static final String DEVICE_IN_COMMUNICATION_NAME = "communication";
1402     /** @hide */ public static final String DEVICE_IN_AMBIENT_NAME = "ambient";
1403     /** @hide */ public static final String DEVICE_IN_BUILTIN_MIC_NAME = "mic";
1404     /** @hide */ public static final String DEVICE_IN_BLUETOOTH_SCO_HEADSET_NAME = "bt_sco_hs";
1405     /** @hide */ public static final String DEVICE_IN_WIRED_HEADSET_NAME = "headset";
1406     /** @hide */ public static final String DEVICE_IN_AUX_DIGITAL_NAME = "aux_digital";
1407     /** @hide */ public static final String DEVICE_IN_TELEPHONY_RX_NAME = "telephony_rx";
1408     /** @hide */ public static final String DEVICE_IN_BACK_MIC_NAME = "back_mic";
1409     /** @hide */ public static final String DEVICE_IN_REMOTE_SUBMIX_NAME = "remote_submix";
1410     /** @hide */ public static final String DEVICE_IN_ANLG_DOCK_HEADSET_NAME = "analog_dock";
1411     /** @hide */ public static final String DEVICE_IN_DGTL_DOCK_HEADSET_NAME = "digital_dock";
1412     /** @hide */ public static final String DEVICE_IN_USB_ACCESSORY_NAME = "usb_accessory";
1413     /** @hide */ public static final String DEVICE_IN_USB_DEVICE_NAME = "usb_device";
1414     /** @hide */ public static final String DEVICE_IN_FM_TUNER_NAME = "fm_tuner";
1415     /** @hide */ public static final String DEVICE_IN_TV_TUNER_NAME = "tv_tuner";
1416     /** @hide */ public static final String DEVICE_IN_LINE_NAME = "line";
1417     /** @hide */ public static final String DEVICE_IN_SPDIF_NAME = "spdif";
1418     /** @hide */ public static final String DEVICE_IN_BLUETOOTH_A2DP_NAME = "bt_a2dp";
1419     /** @hide */ public static final String DEVICE_IN_LOOPBACK_NAME = "loopback";
1420     /** @hide */ public static final String DEVICE_IN_IP_NAME = "ip";
1421     /** @hide */ public static final String DEVICE_IN_BUS_NAME = "bus";
1422     /** @hide */ public static final String DEVICE_IN_PROXY_NAME = "proxy";
1423     /** @hide */ public static final String DEVICE_IN_USB_HEADSET_NAME = "usb_headset";
1424     /** @hide */ public static final String DEVICE_IN_BLUETOOTH_BLE_NAME = "bt_ble";
1425     /** @hide */ public static final String DEVICE_IN_ECHO_REFERENCE_NAME = "echo_reference";
1426     /** @hide */ public static final String DEVICE_IN_HDMI_ARC_NAME = "hdmi_arc";
1427     /** @hide */ public static final String DEVICE_IN_HDMI_EARC_NAME = "hdmi_earc";
1428     /** @hide */ public static final String DEVICE_IN_BLE_HEADSET_NAME = "ble_headset";
1429 
1430     /** @hide */
1431     @UnsupportedAppUsage
getOutputDeviceName(int device)1432     public static String getOutputDeviceName(int device)
1433     {
1434         switch(device) {
1435         case DEVICE_OUT_EARPIECE:
1436             return DEVICE_OUT_EARPIECE_NAME;
1437         case DEVICE_OUT_SPEAKER:
1438             return DEVICE_OUT_SPEAKER_NAME;
1439         case DEVICE_OUT_WIRED_HEADSET:
1440             return DEVICE_OUT_WIRED_HEADSET_NAME;
1441         case DEVICE_OUT_WIRED_HEADPHONE:
1442             return DEVICE_OUT_WIRED_HEADPHONE_NAME;
1443         case DEVICE_OUT_BLUETOOTH_SCO:
1444             return DEVICE_OUT_BLUETOOTH_SCO_NAME;
1445         case DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
1446             return DEVICE_OUT_BLUETOOTH_SCO_HEADSET_NAME;
1447         case DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
1448             return DEVICE_OUT_BLUETOOTH_SCO_CARKIT_NAME;
1449         case DEVICE_OUT_BLUETOOTH_A2DP:
1450             return DEVICE_OUT_BLUETOOTH_A2DP_NAME;
1451         case DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
1452             return DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES_NAME;
1453         case DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
1454             return DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER_NAME;
1455         case DEVICE_OUT_HDMI:
1456             return DEVICE_OUT_HDMI_NAME;
1457         case DEVICE_OUT_ANLG_DOCK_HEADSET:
1458             return DEVICE_OUT_ANLG_DOCK_HEADSET_NAME;
1459         case DEVICE_OUT_DGTL_DOCK_HEADSET:
1460             return DEVICE_OUT_DGTL_DOCK_HEADSET_NAME;
1461         case DEVICE_OUT_USB_ACCESSORY:
1462             return DEVICE_OUT_USB_ACCESSORY_NAME;
1463         case DEVICE_OUT_USB_DEVICE:
1464             return DEVICE_OUT_USB_DEVICE_NAME;
1465         case DEVICE_OUT_REMOTE_SUBMIX:
1466             return DEVICE_OUT_REMOTE_SUBMIX_NAME;
1467         case DEVICE_OUT_TELEPHONY_TX:
1468             return DEVICE_OUT_TELEPHONY_TX_NAME;
1469         case DEVICE_OUT_LINE:
1470             return DEVICE_OUT_LINE_NAME;
1471         case DEVICE_OUT_HDMI_ARC:
1472             return DEVICE_OUT_HDMI_ARC_NAME;
1473         case DEVICE_OUT_HDMI_EARC:
1474             return DEVICE_OUT_HDMI_EARC_NAME;
1475         case DEVICE_OUT_SPDIF:
1476             return DEVICE_OUT_SPDIF_NAME;
1477         case DEVICE_OUT_FM:
1478             return DEVICE_OUT_FM_NAME;
1479         case DEVICE_OUT_AUX_LINE:
1480             return DEVICE_OUT_AUX_LINE_NAME;
1481         case DEVICE_OUT_SPEAKER_SAFE:
1482             return DEVICE_OUT_SPEAKER_SAFE_NAME;
1483         case DEVICE_OUT_IP:
1484             return DEVICE_OUT_IP_NAME;
1485         case DEVICE_OUT_BUS:
1486             return DEVICE_OUT_BUS_NAME;
1487         case DEVICE_OUT_PROXY:
1488             return DEVICE_OUT_PROXY_NAME;
1489         case DEVICE_OUT_USB_HEADSET:
1490             return DEVICE_OUT_USB_HEADSET_NAME;
1491         case DEVICE_OUT_HEARING_AID:
1492             return DEVICE_OUT_HEARING_AID_NAME;
1493         case DEVICE_OUT_ECHO_CANCELLER:
1494             return DEVICE_OUT_ECHO_CANCELLER_NAME;
1495         case DEVICE_OUT_BLE_HEADSET:
1496             return DEVICE_OUT_BLE_HEADSET_NAME;
1497         case DEVICE_OUT_BLE_SPEAKER:
1498             return DEVICE_OUT_BLE_SPEAKER_NAME;
1499         case DEVICE_OUT_BLE_BROADCAST:
1500             return DEVICE_OUT_BLE_BROADCAST_NAME;
1501         case DEVICE_OUT_DEFAULT:
1502         default:
1503             return "0x" + Integer.toHexString(device);
1504         }
1505     }
1506 
1507     /** @hide */
getInputDeviceName(int device)1508     public static String getInputDeviceName(int device)
1509     {
1510         switch(device) {
1511         case DEVICE_IN_COMMUNICATION:
1512             return DEVICE_IN_COMMUNICATION_NAME;
1513         case DEVICE_IN_AMBIENT:
1514             return DEVICE_IN_AMBIENT_NAME;
1515         case DEVICE_IN_BUILTIN_MIC:
1516             return DEVICE_IN_BUILTIN_MIC_NAME;
1517         case DEVICE_IN_BLUETOOTH_SCO_HEADSET:
1518             return DEVICE_IN_BLUETOOTH_SCO_HEADSET_NAME;
1519         case DEVICE_IN_WIRED_HEADSET:
1520             return DEVICE_IN_WIRED_HEADSET_NAME;
1521         case DEVICE_IN_AUX_DIGITAL:
1522             return DEVICE_IN_AUX_DIGITAL_NAME;
1523         case DEVICE_IN_TELEPHONY_RX:
1524             return DEVICE_IN_TELEPHONY_RX_NAME;
1525         case DEVICE_IN_BACK_MIC:
1526             return DEVICE_IN_BACK_MIC_NAME;
1527         case DEVICE_IN_REMOTE_SUBMIX:
1528             return DEVICE_IN_REMOTE_SUBMIX_NAME;
1529         case DEVICE_IN_ANLG_DOCK_HEADSET:
1530             return DEVICE_IN_ANLG_DOCK_HEADSET_NAME;
1531         case DEVICE_IN_DGTL_DOCK_HEADSET:
1532             return DEVICE_IN_DGTL_DOCK_HEADSET_NAME;
1533         case DEVICE_IN_USB_ACCESSORY:
1534             return DEVICE_IN_USB_ACCESSORY_NAME;
1535         case DEVICE_IN_USB_DEVICE:
1536             return DEVICE_IN_USB_DEVICE_NAME;
1537         case DEVICE_IN_FM_TUNER:
1538             return DEVICE_IN_FM_TUNER_NAME;
1539         case DEVICE_IN_TV_TUNER:
1540             return DEVICE_IN_TV_TUNER_NAME;
1541         case DEVICE_IN_LINE:
1542             return DEVICE_IN_LINE_NAME;
1543         case DEVICE_IN_SPDIF:
1544             return DEVICE_IN_SPDIF_NAME;
1545         case DEVICE_IN_BLUETOOTH_A2DP:
1546             return DEVICE_IN_BLUETOOTH_A2DP_NAME;
1547         case DEVICE_IN_LOOPBACK:
1548             return DEVICE_IN_LOOPBACK_NAME;
1549         case DEVICE_IN_IP:
1550             return DEVICE_IN_IP_NAME;
1551         case DEVICE_IN_BUS:
1552             return DEVICE_IN_BUS_NAME;
1553         case DEVICE_IN_PROXY:
1554             return DEVICE_IN_PROXY_NAME;
1555         case DEVICE_IN_USB_HEADSET:
1556             return DEVICE_IN_USB_HEADSET_NAME;
1557         case DEVICE_IN_BLUETOOTH_BLE:
1558             return DEVICE_IN_BLUETOOTH_BLE_NAME;
1559         case DEVICE_IN_ECHO_REFERENCE:
1560             return DEVICE_IN_ECHO_REFERENCE_NAME;
1561         case DEVICE_IN_HDMI_ARC:
1562             return DEVICE_IN_HDMI_ARC_NAME;
1563         case DEVICE_IN_HDMI_EARC:
1564             return DEVICE_IN_HDMI_EARC_NAME;
1565         case DEVICE_IN_BLE_HEADSET:
1566             return DEVICE_IN_BLE_HEADSET_NAME;
1567         case DEVICE_IN_DEFAULT:
1568         default:
1569             return Integer.toString(device);
1570         }
1571     }
1572 
1573     /**
1574      * @hide
1575      * Returns a human readable name for a given device type
1576      * @param device a native device type, NOT an AudioDeviceInfo type
1577      * @return a string describing the device type
1578      */
getDeviceName(int device)1579     public static @NonNull String getDeviceName(int device) {
1580         if ((device & DEVICE_BIT_IN) != 0) {
1581             return getInputDeviceName(device);
1582         }
1583         return getOutputDeviceName(device);
1584     }
1585 
1586     // phone state, match audio_mode???
1587     /** @hide */ public static final int PHONE_STATE_OFFCALL = 0;
1588     /** @hide */ public static final int PHONE_STATE_RINGING = 1;
1589     /** @hide */ public static final int PHONE_STATE_INCALL = 2;
1590 
1591     // device categories config for setForceUse, must match audio_policy_forced_cfg_t
1592     /** @hide */ @UnsupportedAppUsage public static final int FORCE_NONE = 0;
1593     /** @hide */ public static final int FORCE_SPEAKER = 1;
1594     /** @hide */ public static final int FORCE_HEADPHONES = 2;
1595     /** @hide */ public static final int FORCE_BT_SCO = 3;
1596     /** @hide */ public static final int FORCE_BT_A2DP = 4;
1597     /** @hide */ public static final int FORCE_WIRED_ACCESSORY = 5;
1598     /** @hide */ @UnsupportedAppUsage public static final int FORCE_BT_CAR_DOCK = 6;
1599     /** @hide */ @UnsupportedAppUsage public static final int FORCE_BT_DESK_DOCK = 7;
1600     /** @hide */ @UnsupportedAppUsage public static final int FORCE_ANALOG_DOCK = 8;
1601     /** @hide */ @UnsupportedAppUsage public static final int FORCE_DIGITAL_DOCK = 9;
1602     /** @hide */ public static final int FORCE_NO_BT_A2DP = 10;
1603     /** @hide */ public static final int FORCE_SYSTEM_ENFORCED = 11;
1604     /** @hide */ public static final int FORCE_HDMI_SYSTEM_AUDIO_ENFORCED = 12;
1605     /** @hide */ public static final int FORCE_ENCODED_SURROUND_NEVER = 13;
1606     /** @hide */ public static final int FORCE_ENCODED_SURROUND_ALWAYS = 14;
1607     /** @hide */ public static final int FORCE_ENCODED_SURROUND_MANUAL = 15;
1608     /** @hide */ public static final int NUM_FORCE_CONFIG = 16;
1609     /** @hide */ public static final int FORCE_DEFAULT = FORCE_NONE;
1610 
1611     /** @hide */
forceUseConfigToString(int config)1612     public static String forceUseConfigToString(int config) {
1613         switch (config) {
1614             case FORCE_NONE: return "FORCE_NONE";
1615             case FORCE_SPEAKER: return "FORCE_SPEAKER";
1616             case FORCE_HEADPHONES: return "FORCE_HEADPHONES";
1617             case FORCE_BT_SCO: return "FORCE_BT_SCO";
1618             case FORCE_BT_A2DP: return "FORCE_BT_A2DP";
1619             case FORCE_WIRED_ACCESSORY: return "FORCE_WIRED_ACCESSORY";
1620             case FORCE_BT_CAR_DOCK: return "FORCE_BT_CAR_DOCK";
1621             case FORCE_BT_DESK_DOCK: return "FORCE_BT_DESK_DOCK";
1622             case FORCE_ANALOG_DOCK: return "FORCE_ANALOG_DOCK";
1623             case FORCE_DIGITAL_DOCK: return "FORCE_DIGITAL_DOCK";
1624             case FORCE_NO_BT_A2DP: return "FORCE_NO_BT_A2DP";
1625             case FORCE_SYSTEM_ENFORCED: return "FORCE_SYSTEM_ENFORCED";
1626             case FORCE_HDMI_SYSTEM_AUDIO_ENFORCED: return "FORCE_HDMI_SYSTEM_AUDIO_ENFORCED";
1627             case FORCE_ENCODED_SURROUND_NEVER: return "FORCE_ENCODED_SURROUND_NEVER";
1628             case FORCE_ENCODED_SURROUND_ALWAYS: return "FORCE_ENCODED_SURROUND_ALWAYS";
1629             case FORCE_ENCODED_SURROUND_MANUAL: return "FORCE_ENCODED_SURROUND_MANUAL";
1630             default: return "unknown config (" + config + ")" ;
1631         }
1632     }
1633 
1634     // usage for setForceUse, must match audio_policy_force_use_t
1635     /** @hide */ public static final int FOR_COMMUNICATION = 0;
1636     /** @hide */ public static final int FOR_MEDIA = 1;
1637     /** @hide */ public static final int FOR_RECORD = 2;
1638     /** @hide */ public static final int FOR_DOCK = 3;
1639     /** @hide */ public static final int FOR_SYSTEM = 4;
1640     /** @hide */ public static final int FOR_HDMI_SYSTEM_AUDIO = 5;
1641     /** @hide */ public static final int FOR_ENCODED_SURROUND = 6;
1642     /** @hide */ public static final int FOR_VIBRATE_RINGING = 7;
1643     private static final int NUM_FORCE_USE = 8;
1644 
1645     // Device role in audio policy
1646     public static final int DEVICE_ROLE_NONE = 0;
1647     public static final int DEVICE_ROLE_PREFERRED = 1;
1648     public static final int DEVICE_ROLE_DISABLED = 2;
1649 
1650     /** @hide */
forceUseUsageToString(int usage)1651     public static String forceUseUsageToString(int usage) {
1652         switch (usage) {
1653             case FOR_COMMUNICATION: return "FOR_COMMUNICATION";
1654             case FOR_MEDIA: return "FOR_MEDIA";
1655             case FOR_RECORD: return "FOR_RECORD";
1656             case FOR_DOCK: return "FOR_DOCK";
1657             case FOR_SYSTEM: return "FOR_SYSTEM";
1658             case FOR_HDMI_SYSTEM_AUDIO: return "FOR_HDMI_SYSTEM_AUDIO";
1659             case FOR_ENCODED_SURROUND: return "FOR_ENCODED_SURROUND";
1660             case FOR_VIBRATE_RINGING: return "FOR_VIBRATE_RINGING";
1661             default: return "unknown usage (" + usage + ")" ;
1662         }
1663     }
1664 
1665     /** @hide Wrapper for native methods called from AudioService */
setStreamVolumeIndexAS(int stream, int index, int device)1666     public static int setStreamVolumeIndexAS(int stream, int index, int device) {
1667         if (DEBUG_VOLUME) {
1668             Log.i(TAG, "setStreamVolumeIndex: " + STREAM_NAMES[stream]
1669                     + " dev=" + Integer.toHexString(device) + " idx=" + index);
1670         }
1671         return setStreamVolumeIndex(stream, index, device);
1672     }
1673 
1674     // usage for AudioRecord.startRecordingSync(), must match AudioSystem::sync_event_t
1675     /** @hide */ public static final int SYNC_EVENT_NONE = 0;
1676     /** @hide */ public static final int SYNC_EVENT_PRESENTATION_COMPLETE = 1;
1677     /** @hide
1678      *  Not used by native implementation.
1679      *  See {@link AudioRecord.Builder#setSharedAudioEvent(MediaSyncEvent) */
1680     public static final int SYNC_EVENT_SHARE_AUDIO_HISTORY = 100;
1681 
1682     /**
1683      * @hide
1684      * @return command completion status, one of {@link #AUDIO_STATUS_OK},
1685      *     {@link #AUDIO_STATUS_ERROR} or {@link #AUDIO_STATUS_SERVER_DIED}
1686      */
1687     @UnsupportedAppUsage
setDeviceConnectionState(AudioDeviceAttributes attributes, int state, int codecFormat)1688     public static int setDeviceConnectionState(AudioDeviceAttributes attributes, int state,
1689             int codecFormat) {
1690         android.media.audio.common.AudioPort port =
1691                 AidlConversion.api2aidl_AudioDeviceAttributes_AudioPort(attributes);
1692         Parcel parcel = Parcel.obtain();
1693         port.writeToParcel(parcel, 0);
1694         parcel.setDataPosition(0);
1695         try {
1696             return setDeviceConnectionState(state, parcel, codecFormat);
1697         } finally {
1698             parcel.recycle();
1699         }
1700     }
1701     /**
1702      * @hide
1703      */
1704     @UnsupportedAppUsage
setDeviceConnectionState(int state, Parcel parcel, int codecFormat)1705     public static native int setDeviceConnectionState(int state, Parcel parcel, int codecFormat);
1706     /** @hide */
1707     @UnsupportedAppUsage
getDeviceConnectionState(int device, String device_address)1708     public static native int getDeviceConnectionState(int device, String device_address);
1709     /** @hide */
handleDeviceConfigChange(int device, String device_address, String device_name, int codecFormat)1710     public static native int handleDeviceConfigChange(int device,
1711                                                       String device_address,
1712                                                       String device_name,
1713                                                       int codecFormat);
1714     /** @hide */
1715     @UnsupportedAppUsage
setPhoneState(int state)1716     public static int setPhoneState(int state) {
1717         Log.w(TAG, "Do not use this method! Use AudioManager.setMode() instead.");
1718         return 0;
1719     }
1720     /**
1721      * @hide
1722      * Send the current audio mode to audio policy manager and audio HAL.
1723      * @param state the audio mode
1724      * @param uid the UID of the app owning the audio mode
1725      * @return command completion status.
1726      */
setPhoneState(int state, int uid)1727     public static native int setPhoneState(int state, int uid);
1728     /** @hide */
1729     @UnsupportedAppUsage
setForceUse(int usage, int config)1730     public static native int setForceUse(int usage, int config);
1731     /** @hide */
1732     @UnsupportedAppUsage
getForceUse(int usage)1733     public static native int getForceUse(int usage);
1734     /** @hide */
1735     @UnsupportedAppUsage
initStreamVolume(int stream, int indexMin, int indexMax)1736     public static native int initStreamVolume(int stream, int indexMin, int indexMax);
1737     @UnsupportedAppUsage
setStreamVolumeIndex(int stream, int index, int device)1738     private static native int setStreamVolumeIndex(int stream, int index, int device);
1739     /** @hide */
getStreamVolumeIndex(int stream, int device)1740     public static native int getStreamVolumeIndex(int stream, int device);
1741     /**
1742      * @hide
1743      * set a volume for the given {@link AudioAttributes} and for all other stream that belong to
1744      * the same volume group.
1745      * @param attributes the {@link AudioAttributes} to be considered
1746      * @param index to be applied
1747      * @param device the volume device to be considered
1748      * @return command completion status.
1749      */
setVolumeIndexForAttributes(@onNull AudioAttributes attributes, int index, int device)1750     public static native int setVolumeIndexForAttributes(@NonNull AudioAttributes attributes,
1751                                                          int index, int device);
1752    /**
1753     * @hide
1754     * get the volume index for the given {@link AudioAttributes}.
1755     * @param attributes the {@link AudioAttributes} to be considered
1756     * @param device the volume device to be considered
1757     * @return volume index for the given {@link AudioAttributes} and volume device.
1758     */
getVolumeIndexForAttributes(@onNull AudioAttributes attributes, int device)1759     public static native int getVolumeIndexForAttributes(@NonNull AudioAttributes attributes,
1760                                                          int device);
1761     /**
1762      * @hide
1763      * get the minimum volume index for the given {@link AudioAttributes}.
1764      * @param attributes the {@link AudioAttributes} to be considered
1765      * @return minimum volume index for the given {@link AudioAttributes}.
1766      */
getMinVolumeIndexForAttributes(@onNull AudioAttributes attributes)1767     public static native int getMinVolumeIndexForAttributes(@NonNull AudioAttributes attributes);
1768     /**
1769      * @hide
1770      * get the maximum volume index for the given {@link AudioAttributes}.
1771      * @param attributes the {@link AudioAttributes} to be considered
1772      * @return maximum volume index for the given {@link AudioAttributes}.
1773      */
getMaxVolumeIndexForAttributes(@onNull AudioAttributes attributes)1774     public static native int getMaxVolumeIndexForAttributes(@NonNull AudioAttributes attributes);
1775 
1776     /** @hide */
setMasterVolume(float value)1777     public static native int setMasterVolume(float value);
1778     /** @hide */
getMasterVolume()1779     public static native float getMasterVolume();
1780     /** @hide */
1781     @UnsupportedAppUsage
setMasterMute(boolean mute)1782     public static native int setMasterMute(boolean mute);
1783     /** @hide */
1784     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getMasterMute()1785     public static native boolean getMasterMute();
1786     /** @hide
1787      * Only used (unsupported) for legacy apps.
1788      * @deprecated on {@link android.os.Build.VERSION_CODES#T} as new devices
1789      *             will have multi-bit device types.
1790      *             Use {@link AudioManager#getDevicesForAttributes(AudioAttributes)} instead.
1791      */
1792     @UnsupportedAppUsage
1793     @Deprecated
getDevicesForStream(int stream)1794     public static int getDevicesForStream(int stream) {
1795         final AudioAttributes attr =
1796                 AudioProductStrategy.getAudioAttributesForStrategyWithLegacyStreamType(stream);
1797         return getDeviceMaskFromSet(generateAudioDeviceTypesSet(
1798                 getDevicesForAttributes(attr, true /* forVolume */)));
1799     }
1800 
1801     /** @hide
1802      * Conversion from a device set to a bit mask.
1803      *
1804      * Legacy compatibility method (use a device list instead of a bit mask).
1805      * Conversion to bit mask skips multi-bit (S and later) internal device types
1806      * (e.g. AudioSystem.DEVICE_OUT* or AudioManager.DEVICE_OUT*) for legacy
1807      * compatibility reasons.  Legacy apps will not understand these new device types
1808      * and it will raise false matches with old device types.
1809      */
getDeviceMaskFromSet(@onNull Set<Integer> deviceSet)1810     public static int getDeviceMaskFromSet(@NonNull Set<Integer> deviceSet) {
1811         int deviceMask = DEVICE_NONE; // zero.
1812         int deviceInChecksum = DEVICE_BIT_IN;
1813         for (Integer device : deviceSet) {
1814             if ((device & (device - 1) & ~DEVICE_BIT_IN) != 0) {
1815                 Log.v(TAG, "getDeviceMaskFromSet skipping multi-bit device value " + device);
1816                 continue;
1817             }
1818             deviceMask |= device;
1819             deviceInChecksum &= device;
1820         }
1821         // Validate that deviceSet is either ALL input devices or ALL output devices.
1822         // We check that the "OR" of all the DEVICE_BIT_INs == the "AND" of all DEVICE_BIT_INs.
1823         if (!deviceSet.isEmpty() && deviceInChecksum != (deviceMask & DEVICE_BIT_IN)) {
1824             Log.e(TAG, "getDeviceMaskFromSet: Invalid set: " + deviceSetToString(deviceSet));
1825         }
1826         return deviceMask;
1827     }
1828 
1829     /** @hide */
1830     @NonNull
deviceSetToString(@onNull Set<Integer> devices)1831     public static String deviceSetToString(@NonNull Set<Integer> devices) {
1832         int n = 0;
1833         StringBuilder sb = new StringBuilder();
1834         for (Integer device : devices) {
1835             if (n++ > 0) {
1836                 sb.append(", ");
1837             }
1838             sb.append(AudioSystem.getDeviceName(device));
1839             sb.append("(" + Integer.toHexString(device) + ")");
1840         }
1841         return sb.toString();
1842     }
1843 
1844     /**
1845      * @hide
1846      * Do not use directly, see {@link AudioManager#getDevicesForAttributes(AudioAttributes)}
1847      * Get the audio devices that would be used for the routing of the given audio attributes.
1848      * @param attributes the {@link AudioAttributes} for which the routing is being queried
1849      * @return an empty list if there was an issue with the request, a list of audio devices
1850      *   otherwise (typically one device, except for duplicated paths).
1851      */
getDevicesForAttributes( @onNull AudioAttributes attributes, boolean forVolume)1852     public static @NonNull ArrayList<AudioDeviceAttributes> getDevicesForAttributes(
1853             @NonNull AudioAttributes attributes, boolean forVolume) {
1854         Objects.requireNonNull(attributes);
1855         final AudioDeviceAttributes[] devices = new AudioDeviceAttributes[MAX_DEVICE_ROUTING];
1856         final int res = getDevicesForAttributes(attributes, devices, forVolume);
1857         final ArrayList<AudioDeviceAttributes> routeDevices = new ArrayList<>();
1858         if (res != SUCCESS) {
1859             Log.e(TAG, "error " + res + " in getDevicesForAttributes attributes: " + attributes
1860                     + " forVolume: " + forVolume);
1861             return routeDevices;
1862         }
1863 
1864         for (AudioDeviceAttributes device : devices) {
1865             if (device != null) {
1866                 routeDevices.add(device);
1867             }
1868         }
1869         return routeDevices;
1870     }
1871 
1872     /**
1873      * Maximum number of audio devices a track is ever routed to, determines the size of the
1874      * array passed to {@link #getDevicesForAttributes(AudioAttributes, AudioDeviceAttributes[])}
1875      */
1876     private static final int MAX_DEVICE_ROUTING = 4;
1877 
getDevicesForAttributes(@onNull AudioAttributes aa, @NonNull AudioDeviceAttributes[] devices, boolean forVolume)1878     private static native int getDevicesForAttributes(@NonNull AudioAttributes aa,
1879                                                       @NonNull AudioDeviceAttributes[] devices,
1880                                                       boolean forVolume);
1881 
1882     /** @hide returns true if master mono is enabled. */
getMasterMono()1883     public static native boolean getMasterMono();
1884     /** @hide enables or disables the master mono mode. */
setMasterMono(boolean mono)1885     public static native int setMasterMono(boolean mono);
1886     /** @hide enables or disables the RTT mode. */
setRttEnabled(boolean enabled)1887     public static native int setRttEnabled(boolean enabled);
1888 
1889     /** @hide returns master balance value in range -1.f -> 1.f, where 0.f is dead center. */
1890     @TestApi
1891     @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS)
getMasterBalance()1892     public static native float getMasterBalance();
1893     /** @hide Changes the audio balance of the device. */
1894     @TestApi
1895     @RequiresPermission(android.Manifest.permission.MODIFY_AUDIO_SETTINGS)
setMasterBalance(float balance)1896     public static native int setMasterBalance(float balance);
1897 
1898     // helpers for android.media.AudioManager.getProperty(), see description there for meaning
1899     /** @hide */
1900     @UnsupportedAppUsage(trackingBug = 134049522)
getPrimaryOutputSamplingRate()1901     public static native int getPrimaryOutputSamplingRate();
1902     /** @hide */
1903     @UnsupportedAppUsage(trackingBug = 134049522)
getPrimaryOutputFrameCount()1904     public static native int getPrimaryOutputFrameCount();
1905     /** @hide */
1906     @UnsupportedAppUsage
getOutputLatency(int stream)1907     public static native int getOutputLatency(int stream);
1908 
1909     /** @hide */
setLowRamDevice(boolean isLowRamDevice, long totalMemory)1910     public static native int setLowRamDevice(boolean isLowRamDevice, long totalMemory);
1911     /** @hide */
1912     @UnsupportedAppUsage
checkAudioFlinger()1913     public static native int checkAudioFlinger();
1914     /** @hide */
setAudioFlingerBinder(IBinder audioFlinger)1915     public static native void setAudioFlingerBinder(IBinder audioFlinger);
1916 
1917     /** @hide */
listAudioPorts(ArrayList<AudioPort> ports, int[] generation)1918     public static native int listAudioPorts(ArrayList<AudioPort> ports, int[] generation);
1919     /** @hide */
createAudioPatch(AudioPatch[] patch, AudioPortConfig[] sources, AudioPortConfig[] sinks)1920     public static native int createAudioPatch(AudioPatch[] patch,
1921                                             AudioPortConfig[] sources, AudioPortConfig[] sinks);
1922     /** @hide */
releaseAudioPatch(AudioPatch patch)1923     public static native int releaseAudioPatch(AudioPatch patch);
1924     /** @hide */
listAudioPatches(ArrayList<AudioPatch> patches, int[] generation)1925     public static native int listAudioPatches(ArrayList<AudioPatch> patches, int[] generation);
1926     /** @hide */
setAudioPortConfig(AudioPortConfig config)1927     public static native int setAudioPortConfig(AudioPortConfig config);
1928 
1929     /** @hide */
startAudioSource(AudioPortConfig config, AudioAttributes audioAttributes)1930     public static native int startAudioSource(AudioPortConfig config,
1931                                               AudioAttributes audioAttributes);
1932     /** @hide */
stopAudioSource(int handle)1933     public static native int stopAudioSource(int handle);
1934 
1935     // declare this instance as having a dynamic policy callback handler
native_register_dynamic_policy_callback()1936     private static native final void native_register_dynamic_policy_callback();
1937     // declare this instance as having a recording configuration update callback handler
native_register_recording_callback()1938     private static native final void native_register_recording_callback();
1939     // declare this instance as having a routing update callback handler
native_register_routing_callback()1940     private static native void native_register_routing_callback();
1941     // declare this instance as having a volume range init request handler
native_register_vol_range_init_req_callback()1942     private static native void native_register_vol_range_init_req_callback();
1943 
1944     // must be kept in sync with value in include/system/audio.h
1945     /** @hide */ public static final int AUDIO_HW_SYNC_INVALID = 0;
1946 
1947     /** @hide */
getAudioHwSyncForSession(int sessionId)1948     public static native int getAudioHwSyncForSession(int sessionId);
1949 
1950     /** @hide */
registerPolicyMixes(ArrayList<AudioMix> mixes, boolean register)1951     public static native int registerPolicyMixes(ArrayList<AudioMix> mixes, boolean register);
1952 
1953     /** @hide see AudioPolicy.setUidDeviceAffinities() */
setUidDeviceAffinities(int uid, @NonNull int[] types, @NonNull String[] addresses)1954     public static native int setUidDeviceAffinities(int uid, @NonNull int[] types,
1955             @NonNull String[] addresses);
1956 
1957     /** @hide see AudioPolicy.removeUidDeviceAffinities() */
removeUidDeviceAffinities(int uid)1958     public static native int removeUidDeviceAffinities(int uid);
1959 
1960     /** @hide see AudioPolicy.setUserIdDeviceAffinities() */
setUserIdDeviceAffinities(int userId, @NonNull int[] types, @NonNull String[] addresses)1961     public static native int setUserIdDeviceAffinities(int userId, @NonNull int[] types,
1962             @NonNull String[] addresses);
1963 
1964     /** @hide see AudioPolicy.removeUserIdDeviceAffinities() */
removeUserIdDeviceAffinities(int userId)1965     public static native int removeUserIdDeviceAffinities(int userId);
1966 
1967     /** @hide */
systemReady()1968     public static native int systemReady();
1969 
1970     /** @hide */
getStreamVolumeDB(int stream, int index, int device)1971     public static native float getStreamVolumeDB(int stream, int index, int device);
1972 
1973     /**
1974      * @hide
1975      * Communicate supported system usages to audio policy service.
1976      */
setSupportedSystemUsages(int[] systemUsages)1977     public static native int setSupportedSystemUsages(int[] systemUsages);
1978 
1979     /**
1980      * @hide
1981      * @see AudioManager#setAllowedCapturePolicy()
1982      */
setAllowedCapturePolicy(int uid, int flags)1983     public static native int setAllowedCapturePolicy(int uid, int flags);
1984 
1985     /**
1986      * @hide
1987      * Direct playback modes supported by audio HAL implementation.
1988      */
1989     public static final int DIRECT_NOT_SUPPORTED = 0;
1990     public static final int DIRECT_OFFLOAD_SUPPORTED = 1;
1991     public static final int DIRECT_OFFLOAD_GAPLESS_SUPPORTED = 3;
1992     public static final int DIRECT_BITSTREAM_SUPPORTED = 4;
1993 
1994     /**
1995      * @hide
1996      * Compressed audio offload decoding modes supported by audio HAL implementation.
1997      * Keep in sync with system/media/include/media/audio.h.
1998      */
1999     public static final int OFFLOAD_NOT_SUPPORTED = DIRECT_NOT_SUPPORTED;
2000     public static final int OFFLOAD_SUPPORTED = DIRECT_OFFLOAD_SUPPORTED;
2001     public static final int OFFLOAD_GAPLESS_SUPPORTED = 2;
2002 
2003     /**
2004      * @hide
2005      * Returns how direct playback of an audio format is currently available on the device.
2006      * @param format the audio format (codec, sample rate, channels) being checked.
2007      * @param attributes the {@link AudioAttributes} to be used for playback
2008      * @return the direct playback mode available with given format and attributes. Any combination
2009      *         of {@link #DIRECT_NOT_SUPPORTED}, {@link #DIRECT_OFFLOAD_SUPPORTED},
2010      *         {@link #DIRECT_OFFLOAD_GAPLESS_SUPPORTED} and {@link #DIRECT_BITSTREAM_SUPPORTED}.
2011      */
getDirectPlaybackSupport( @onNull AudioFormat format, @NonNull AudioAttributes attributes)2012     public static native int getDirectPlaybackSupport(
2013             @NonNull AudioFormat format, @NonNull AudioAttributes attributes);
2014 
getOffloadSupport(@onNull AudioFormat format, @NonNull AudioAttributes attr)2015     static int getOffloadSupport(@NonNull AudioFormat format, @NonNull AudioAttributes attr) {
2016         return native_get_offload_support(format.getEncoding(), format.getSampleRate(),
2017                 format.getChannelMask(), format.getChannelIndexMask(),
2018                 attr.getVolumeControlStream());
2019     }
2020 
native_get_offload_support(int encoding, int sampleRate, int channelMask, int channelIndexMask, int streamType)2021     private static native int native_get_offload_support(int encoding, int sampleRate,
2022             int channelMask, int channelIndexMask, int streamType);
2023 
2024     /** @hide */
getMicrophones(ArrayList<MicrophoneInfo> microphonesInfo)2025     public static native int getMicrophones(ArrayList<MicrophoneInfo> microphonesInfo);
2026 
2027     /** @hide */
getSurroundFormats(Map<Integer, Boolean> surroundFormats)2028     public static native int getSurroundFormats(Map<Integer, Boolean> surroundFormats);
2029 
2030     /** @hide */
getReportedSurroundFormats(ArrayList<Integer> surroundFormats)2031     public static native int getReportedSurroundFormats(ArrayList<Integer> surroundFormats);
2032 
2033     /**
2034      * @hide
2035      * Returns a list of audio formats (codec) supported on the A2DP and LE audio offload path.
2036      */
getHwOffloadFormatsSupportedForBluetoothMedia( @tOffloadDeviceType int deviceType, ArrayList<Integer> formatList)2037     public static native int getHwOffloadFormatsSupportedForBluetoothMedia(
2038             @BtOffloadDeviceType int deviceType, ArrayList<Integer> formatList);
2039 
2040     /** @hide */
setSurroundFormatEnabled(int audioFormat, boolean enabled)2041     public static native int setSurroundFormatEnabled(int audioFormat, boolean enabled);
2042 
2043     /**
2044      * @hide
2045      * Communicate UIDs of the active assistant to audio policy service.
2046      */
setActiveAssistantServicesUids(int[] uids)2047     public static native int setActiveAssistantServicesUids(int[] uids);
2048 
2049     /**
2050      * @hide
2051      * Communicate UIDs of assistant to audio policy service.
2052      */
setAssistantServicesUids(int[] uids)2053     public static native int setAssistantServicesUids(int[] uids);
2054 
2055     /**
2056      * @hide
2057      * Communicate UIDs of active accessibility services to audio policy service.
2058      */
setA11yServicesUids(int[] uids)2059     public static native int setA11yServicesUids(int[] uids);
2060 
2061     /**
2062      * @hide
2063      * Communicate UID of current InputMethodService to audio policy service.
2064      */
setCurrentImeUid(int uid)2065     public static native int setCurrentImeUid(int uid);
2066 
2067 
2068     /**
2069      * @hide
2070      * @see AudioManager#isHapticPlaybackSupported()
2071      */
isHapticPlaybackSupported()2072     public static native boolean isHapticPlaybackSupported();
2073 
2074     /**
2075      * @hide
2076      * @see AudioManager#isUltrasoundSupported()
2077      */
isUltrasoundSupported()2078     public static native boolean isUltrasoundSupported();
2079 
2080     /**
2081      * @hide
2082      * Send audio HAL server process pids to native audioserver process for use
2083      * when generating audio HAL servers tombstones
2084      */
setAudioHalPids(int[] pids)2085     public static native int setAudioHalPids(int[] pids);
2086 
2087     /**
2088      * @hide
2089      * @see AudioManager#isCallScreeningModeSupported()
2090      */
isCallScreeningModeSupported()2091     public static native boolean isCallScreeningModeSupported();
2092 
2093     // use case routing by product strategy
2094 
2095     /**
2096      * @hide
2097      * Set device as role for product strategy.
2098      * @param strategy the id of the strategy to configure
2099      * @param role the role of the devices
2100      * @param devices the list of devices to be set as role for the given strategy
2101      * @return {@link #SUCCESS} if successfully set
2102      */
setDevicesRoleForStrategy( int strategy, int role, @NonNull List<AudioDeviceAttributes> devices)2103     public static int setDevicesRoleForStrategy(
2104             int strategy, int role, @NonNull List<AudioDeviceAttributes> devices) {
2105         if (devices.isEmpty()) {
2106             return BAD_VALUE;
2107         }
2108         int[] types = new int[devices.size()];
2109         String[] addresses = new String[devices.size()];
2110         for (int i = 0; i < devices.size(); ++i) {
2111             types[i] = devices.get(i).getInternalType();
2112             addresses[i] = devices.get(i).getAddress();
2113         }
2114         return setDevicesRoleForStrategy(strategy, role, types, addresses);
2115     }
2116 
2117     /**
2118      * @hide
2119      * Set device as role for product strategy.
2120      * @param strategy the id of the strategy to configure
2121      * @param role the role of the devices
2122      * @param types all device types
2123      * @param addresses all device addresses
2124      * @return {@link #SUCCESS} if successfully set
2125      */
setDevicesRoleForStrategy( int strategy, int role, @NonNull int[] types, @NonNull String[] addresses)2126     private static native int setDevicesRoleForStrategy(
2127             int strategy, int role, @NonNull int[] types, @NonNull String[] addresses);
2128 
2129     /**
2130      * @hide
2131      * Remove device as role for product strategy.
2132      * @param strategy the id of the strategy to configure
2133      * @param role the role of the devices
2134      * @param devices the list of devices to be removed as role for the given strategy
2135      * @return {@link #SUCCESS} if successfully set
2136      */
removeDevicesRoleForStrategy( int strategy, int role, @NonNull List<AudioDeviceAttributes> devices)2137     public static int removeDevicesRoleForStrategy(
2138             int strategy, int role, @NonNull List<AudioDeviceAttributes> devices) {
2139         if (devices.isEmpty()) {
2140             return BAD_VALUE;
2141         }
2142         int[] types = new int[devices.size()];
2143         String[] addresses = new String[devices.size()];
2144         for (int i = 0; i < devices.size(); ++i) {
2145             types[i] = devices.get(i).getInternalType();
2146             addresses[i] = devices.get(i).getAddress();
2147         }
2148         return removeDevicesRoleForStrategy(strategy, role, types, addresses);
2149     }
2150 
2151     /**
2152      * @hide
2153      * Remove devices as role for the strategy
2154      * @param strategy the id of the strategy to configure
2155      * @param role the role of the devices
2156      * @param types all device types
2157      * @param addresses all device addresses
2158      * @return {@link #SUCCESS} if successfully removed
2159      */
removeDevicesRoleForStrategy( int strategy, int role, @NonNull int[] types, @NonNull String[] addresses)2160     public static native int removeDevicesRoleForStrategy(
2161             int strategy, int role, @NonNull int[] types, @NonNull String[] addresses);
2162 
2163     /**
2164      * @hide
2165      * Remove all devices as role for the strategy
2166      * @param strategy the id of the strategy to configure
2167      * @param role the role of the devices
2168      * @return {@link #SUCCESS} if successfully removed
2169      */
clearDevicesRoleForStrategy(int strategy, int role)2170     public static native int clearDevicesRoleForStrategy(int strategy, int role);
2171 
2172     /**
2173      * @hide
2174      * Query previously set devices as role for a strategy
2175      * @param strategy the id of the strategy to query for
2176      * @param role the role of the devices
2177      * @param devices a list that will contain the devices of role
2178      * @return {@link #SUCCESS} if there is a preferred device and it was successfully retrieved
2179      *     and written to the array
2180      */
getDevicesForRoleAndStrategy( int strategy, int role, @NonNull List<AudioDeviceAttributes> devices)2181     public static native int getDevicesForRoleAndStrategy(
2182             int strategy, int role, @NonNull List<AudioDeviceAttributes> devices);
2183 
2184     // use case routing by capture preset
2185 
populateInputDevicesTypeAndAddress( @onNull List<AudioDeviceAttributes> devices)2186     private static Pair<int[], String[]> populateInputDevicesTypeAndAddress(
2187             @NonNull List<AudioDeviceAttributes> devices) {
2188         int[] types = new int[devices.size()];
2189         String[] addresses = new String[devices.size()];
2190         for (int i = 0; i < devices.size(); ++i) {
2191             types[i] = devices.get(i).getInternalType();
2192             if (types[i] == AudioSystem.DEVICE_NONE) {
2193                 types[i] = AudioDeviceInfo.convertDeviceTypeToInternalInputDevice(
2194                         devices.get(i).getType(), devices.get(i).getAddress());
2195             }
2196             addresses[i] = devices.get(i).getAddress();
2197         }
2198         return new Pair<int[], String[]>(types, addresses);
2199     }
2200 
2201     /**
2202      * @hide
2203      * Set devices as role for capture preset.
2204      * @param capturePreset the capture preset to configure
2205      * @param role the role of the devices
2206      * @param devices the list of devices to be set as role for the given capture preset
2207      * @return {@link #SUCCESS} if successfully set
2208      */
setDevicesRoleForCapturePreset( int capturePreset, int role, @NonNull List<AudioDeviceAttributes> devices)2209     public static int setDevicesRoleForCapturePreset(
2210             int capturePreset, int role, @NonNull List<AudioDeviceAttributes> devices) {
2211         if (devices.isEmpty()) {
2212             return BAD_VALUE;
2213         }
2214         Pair<int[], String[]> typeAddresses = populateInputDevicesTypeAndAddress(devices);
2215         return setDevicesRoleForCapturePreset(
2216                 capturePreset, role, typeAddresses.first, typeAddresses.second);
2217     }
2218 
2219     /**
2220      * @hide
2221      * Set devices as role for capture preset.
2222      * @param capturePreset the capture preset to configure
2223      * @param role the role of the devices
2224      * @param types all device types
2225      * @param addresses all device addresses
2226      * @return {@link #SUCCESS} if successfully set
2227      */
setDevicesRoleForCapturePreset( int capturePreset, int role, @NonNull int[] types, @NonNull String[] addresses)2228     private static native int setDevicesRoleForCapturePreset(
2229             int capturePreset, int role, @NonNull int[] types, @NonNull String[] addresses);
2230 
2231     /**
2232      * @hide
2233      * Add devices as role for capture preset.
2234      * @param capturePreset the capture preset to configure
2235      * @param role the role of the devices
2236      * @param devices the list of devices to be added as role for the given capture preset
2237      * @return {@link #SUCCESS} if successfully add
2238      */
addDevicesRoleForCapturePreset( int capturePreset, int role, @NonNull List<AudioDeviceAttributes> devices)2239     public static int addDevicesRoleForCapturePreset(
2240             int capturePreset, int role, @NonNull List<AudioDeviceAttributes> devices) {
2241         if (devices.isEmpty()) {
2242             return BAD_VALUE;
2243         }
2244         Pair<int[], String[]> typeAddresses = populateInputDevicesTypeAndAddress(devices);
2245         return addDevicesRoleForCapturePreset(
2246                 capturePreset, role, typeAddresses.first, typeAddresses.second);
2247     }
2248 
2249     /**
2250      * @hide
2251      * Add devices as role for capture preset.
2252      * @param capturePreset the capture preset to configure
2253      * @param role the role of the devices
2254      * @param types all device types
2255      * @param addresses all device addresses
2256      * @return {@link #SUCCESS} if successfully set
2257      */
addDevicesRoleForCapturePreset( int capturePreset, int role, @NonNull int[] types, @NonNull String[] addresses)2258     private static native int addDevicesRoleForCapturePreset(
2259             int capturePreset, int role, @NonNull int[] types, @NonNull String[] addresses);
2260 
2261     /**
2262      * @hide
2263      * Remove devices as role for the capture preset
2264      * @param capturePreset the capture preset to configure
2265      * @param role the role of the devices
2266      * @param devices the devices to be removed
2267      * @return {@link #SUCCESS} if successfully removed
2268      */
removeDevicesRoleForCapturePreset( int capturePreset, int role, @NonNull List<AudioDeviceAttributes> devices)2269     public static int removeDevicesRoleForCapturePreset(
2270             int capturePreset, int role, @NonNull List<AudioDeviceAttributes> devices) {
2271         if (devices.isEmpty()) {
2272             return BAD_VALUE;
2273         }
2274         Pair<int[], String[]> typeAddresses = populateInputDevicesTypeAndAddress(devices);
2275         return removeDevicesRoleForCapturePreset(
2276                 capturePreset, role, typeAddresses.first, typeAddresses.second);
2277     }
2278 
2279     /**
2280      * @hide
2281      * Remove devices as role for capture preset.
2282      * @param capturePreset the capture preset to configure
2283      * @param role the role of the devices
2284      * @param types all device types
2285      * @param addresses all device addresses
2286      * @return {@link #SUCCESS} if successfully set
2287      */
removeDevicesRoleForCapturePreset( int capturePreset, int role, @NonNull int[] types, @NonNull String[] addresses)2288     private static native int removeDevicesRoleForCapturePreset(
2289             int capturePreset, int role, @NonNull int[] types, @NonNull String[] addresses);
2290 
2291     /**
2292      * @hide
2293      * Remove all devices as role for the capture preset
2294      * @param capturePreset the capture preset to configure
2295      * @param role the role of the devices
2296      * @return {@link #SUCCESS} if successfully removed
2297      */
clearDevicesRoleForCapturePreset(int capturePreset, int role)2298     public static native int clearDevicesRoleForCapturePreset(int capturePreset, int role);
2299 
2300     /**
2301      * @hide
2302      * Query previously set devices as role for a capture preset
2303      * @param capturePreset the capture preset to query for
2304      * @param role the role of the devices
2305      * @param devices a list that will contain the devices of role
2306      * @return {@link #SUCCESS} if there is a preferred device and it was successfully retrieved
2307      *     and written to the array
2308      */
getDevicesForRoleAndCapturePreset( int capturePreset, int role, @NonNull List<AudioDeviceAttributes> devices)2309     public static native int getDevicesForRoleAndCapturePreset(
2310             int capturePreset, int role, @NonNull List<AudioDeviceAttributes> devices);
2311 
2312     /**
2313      * @hide
2314      * Set the vibrators' information. The value will be used to initialize HapticGenerator.
2315      * @param vibrators a list of all available vibrators
2316      * @return command completion status
2317      */
setVibratorInfos(@onNull List<Vibrator> vibrators)2318     public static native int setVibratorInfos(@NonNull List<Vibrator> vibrators);
2319 
2320     /**
2321      * @hide
2322      * If a spatializer effect is present on the platform, this will return an
2323      * ISpatializer interface to control this feature.
2324      * If no spatializer is present, a null interface is returned.
2325      * The INativeSpatializerCallback passed must not be null.
2326      * Only one ISpatializer interface can exist at a given time. The native audio policy
2327      * service will reject the request if an interface was already acquired and previous owner
2328      * did not die or call ISpatializer.release().
2329      * @param callback the callback to receive state updates if the ISpatializer
2330      *        interface is acquired.
2331      * @return the ISpatializer interface made available to control the
2332      *        platform spatializer
2333      */
2334     @Nullable
getSpatializer(INativeSpatializerCallback callback)2335     public static ISpatializer getSpatializer(INativeSpatializerCallback callback) {
2336         return ISpatializer.Stub.asInterface(nativeGetSpatializer(callback));
2337     }
nativeGetSpatializer(INativeSpatializerCallback callback)2338     private static native IBinder nativeGetSpatializer(INativeSpatializerCallback callback);
2339 
2340     /**
2341      * @hide
2342      * Queries if some kind of spatialization will be performed if the audio playback context
2343      * described by the provided arguments is present.
2344      * The context is made of:
2345      * - The audio attributes describing the playback use case.
2346      * - The audio configuration describing the audio format, channels, sampling rate ...
2347      * - The devices describing the sink audio device selected for playback.
2348      * All arguments are optional and only the specified arguments are used to match against
2349      * supported criteria. For instance, supplying no argument will tell if spatialization is
2350      * supported or not in general.
2351      * @param attributes audio attributes describing the playback use case
2352      * @param format audio configuration describing the audio format, channels, sampling rate...
2353      * @param devices the sink audio device selected for playback
2354      * @return true if spatialization is enabled for this context, false otherwise.
2355      */
canBeSpatialized(AudioAttributes attributes, AudioFormat format, AudioDeviceAttributes[] devices)2356     public static native boolean canBeSpatialized(AudioAttributes attributes,
2357                                               AudioFormat format,
2358                                               AudioDeviceAttributes[] devices);
2359 
2360     /**
2361      * @hide
2362      * Register the sound dose callback with the audio server and returns the binder to the
2363      * ISoundDose interface.
2364      *
2365      * @return ISoundDose interface with registered callback.
2366      */
2367     @Nullable
getSoundDoseInterface(ISoundDoseCallback callback)2368     public static ISoundDose getSoundDoseInterface(ISoundDoseCallback callback) {
2369         return ISoundDose.Stub.asInterface(nativeGetSoundDose(callback));
2370     }
2371 
nativeGetSoundDose(ISoundDoseCallback callback)2372     private static native IBinder nativeGetSoundDose(ISoundDoseCallback callback);
2373 
2374     /**
2375      * @hide
2376      * @param attributes audio attributes describing the playback use case
2377      * @param audioProfilesList the list of AudioProfiles that can be played as direct output
2378      * @return {@link #SUCCESS} if the list of AudioProfiles was successfully created (can be empty)
2379      */
getDirectProfilesForAttributes(@onNull AudioAttributes attributes, @NonNull ArrayList<AudioProfile> audioProfilesList)2380     public static native int getDirectProfilesForAttributes(@NonNull AudioAttributes attributes,
2381             @NonNull ArrayList<AudioProfile> audioProfilesList);
2382 
2383     // Items shared with audio service
2384 
2385     /**
2386      * @hide
2387      * The delay before playing a sound. This small period exists so the user
2388      * can press another key (non-volume keys, too) to have it NOT be audible.
2389      * <p>
2390      * PhoneWindow will implement this part.
2391      */
2392     public static final int PLAY_SOUND_DELAY = 300;
2393 
2394     /**
2395      * @hide
2396      * Constant to identify a focus stack entry that is used to hold the focus while the phone
2397      * is ringing or during a call. Used by com.android.internal.telephony.CallManager when
2398      * entering and exiting calls.
2399      */
2400     public final static String IN_VOICE_COMM_FOCUS_ID = "AudioFocus_For_Phone_Ring_And_Calls";
2401 
2402     /**
2403      * @hide
2404      * @see AudioManager#setVibrateSetting(int, int)
2405      */
getValueForVibrateSetting(int existingValue, int vibrateType, int vibrateSetting)2406     public static int getValueForVibrateSetting(int existingValue, int vibrateType,
2407             int vibrateSetting) {
2408 
2409         // First clear the existing setting. Each vibrate type has two bits in
2410         // the value. Note '3' is '11' in binary.
2411         existingValue &= ~(3 << (vibrateType * 2));
2412 
2413         // Set into the old value
2414         existingValue |= (vibrateSetting & 3) << (vibrateType * 2);
2415 
2416         return existingValue;
2417     }
2418 
2419     /** @hide */
getDefaultStreamVolume(int streamType)2420     public static int getDefaultStreamVolume(int streamType) {
2421         return DEFAULT_STREAM_VOLUME[streamType];
2422     }
2423 
2424     /** @hide */
2425     public static int[] DEFAULT_STREAM_VOLUME = new int[] {
2426         4,  // STREAM_VOICE_CALL
2427         7,  // STREAM_SYSTEM
2428         5,  // STREAM_RING           // configured in AudioService by config_audio_notif_vol_default
2429         5, // STREAM_MUSIC
2430         6,  // STREAM_ALARM
2431         5,  // STREAM_NOTIFICATION   // configured in AudioService by config_audio_ring_vol_default
2432         7,  // STREAM_BLUETOOTH_SCO
2433         7,  // STREAM_SYSTEM_ENFORCED
2434         5, // STREAM_DTMF
2435         5, // STREAM_TTS
2436         5, // STREAM_ACCESSIBILITY
2437         5, // STREAM_ASSISTANT
2438     };
2439 
2440     /** @hide */
2441     @TestApi
streamToString(int stream)2442     public static @NonNull String streamToString(int stream) {
2443         if (stream >= 0 && stream < STREAM_NAMES.length) return STREAM_NAMES[stream];
2444         if (stream == AudioManager.USE_DEFAULT_STREAM_TYPE) return "USE_DEFAULT_STREAM_TYPE";
2445         return "UNKNOWN_STREAM_" + stream;
2446     }
2447 
2448     /** @hide The platform has no specific capabilities */
2449     public static final int PLATFORM_DEFAULT = 0;
2450     /** @hide The platform is voice call capable (a phone) */
2451     public static final int PLATFORM_VOICE = 1;
2452     /** @hide The platform is a television or a set-top box */
2453     public static final int PLATFORM_TELEVISION = 2;
2454 
2455     /**
2456      * @hide
2457      * Return the platform type that this is running on. One of:
2458      * <ul>
2459      * <li>{@link #PLATFORM_VOICE}</li>
2460      * <li>{@link #PLATFORM_TELEVISION}</li>
2461      * <li>{@link #PLATFORM_DEFAULT}</li>
2462      * </ul>
2463      */
getPlatformType(Context context)2464     public static int getPlatformType(Context context) {
2465         if (((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE))
2466                 .isVoiceCapable()) {
2467             return PLATFORM_VOICE;
2468         } else if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {
2469             return PLATFORM_TELEVISION;
2470         } else {
2471             return PLATFORM_DEFAULT;
2472         }
2473     }
2474 
2475     /**
2476      * @hide
2477      * @return whether the system uses a single volume stream.
2478      */
isSingleVolume(Context context)2479     public static boolean isSingleVolume(Context context) {
2480         boolean forceSingleVolume = context.getResources().getBoolean(
2481                 com.android.internal.R.bool.config_single_volume);
2482         return getPlatformType(context) == PLATFORM_TELEVISION || forceSingleVolume;
2483     }
2484 
2485     /**
2486      * @hide
2487      * Return a set of audio device types from a list of audio device attributes, which may
2488      * represent multiple audio device types.
2489      */
2490     @NonNull
generateAudioDeviceTypesSet( @onNull List<AudioDeviceAttributes> deviceList)2491     public static Set<Integer> generateAudioDeviceTypesSet(
2492             @NonNull List<AudioDeviceAttributes> deviceList) {
2493         Set<Integer> deviceTypes = new TreeSet<>();
2494         for (AudioDeviceAttributes device : deviceList) {
2495             deviceTypes.add(device.getInternalType());
2496         }
2497         return deviceTypes;
2498     }
2499 
2500     /**
2501      * @hide
2502      * Return the intersection of two audio device types collections.
2503      */
intersectionAudioDeviceTypes( @onNull Set<Integer> a, @NonNull Set<Integer> b)2504     public static Set<Integer> intersectionAudioDeviceTypes(
2505             @NonNull Set<Integer> a, @NonNull Set<Integer> b) {
2506         Set<Integer> intersection = new TreeSet<>(a);
2507         intersection.retainAll(b);
2508         return intersection;
2509     }
2510 
2511     /**
2512      * @hide
2513      * Return true if the audio device types collection only contains the given device type.
2514      */
isSingleAudioDeviceType(@onNull Set<Integer> types, int type)2515     public static boolean isSingleAudioDeviceType(@NonNull Set<Integer> types, int type) {
2516         return types.size() == 1 && types.contains(type);
2517     }
2518 
2519     /**
2520      * @hide
2521      * Return true if the audio device type is a Bluetooth LE Audio device.
2522      */
isLeAudioDeviceType(int type)2523     public static boolean isLeAudioDeviceType(int type) {
2524         return DEVICE_OUT_ALL_BLE_SET.contains(type);
2525     }
2526 
2527     /** @hide */
2528     public static final int DEFAULT_MUTE_STREAMS_AFFECTED =
2529             (1 << STREAM_MUSIC) |
2530             (1 << STREAM_RING) |
2531             (1 << STREAM_NOTIFICATION) |
2532             (1 << STREAM_SYSTEM) |
2533             (1 << STREAM_VOICE_CALL) |
2534             (1 << STREAM_BLUETOOTH_SCO);
2535 
2536     /**
2537      * @hide
2538      * Event posted by AudioTrack and AudioRecord JNI (JNIDeviceCallback) when routing changes.
2539      * Keep in sync with core/jni/android_media_DeviceCallback.h.
2540      */
2541     final static int NATIVE_EVENT_ROUTING_CHANGE = 1000;
2542 
2543     /**
2544      * @hide
2545      * Query the mixer attributes that can be set as preferred mixer attributes for the given
2546      * device.
2547      */
getSupportedMixerAttributes( int deviceId, @NonNull List<AudioMixerAttributes> mixerAttrs)2548     public static native int getSupportedMixerAttributes(
2549             int deviceId, @NonNull List<AudioMixerAttributes> mixerAttrs);
2550 
2551     /**
2552      * @hide
2553      * Set preferred mixer attributes for a given device when playing particular
2554      * audio attributes.
2555      */
setPreferredMixerAttributes( @onNull AudioAttributes attributes, int portId, int uid, @NonNull AudioMixerAttributes mixerAttributes)2556     public static native int setPreferredMixerAttributes(
2557             @NonNull AudioAttributes attributes,
2558             int portId,
2559             int uid,
2560             @NonNull AudioMixerAttributes mixerAttributes);
2561 
2562     /**
2563      * @hide
2564      * Get preferred mixer attributes that is previously set via
2565      * {link #setPreferredMixerAttributes}.
2566      */
getPreferredMixerAttributes( @onNull AudioAttributes attributes, int portId, List<AudioMixerAttributes> mixerAttributesList)2567     public static native int getPreferredMixerAttributes(
2568             @NonNull AudioAttributes attributes, int portId,
2569             List<AudioMixerAttributes> mixerAttributesList);
2570 
2571     /**
2572      * @hide
2573      * Clear preferred mixer attributes that is previously set via
2574      * {@link #setPreferredMixerAttributes}
2575      */
clearPreferredMixerAttributes( @onNull AudioAttributes attributes, int portId, int uid)2576     public static native int clearPreferredMixerAttributes(
2577             @NonNull AudioAttributes attributes, int portId, int uid);
2578 
2579 
2580     /**
2581      * Requests if the implementation supports controlling the latency modes
2582      * over the Bluetooth A2DP or LE Audio links.
2583      *
2584      * @return true if supported, false otherwise
2585      *
2586      * @hide
2587      */
supportsBluetoothVariableLatency()2588     public static native boolean supportsBluetoothVariableLatency();
2589 
2590     /**
2591      * Enables or disables the variable Bluetooth latency control mechanism in the
2592      * audio framework and the audio HAL. This does not apply to the latency mode control
2593      * on the spatializer output as this is a built-in feature.
2594      *
2595      * @hide
2596      */
setBluetoothVariableLatencyEnabled(boolean enabled)2597     public static native int setBluetoothVariableLatencyEnabled(boolean enabled);
2598 
2599     /**
2600      * Indicates if the variable Bluetooth latency control mechanism is enabled or disabled.
2601      * @hide
2602      */
isBluetoothVariableLatencyEnabled()2603     public static native boolean isBluetoothVariableLatencyEnabled();
2604 }
2605