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