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;
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 switch (deviceInfo.getType()) {
184 static boolean prepareAudioInput(
int id)
187 m_audioManager.getDevices(AudioManager.GET_DEVICES_INPUTS);
189 if (deviceInfo.getId() ==
id) {
190 switch (deviceInfo.getType())
197 return prepareAudioDevice(deviceInfo, AudioManager.MODE_NORMAL);
206 private static void setInputMuted(
boolean mute)
209 m_audioManager.setMicrophoneMute(mute);
212 private static boolean isMicrophoneMute()
214 return m_audioManager.isMicrophoneMute();
217 private static String audioDeviceTypeToString(
int type)
228 return "Built in earpiece";
230 return "Built in microphone";
232 return "Built in speaker";
246 return "Line analog";
248 return "Line digital";
252 return "USB accessory";
256 return "Wired headphones";
258 return "Wired headset";
262 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
267 return "Unknown-Type";
271 private static boolean isDeviceTypeSupported(
int type)
273 return audioDeviceTypeToString(
type)
277 private static final HashMap<Integer, Integer> priorityMap =
new HashMap<Integer, Integer>() {{
286 private static final int DEFAULT_PRIORITY = 4;
289 Comparator<AudioDeviceInfo> deviceTypeComparator =
new Comparator<AudioDeviceInfo>() {
292 return getPriority(device1) - getPriority(device2);
296 return priorityMap.getOrDefault(
device.getType(), DEFAULT_PRIORITY);
300 Arrays.sort(
devices, deviceTypeComparator);
305 ArrayList<AudioDeviceInfo> filteredDevices =
new ArrayList<>();
307 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
308 boolean builtInMicAdded =
false;
309 boolean bluetoothDeviceAdded =
false;
311 sortAudioDevices(audioDevices);
314 if (!isDeviceTypeSupported(deviceInfo.getType()))
319 if (builtInMicAdded) {
328 builtInMicAdded =
true;
329 }
else if (isBluetoothDevice(deviceInfo)) {
330 if (bluetoothDeviceAdded) {
336 bluetoothDeviceAdded =
true;
339 filteredDevices.add(deviceInfo);
343 return filteredDevices.toArray(
new AudioDeviceInfo[filteredDevices.size()]);
346 final private static int [] bluetoothTypes = {
348 AudioDeviceInfo.TYPE_BLUETOOTH_SCO
350 final private static int [] wiredTypes = {
352 AudioDeviceInfo.TYPE_WIRED_HEADPHONES
359 .flatMapToInt(Arrays::stream)
365 AudioManager.MODE_IN_COMMUNICATION : AudioManager.MODE_NORMAL;
370 return getCorrectModeIfContainsAnyOfType(audioDevices, bluetoothTypes);
375 return getCorrectModeIfContainsAnyOfType(audioDevices, wiredTypes);
380 return getCorrectModeIfContainsAnyOfType(audioDevices, bluetoothTypes, wiredTypes);
383 private static boolean prepareAudioOutput(
int id)
386 m_audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
388 if (deviceInfo.getId() ==
id) {
389 switch (deviceInfo.getType())
393 return prepareAudioDevice(deviceInfo, getModeForBluetooth(audioDevices));
395 return prepareAudioDevice(deviceInfo, getModeForSpeaker(audioDevices));
398 return prepareAudioDevice(deviceInfo, getModeForWired(audioDevices));
403 Log.w(TAG,
"Built in Earpiece may not work when "
404 +
"Wired Headphones are connected");
405 return prepareAudioDevice(deviceInfo, AudioManager.MODE_IN_CALL);
409 return prepareAudioDevice(deviceInfo, AudioManager.MODE_NORMAL);
426 if (isBluetoothDevice(
device)) {
430 boolean isSameType = communicationDevice.getType() ==
device.getType();
431 boolean isSameAddress = communicationDevice.getAddress().equals(
device.getAddress());
432 if (isSameType && isSameAddress)
433 return communicationDevice;
436 Log.w(TAG,
"No matching bluetooth output device found for " +
device);
443 if (m_currentCommunicationDeviceId == -1 ||
device ==
null) {
447 return m_currentCommunicationDeviceId ==
device.getId();
451 static void releaseAudioDevice(
int id) {
455 releaseAudioDevice(
device);
463 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
465 AudioDeviceInfo communicationDevice = getValidCommunicationDevice(deviceInfo);
466 if (!deviceIsCurrentCommunicationDevice(communicationDevice))
469 if (m_communicationDeviceCounter.decrementAndGet() == 0) {
470 m_audioManager.clearCommunicationDevice();
471 m_currentCommunicationDeviceId = -1;
473 }
else if (isBluetoothDevice(deviceInfo) && m_audioManager.isBluetoothScoOn()
474 && m_scoCounter.decrementAndGet() == 0) {
475 m_audioManager.stopBluetoothSco();
476 m_audioManager.setBluetoothScoOn(
false);
477 }
else if (deviceInfo.getType() ==
AudioDeviceInfo.TYPE_BUILTIN_SPEAKER
478 && m_speakerphoneCounter.decrementAndGet() == 0) {
479 m_audioManager.setSpeakerphoneOn(
false);
485 if (deviceInfo ==
null)
488 m_audioManager.setMode(
mode);
490 boolean isSink = deviceInfo.isSink();
492 m_currentOutputId = deviceInfo.getId();
494 boolean isBluetoothDevice = isBluetoothDevice(deviceInfo);
495 boolean isBluetoothSource = isBluetoothDevice && !isSink;
496 boolean isCommunicationMode = (
mode == AudioManager.MODE_IN_CALL
497 ||
mode == AudioManager.MODE_IN_COMMUNICATION);
499 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
500 if (!isBluetoothSource && !isCommunicationMode)
504 AudioDeviceInfo communicationDevice = getValidCommunicationDevice(deviceInfo);
505 if (communicationDevice ==
null) {
506 Log.w(TAG,
"No suitable communication device to set to enable communication via "
507 + deviceInfo.getId());
511 if (deviceIsCurrentCommunicationDevice(communicationDevice)) {
512 m_communicationDeviceCounter.incrementAndGet();
514 }
else if (m_audioManager.setCommunicationDevice(communicationDevice)) {
520 m_currentCommunicationDeviceId = communicationDevice.getId();
521 m_communicationDeviceCounter.set(1);
528 boolean isSpeakerphoneDevice = deviceInfo.getType() ==
AudioDeviceInfo.TYPE_BUILTIN_SPEAKER;
530 if (isBluetoothSource && m_scoCounter.getAndIncrement() == 0) {
531 m_audioManager.startBluetoothSco();
532 m_audioManager.setBluetoothScoOn(
true);
533 }
else if (isSpeakerphoneDevice
534 && m_speakerphoneCounter.getAndIncrement() == 0) {
537 m_audioManager.setSpeakerphoneOn(
true);
543 private static void streamSound()
545 byte data[] =
new byte[m_bufferSize];
546 while (m_isStreaming) {
547 m_recorder.read(
data, 0, m_bufferSize);
548 m_streamPlayer.play();
549 m_streamPlayer.write(
data, 0, m_bufferSize);
550 m_streamPlayer.stop();
554 private static void startSoundStreaming(
int inputId,
int outputId)
557 stopSoundStreaming();
559 m_recorder =
new AudioRecord(MediaRecorder.AudioSource.DEFAULT, m_sampleRate, m_channels,
560 m_audioFormat, m_bufferSize);
561 m_streamPlayer =
new AudioTrack(AudioManager.STREAM_MUSIC, m_sampleRate, m_channels,
562 m_audioFormat, m_bufferSize, AudioTrack.MODE_STREAM);
566 if (deviceInfo.getId() == outputId) {
567 m_streamPlayer.setPreferredDevice(deviceInfo);
568 }
else if (deviceInfo.getId() == inputId) {
569 m_recorder.setPreferredDevice(deviceInfo);
573 m_recorder.startRecording();
574 m_isStreaming =
true;
576 m_streamingThread =
new Thread(
new Runnable() {
583 m_streamingThread.start();
586 private static void stopSoundStreaming()
591 m_isStreaming =
false;
593 m_streamingThread.join();
594 m_streamingThread =
null;
595 }
catch (InterruptedException e) {
599 m_recorder.release();
600 m_streamPlayer.release();
601 m_streamPlayer =
null;
void AudioDeviceInfo()
[Audio callback capture setup peak meter]
IOBluetoothDevice * device
static const QString context()
QTCONCURRENT_RUN_NODISCARD auto run(QThreadPool *pool, Function &&f, Args &&...args)
GLsizei GLenum GLenum * types
GLint GLsizei GLsizei GLenum GLenum GLsizei void * data
[0]
static int compare(quint64 a, quint64 b)
static QInputDevice::DeviceType deviceType(const UINT cursorType)
manager put(request, myData, this, [this](QRestReply &reply) { if(reply.isSuccess()) })
[5]