4package org.qtproject.qt.android.multimedia;
6import java.util.ArrayList;
7import java.util.Arrays;
8import java.util.Comparator;
9import java.util.HashMap;
11import java.util.concurrent.CountDownLatch;
12import java.util.concurrent.atomic.AtomicInteger;
13import android.content.Context;
14import android.media.AudioDeviceCallback;
15import android.media.AudioDeviceInfo;
16import android.media.AudioFormat;
17import android.media.AudioManager;
18import android.media.AudioRecord;
19import android.media.AudioTrack;
20import android.media.MediaRecorder;
21import android.os.Build;
22import android.os.Handler;
23import android.os.HandlerThread;
24import android.util.Log;
26import org.qtproject.qt.android.UsedFromNativeCode;
28class QtAudioDeviceManager
30 private static final String TAG =
"QtAudioDeviceManager";
32 static private AudioManager m_audioManager =
null;
33 static private final AudioDevicesReceiver m_audioDevicesReceiver =
new AudioDevicesReceiver();
34 static private HandlerThread m_handlerThread =
null;
35 static private Handler m_handler =
null;
36 static private AudioRecord m_recorder =
null;
37 static private AudioTrack m_streamPlayer =
null;
38 static private Thread m_streamingThread =
null;
39 static private boolean m_isStreaming =
false;
40 static private boolean m_useSpeaker =
false;
41 static private final int m_sampleRate = 8000;
42 static private final int m_channels = AudioFormat.CHANNEL_CONFIGURATION_MONO;
43 static private final int m_audioFormat = AudioFormat.ENCODING_PCM_16BIT;
44 static private final int m_bufferSize = AudioRecord.getMinBufferSize(m_sampleRate, m_channels, m_audioFormat);
45 static private int m_currentOutputId = -1;
46 static private AtomicInteger m_scoCounter =
new AtomicInteger();
47 static private AtomicInteger m_communicationDeviceCounter =
new AtomicInteger();
48 static private AtomicInteger m_speakerphoneCounter =
new AtomicInteger();
49 static private int m_currentCommunicationDeviceId = -1;
57 static private long m_qAudioDevicesNativePtr = 0;
59 static native
void onAudioInputDevicesUpdated(
long qAudioDeviceNativePtr);
60 static native
void onAudioOutputDevicesUpdated(
long qAudioDeviceNativePtr);
62 static private void updateDeviceList() {
63 assert(m_handler.getLooper().isCurrentThread());
65 assert(m_qAudioDevicesNativePtr != 0);
67 if (m_currentOutputId != -1)
68 prepareAudioOutput(m_currentOutputId);
69 onAudioInputDevicesUpdated(m_qAudioDevicesNativePtr);
70 onAudioOutputDevicesUpdated(m_qAudioDevicesNativePtr);
73 private static class AudioDevicesReceiver
extends AudioDeviceCallback {
76 assert(m_handler.getLooper().isCurrentThread());
82 assert(m_handler.getLooper().isCurrentThread());
88 static void qAndroidAudioDevicesConstructed(
long nativePtr)
91 assert(m_handlerThread ==
null);
92 m_qAudioDevicesNativePtr = nativePtr;
93 m_handlerThread =
new HandlerThread(
"QtAudioDeviceCallbacks");
94 m_handlerThread.start();
95 m_handler =
new Handler(m_handlerThread.getLooper());
96 m_audioManager.registerAudioDeviceCallback(m_audioDevicesReceiver, m_handler);
100 static void qAndroidAudioDevicesDestroyed()
102 assert(!m_handler.getLooper().isCurrentThread());
106 final CountDownLatch latch =
new CountDownLatch(1);
107 final boolean postSuccess = m_handler.post(() -> {
108 m_audioManager.unregisterAudioDeviceCallback(m_audioDevicesReceiver);
109 assert(m_qAudioDevicesNativePtr != 0);
110 m_qAudioDevicesNativePtr = 0;
117 "Unable to post cleanup job to corresponding thread during " +
118 "QAndroidAudioDevices cleanup.");
124 }
catch (Exception e) {
127 "Unable to wait for cleanup job to finish on corresponding thread during" +
128 "QAndroidAudioDevices cleanup.");
131 m_handlerThread.quitSafely();
132 m_handlerThread =
null;
136 static void setContext(
Context context)
138 m_audioManager = (AudioManager)
context.getSystemService(
Context.AUDIO_SERVICE);
143 return getAudioDevices(AudioManager.GET_DEVICES_OUTPUTS);
148 return getAudioDevices(AudioManager.GET_DEVICES_INPUTS);
154 final AudioDeviceInfo[] audioDevices = m_audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS);
157 if (deviceInfo.getId() ==
id)
165 static int getDefaultSampleRate()
167 String sampleRate = m_audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE);
168 return Integer.parseInt(sampleRate);
174 return isBluetoothDeviceType(deviceInfo.getType());
178 static boolean isBluetoothDeviceId(
int id)
180 if (m_audioManager ==
null)
183 for (
AudioDeviceInfo deviceInfo : m_audioManager.getDevices(AudioManager.GET_DEVICES_ALL)) {
184 if (deviceInfo.getId() ==
id)
185 return isBluetoothDevice(deviceInfo);
191 static boolean prepareAudioInput(
int id)
194 m_audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS);
196 if (deviceInfo.getId() ==
id) {
197 if (isBluetoothDevice(deviceInfo))
198 return prepareAudioDevice(deviceInfo, AudioManager.MODE_NORMAL);
199 switch (deviceInfo.getType())
204 return prepareAudioDevice(deviceInfo, AudioManager.MODE_NORMAL);
213 private static boolean isBluetoothDeviceType(
int type)
215 return Arrays.stream(bluetoothTypes).anyMatch(
t ->
t ==
type);
218 private static void setInputMuted(
boolean mute)
221 m_audioManager.setMicrophoneMute(mute);
224 private static boolean isMicrophoneMute()
226 return m_audioManager.isMicrophoneMute();
229 private static String audioDeviceTypeToString(
int type)
237 return "Built in earpiece";
239 return "Built in microphone";
241 return "Built in speaker";
255 return "Line analog";
257 return "Line digital";
261 return "USB accessory";
265 return "Wired headphones";
267 return "Wired headset";
270 if (isBluetoothDeviceType(
type))
274 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
279 return "Unknown-Type";
283 private static boolean isDeviceTypeSupported(
int type)
285 return audioDeviceTypeToString(
type)
289 private static final HashMap<Integer, Integer> priorityMap =
new HashMap<Integer, Integer>() {{
297 private static final int BLUETOOTH_PRIORITY = 2;
298 private static final int DEFAULT_PRIORITY = 5;
300 private static int getDevicePriority(
int type) {
302 if (priority !=
null)
305 if (isBluetoothDeviceType(
type))
306 return BLUETOOTH_PRIORITY;
308 return DEFAULT_PRIORITY;
312 Comparator<AudioDeviceInfo> deviceTypeComparator =
new Comparator<AudioDeviceInfo>() {
315 return getDevicePriority(device1.getType()) - getDevicePriority(device2.getType());
319 Arrays.sort(
devices, deviceTypeComparator);
324 ArrayList<AudioDeviceInfo> filteredDevices =
new ArrayList<>();
326 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
327 boolean builtInMicAdded =
false;
328 boolean bluetoothDeviceAdded =
false;
330 sortAudioDevices(audioDevices);
333 if (!isDeviceTypeSupported(deviceInfo.getType()))
338 if (builtInMicAdded) {
347 builtInMicAdded =
true;
348 }
else if (isBluetoothDevice(deviceInfo)) {
349 if (bluetoothDeviceAdded) {
355 bluetoothDeviceAdded =
true;
358 filteredDevices.add(deviceInfo);
362 return filteredDevices.toArray(
new AudioDeviceInfo[filteredDevices.size()]);
365 final private static int [] bluetoothTypes = createBluetoothTypes();
367 private static int[] createBluetoothTypes()
369 ArrayList<Integer>
types =
new ArrayList<>(Arrays.asList(
372 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
376 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
378 return types.stream().mapToInt(Integer::intValue).toArray();
381 final private static int [] wiredTypes = {
383 AudioDeviceInfo.TYPE_WIRED_HEADPHONES
390 .flatMapToInt(Arrays::stream)
396 AudioManager.MODE_IN_COMMUNICATION : AudioManager.MODE_NORMAL;
401 return getCorrectModeIfContainsAnyOfType(audioDevices, bluetoothTypes);
406 return getCorrectModeIfContainsAnyOfType(audioDevices, wiredTypes);
411 return getCorrectModeIfContainsAnyOfType(audioDevices, bluetoothTypes, wiredTypes);
414 private static boolean prepareAudioOutput(
int id)
417 m_audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
419 if (deviceInfo.getId() ==
id) {
420 if (isBluetoothDevice(deviceInfo))
421 return prepareAudioDevice(deviceInfo, getModeForBluetooth(audioDevices));
422 switch (deviceInfo.getType())
425 return prepareAudioDevice(deviceInfo, getModeForSpeaker(audioDevices));
428 return prepareAudioDevice(deviceInfo, getModeForWired(audioDevices));
433 Log.w(TAG,
"Built in Earpiece may not work when "
434 +
"Wired Headphones are connected");
435 return prepareAudioDevice(deviceInfo, AudioManager.MODE_IN_CALL);
439 return prepareAudioDevice(deviceInfo, AudioManager.MODE_NORMAL);
456 if (isBluetoothDevice(
device)) {
458 List<AudioDeviceInfo> communicationDevices = m_audioManager.getAvailableCommunicationDevices();
460 boolean isSameType = communicationDevice.getType() ==
device.getType();
461 boolean isSameAddress = communicationDevice.getAddress().equals(
device.getAddress());
462 if (isSameType && isSameAddress)
463 return communicationDevice;
466 Log.w(TAG,
"No matching bluetooth output device found for " +
device);
473 if (m_currentCommunicationDeviceId == -1 ||
device ==
null) {
477 return m_currentCommunicationDeviceId ==
device.getId();
481 static void releaseAudioDevice(
int id) {
485 releaseAudioDevice(
device);
493 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
495 AudioDeviceInfo communicationDevice = getValidCommunicationDevice(deviceInfo);
496 if (!deviceIsCurrentCommunicationDevice(communicationDevice))
499 if (m_communicationDeviceCounter.decrementAndGet() == 0) {
500 m_audioManager.clearCommunicationDevice();
501 m_currentCommunicationDeviceId = -1;
503 }
else if (isBluetoothDevice(deviceInfo) && m_audioManager.isBluetoothScoOn()
504 && m_scoCounter.decrementAndGet() == 0) {
505 m_audioManager.stopBluetoothSco();
506 m_audioManager.setBluetoothScoOn(
false);
507 }
else if (deviceInfo.getType() ==
AudioDeviceInfo.TYPE_BUILTIN_SPEAKER
508 && m_speakerphoneCounter.decrementAndGet() == 0) {
509 m_audioManager.setSpeakerphoneOn(
false);
515 if (deviceInfo ==
null)
518 m_audioManager.setMode(
mode);
520 boolean isSink = deviceInfo.isSink();
522 m_currentOutputId = deviceInfo.getId();
524 boolean isBluetoothDevice = isBluetoothDevice(deviceInfo);
525 boolean isBluetoothSource = isBluetoothDevice && !isSink;
526 boolean isCommunicationMode = (
mode == AudioManager.MODE_IN_CALL
527 ||
mode == AudioManager.MODE_IN_COMMUNICATION);
529 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
530 if (!isBluetoothSource && !isCommunicationMode)
534 AudioDeviceInfo communicationDevice = getValidCommunicationDevice(deviceInfo);
535 if (communicationDevice ==
null) {
536 Log.w(TAG,
"No suitable communication device to set to enable communication via "
537 + deviceInfo.getId());
541 if (deviceIsCurrentCommunicationDevice(communicationDevice)) {
542 m_communicationDeviceCounter.incrementAndGet();
544 }
else if (m_audioManager.setCommunicationDevice(communicationDevice)) {
550 m_currentCommunicationDeviceId = communicationDevice.getId();
551 m_communicationDeviceCounter.set(1);
558 boolean isSpeakerphoneDevice = deviceInfo.getType() ==
AudioDeviceInfo.TYPE_BUILTIN_SPEAKER;
560 if (isBluetoothSource && m_scoCounter.getAndIncrement() == 0) {
561 m_audioManager.startBluetoothSco();
562 m_audioManager.setBluetoothScoOn(
true);
563 }
else if (isSpeakerphoneDevice
564 && m_speakerphoneCounter.getAndIncrement() == 0) {
567 m_audioManager.setSpeakerphoneOn(
true);
573 private static void streamSound()
575 byte data[] =
new byte[m_bufferSize];
576 while (m_isStreaming) {
577 m_recorder.read(
data, 0, m_bufferSize);
578 m_streamPlayer.play();
579 m_streamPlayer.write(
data, 0, m_bufferSize);
580 m_streamPlayer.stop();
584 private static void startSoundStreaming(
int inputId,
int outputId)
587 stopSoundStreaming();
589 m_recorder =
new AudioRecord(MediaRecorder.AudioSource.DEFAULT, m_sampleRate, m_channels,
590 m_audioFormat, m_bufferSize);
591 m_streamPlayer =
new AudioTrack(AudioManager.STREAM_MUSIC, m_sampleRate, m_channels,
592 m_audioFormat, m_bufferSize, AudioTrack.MODE_STREAM);
596 if (deviceInfo.getId() == outputId) {
597 m_streamPlayer.setPreferredDevice(deviceInfo);
598 }
else if (deviceInfo.getId() == inputId) {
599 m_recorder.setPreferredDevice(deviceInfo);
603 m_recorder.startRecording();
604 m_isStreaming =
true;
606 m_streamingThread =
new Thread(
new Runnable() {
613 m_streamingThread.start();
616 private static void stopSoundStreaming()
621 m_isStreaming =
false;
623 m_streamingThread.join();
624 m_streamingThread =
null;
625 }
catch (InterruptedException e) {
629 m_recorder.release();
630 m_streamPlayer.release();
631 m_streamPlayer =
null;
void AudioDeviceInfo()
[Audio callback capture setup peak meter]
IOBluetoothDevice * device
int compare(const FunctionNode *f1, const FunctionNode *f2)
QTCONCURRENT_RUN_NODISCARD auto run(QThreadPool *pool, Function &&f, Args &&...args)
GLsizei GLenum GLenum * types
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
[0]
manager put(request, myData, this, [this](QRestReply &reply) { if(reply.isSuccess()) })
[5]