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";
254 return "Wired headphones";
256 return "Wired headset";
260 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
265 return "Unknown-Type";
269 private static final HashMap<Integer, Integer> priorityMap =
new HashMap<Integer, Integer>() {{
276 private static final int DEFAULT_PRIORITY = 4;
279 Comparator<AudioDeviceInfo> deviceTypeComparator =
new Comparator<AudioDeviceInfo>() {
282 return getPriority(device1) - getPriority(device2);
286 return priorityMap.getOrDefault(
device.getType(), DEFAULT_PRIORITY);
290 Arrays.sort(
devices, deviceTypeComparator);
295 ArrayList<AudioDeviceInfo> filteredDevices =
new ArrayList<>();
297 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
298 boolean builtInMicAdded =
false;
299 boolean bluetoothDeviceAdded =
false;
301 sortAudioDevices(audioDevices);
310 if (builtInMicAdded) {
319 builtInMicAdded =
true;
320 }
else if (isBluetoothDevice(deviceInfo)) {
321 if (bluetoothDeviceAdded) {
327 bluetoothDeviceAdded =
true;
330 filteredDevices.add(deviceInfo);
334 return filteredDevices.toArray(
new AudioDeviceInfo[filteredDevices.size()]);
337 final private static int [] bluetoothTypes = {
339 AudioDeviceInfo.TYPE_BLUETOOTH_SCO
341 final private static int [] wiredTypes = {
343 AudioDeviceInfo.TYPE_WIRED_HEADPHONES
350 .flatMapToInt(Arrays::stream)
356 AudioManager.MODE_IN_COMMUNICATION : AudioManager.MODE_NORMAL;
361 return getCorrectModeIfContainsAnyOfType(audioDevices, bluetoothTypes);
366 return getCorrectModeIfContainsAnyOfType(audioDevices, wiredTypes);
371 return getCorrectModeIfContainsAnyOfType(audioDevices, bluetoothTypes, wiredTypes);
374 private static boolean prepareAudioOutput(
int id)
377 m_audioManager.getDevices(AudioManager.GET_DEVICES_OUTPUTS);
379 if (deviceInfo.getId() ==
id) {
380 switch (deviceInfo.getType())
384 return prepareAudioDevice(deviceInfo, getModeForBluetooth(audioDevices));
386 return prepareAudioDevice(deviceInfo, getModeForSpeaker(audioDevices));
389 return prepareAudioDevice(deviceInfo, getModeForWired(audioDevices));
394 Log.w(TAG,
"Built in Earpiece may not work when "
395 +
"Wired Headphones are connected");
396 return prepareAudioDevice(deviceInfo, AudioManager.MODE_IN_CALL);
400 return prepareAudioDevice(deviceInfo, AudioManager.MODE_NORMAL);
417 if (isBluetoothDevice(
device)) {
421 boolean isSameType = communicationDevice.getType() ==
device.getType();
422 boolean isSameAddress = communicationDevice.getAddress().equals(
device.getAddress());
423 if (isSameType && isSameAddress)
424 return communicationDevice;
427 Log.w(TAG,
"No matching bluetooth output device found for " +
device);
434 if (m_currentCommunicationDeviceId == -1 ||
device ==
null) {
438 return m_currentCommunicationDeviceId ==
device.getId();
442 static void releaseAudioDevice(
int id) {
446 releaseAudioDevice(
device);
454 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
456 AudioDeviceInfo communicationDevice = getValidCommunicationDevice(deviceInfo);
457 if (!deviceIsCurrentCommunicationDevice(communicationDevice))
460 if (m_communicationDeviceCounter.decrementAndGet() == 0) {
461 m_audioManager.clearCommunicationDevice();
462 m_currentCommunicationDeviceId = -1;
464 }
else if (isBluetoothDevice(deviceInfo) && m_audioManager.isBluetoothScoOn()
465 && m_scoCounter.decrementAndGet() == 0) {
466 m_audioManager.stopBluetoothSco();
467 m_audioManager.setBluetoothScoOn(
false);
468 }
else if (deviceInfo.getType() ==
AudioDeviceInfo.TYPE_BUILTIN_SPEAKER
469 && m_speakerphoneCounter.decrementAndGet() == 0) {
470 m_audioManager.setSpeakerphoneOn(
false);
476 if (deviceInfo ==
null)
479 m_audioManager.setMode(
mode);
481 boolean isSink = deviceInfo.isSink();
483 m_currentOutputId = deviceInfo.getId();
485 boolean isBluetoothDevice = isBluetoothDevice(deviceInfo);
486 boolean isBluetoothSource = isBluetoothDevice && !isSink;
487 boolean isCommunicationMode = (
mode == AudioManager.MODE_IN_CALL
488 ||
mode == AudioManager.MODE_IN_COMMUNICATION);
490 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
491 if (!isBluetoothSource && !isCommunicationMode)
495 AudioDeviceInfo communicationDevice = getValidCommunicationDevice(deviceInfo);
496 if (communicationDevice ==
null) {
497 Log.w(TAG,
"No suitable communication device to set to enable communication via "
498 + deviceInfo.getId());
502 if (deviceIsCurrentCommunicationDevice(communicationDevice)) {
503 m_communicationDeviceCounter.incrementAndGet();
505 }
else if (m_audioManager.setCommunicationDevice(communicationDevice)) {
511 m_currentCommunicationDeviceId = communicationDevice.getId();
512 m_communicationDeviceCounter.set(1);
519 boolean isSpeakerphoneDevice = deviceInfo.getType() ==
AudioDeviceInfo.TYPE_BUILTIN_SPEAKER;
521 if (isBluetoothSource && m_scoCounter.getAndIncrement() == 0) {
522 m_audioManager.startBluetoothSco();
523 m_audioManager.setBluetoothScoOn(
true);
524 }
else if (isSpeakerphoneDevice
525 && m_speakerphoneCounter.getAndIncrement() == 0) {
528 m_audioManager.setSpeakerphoneOn(
true);
534 private static void streamSound()
536 byte data[] =
new byte[m_bufferSize];
537 while (m_isStreaming) {
538 m_recorder.read(
data, 0, m_bufferSize);
539 m_streamPlayer.play();
540 m_streamPlayer.write(
data, 0, m_bufferSize);
541 m_streamPlayer.stop();
545 private static void startSoundStreaming(
int inputId,
int outputId)
548 stopSoundStreaming();
550 m_recorder =
new AudioRecord(MediaRecorder.AudioSource.DEFAULT, m_sampleRate, m_channels,
551 m_audioFormat, m_bufferSize);
552 m_streamPlayer =
new AudioTrack(AudioManager.STREAM_MUSIC, m_sampleRate, m_channels,
553 m_audioFormat, m_bufferSize, AudioTrack.MODE_STREAM);
557 if (deviceInfo.getId() == outputId) {
558 m_streamPlayer.setPreferredDevice(deviceInfo);
559 }
else if (deviceInfo.getId() == inputId) {
560 m_recorder.setPreferredDevice(deviceInfo);
564 m_recorder.startRecording();
565 m_isStreaming =
true;
567 m_streamingThread =
new Thread(
new Runnable() {
574 m_streamingThread.start();
577 private static void stopSoundStreaming()
582 m_isStreaming =
false;
584 m_streamingThread.join();
585 m_streamingThread =
null;
586 }
catch (InterruptedException e) {
590 m_recorder.release();
591 m_streamPlayer.release();
592 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]