/
AdvancedAudioDevice.java
1173 lines (989 loc) · 43.4 KB
/
AdvancedAudioDevice.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.tokbox.sample.advancedaudiodriver;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder.AudioSource;
import android.media.audiofx.AcousticEchoCanceler;
import android.media.audiofx.NoiseSuppressor;
import android.os.Build;
import android.os.Handler;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.opentok.android.BaseAudioDevice;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
class AdvancedAudioDevice extends BaseAudioDevice {
private final static String TAG = AdvancedAudioDevice.class.getSimpleName();
private static final int NUM_CHANNELS_CAPTURING = 1;
private static final int NUM_CHANNELS_RENDERING = 1;
private static final int STEREO_CHANNELS = 2;
private static final int DEFAULT_SAMPLE_RATE = 44100;
private static final int SAMPLE_SIZE_IN_BYTES = 2;
private static final int DEFAULT_SAMPLES_PER_BUFFER = (DEFAULT_SAMPLE_RATE / 1000) * 10; // 10ms
private static final int DEFAULT_BUFFER_SIZE =
SAMPLE_SIZE_IN_BYTES * DEFAULT_SAMPLES_PER_BUFFER * STEREO_CHANNELS;
// Max 10 ms @ 48 kHz - Stereo
private static final int DEFAULT_START_RENDERER_AND_CAPTURER_DELAY = 5 * 1000;
private static final int DEFAULT_BLUETOOTH_SCO_START_DELAY = 2000;
private Context context;
private AudioTrack audioTrack;
private AudioRecord audioRecord;
// Capture & render buffers
private ByteBuffer playBuffer;
private ByteBuffer recBuffer;
private byte[] tempBufPlay;
private byte[] tempBufRec;
private final ReentrantLock rendererLock = new ReentrantLock(true);
private final Condition renderEvent = rendererLock.newCondition();
private volatile boolean isRendering = false;
private volatile boolean shutdownRenderThread = false;
private final ReentrantLock captureLock = new ReentrantLock(true);
private final Condition captureEvent = captureLock.newCondition();
private volatile boolean isCapturing = false;
private volatile boolean shutdownCaptureThread = false;
private AudioSettings captureSettings;
private AudioSettings rendererSettings;
private NoiseSuppressor noiseSuppressor;
private AcousticEchoCanceler echoCanceler;
// Capturing delay estimation
private int estimatedCaptureDelay = 0;
// Rendering delay estimation
private int bufferedPlaySamples = 0;
private int playPosition = 0;
private int estimatedRenderDelay = 0;
private AudioManager audioManager;
private AudioManagerMode audioManagerMode = new AudioManagerMode();
private int outputSamplingRate = DEFAULT_SAMPLE_RATE;
private int captureSamplingRate = DEFAULT_SAMPLE_RATE;
private int samplesPerBuffer = DEFAULT_SAMPLES_PER_BUFFER;
// For headset receiver.
private static final String HEADSET_PLUG_STATE_KEY = "state";
private BluetoothState bluetoothState;
private BluetoothAdapter bluetoothAdapter;
private BluetoothProfile bluetoothProfile;
private final Object bluetoothLock = new Object();
private TelephonyManager telephonyManager;
private boolean isPaused;
private enum OutputType {
SPEAKER_PHONE,
EAR_PIECE,
HEAD_PHONES,
BLUETOOTH
}
private OutputType audioOutputType = OutputType.SPEAKER_PHONE;
private OutputType getOutputType() {
return audioOutputType;
}
private void setOutputType(OutputType type) {
audioOutputType = type;
}
private static class AudioManagerMode {
private int oldMode;
private int naquire;
AudioManagerMode() {
oldMode = 0;
naquire = 0;
}
void acquireMode(AudioManager audioManager) {
if (0 == naquire++) {
oldMode = audioManager.getMode();
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
}
}
void releaseMode(AudioManager audioManager) {
if (0 == --naquire) {
audioManager.setMode(oldMode);
}
}
}
private static class AudioState {
private int lastStreamVolume = 0;
private int lastKnownFocusState = 0;
private OutputType lastOutputType = OutputType.SPEAKER_PHONE;
int getLastStreamVolume() {
return lastStreamVolume;
}
void setLastStreamVolume(int lastStreamVolume) {
this.lastStreamVolume = lastStreamVolume;
}
int getLastKnownFocusState() {
return lastKnownFocusState;
}
void setLastKnownFocusState(int lastKnownFocusState) {
this.lastKnownFocusState = lastKnownFocusState;
}
OutputType getLastOutputType() {
return this.lastOutputType;
}
void setLastOutputType(OutputType lastOutputType) {
this.lastOutputType = lastOutputType;
}
}
private AudioState audioState = new AudioState();
private BroadcastReceiver headsetBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "headsetBroadcastReceiver.onReceive()");
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
if (intent.getIntExtra(HEADSET_PLUG_STATE_KEY, 0) == 1) {
Log.d(TAG, "headsetBroadcastReceiver.onReceive(): Headphones connected");
audioState.setLastOutputType(getOutputType());
setOutputType(OutputType.HEAD_PHONES);
audioManager.setSpeakerphoneOn(false);
audioManager.setBluetoothScoOn(false);
} else {
Log.d(TAG, "headsetBroadcastReceiver.onReceive(): Headphones disconnected");
if (getOutputType() == OutputType.HEAD_PHONES) {
if (audioState.getLastOutputType() == OutputType.BLUETOOTH &&
BluetoothState.Connected == bluetoothState) {
audioManager.setBluetoothScoOn(true);
startBluetoothSco();
setOutputType(OutputType.BLUETOOTH);
} else {
if (audioState.getLastOutputType() == OutputType.SPEAKER_PHONE) {
setOutputType(OutputType.SPEAKER_PHONE);
audioManager.setSpeakerphoneOn(true);
}
if (audioState.getLastOutputType() == OutputType.EAR_PIECE) {
setOutputType(OutputType.EAR_PIECE);
audioManager.setSpeakerphoneOn(false);
}
}
}
}
}
}
};
// Intent broadcast receiver which handles changes in Bluetooth device availability.
// Detects headset changes and Bluetooth SCO state changes.
private final BroadcastReceiver bluetoothHeadsetReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED)) {
final int state = intent.getIntExtra(
BluetoothHeadset.EXTRA_STATE, -1);
switch (state) {
case BluetoothHeadset.STATE_AUDIO_DISCONNECTED:
Log.d(TAG, "bluetoothHeadsetReceiver.onReceive(): STATE_AUDIO_DISCONNECTED");
break;
case BluetoothHeadset.STATE_AUDIO_CONNECTING:
Log.d(TAG, "bluetoothHeadsetReceiver.onReceive(): STATE_AUDIO_CONNECTING");
break;
case BluetoothHeadset.STATE_AUDIO_CONNECTED:
Log.d(TAG, "bluetoothHeadsetReceiver.onReceive(): STATE_AUDIO_CONNECTED");
break;
default:
break;
}
}
}
};
private void restoreAudioAfterBluetoothDisconnect() {
if (audioManager.isWiredHeadsetOn()) {
setOutputType(OutputType.HEAD_PHONES);
audioManager.setSpeakerphoneOn(false);
} else {
if (audioState.getLastOutputType() == OutputType.SPEAKER_PHONE) {
setOutputType(OutputType.SPEAKER_PHONE);
super.setOutputMode(OutputMode.SpeakerPhone);
audioManager.setSpeakerphoneOn(true);
} else if (audioState.getLastOutputType() == OutputType.EAR_PIECE) {
setOutputType(OutputType.EAR_PIECE);
super.setOutputMode(OutputMode.Handset);
audioManager.setSpeakerphoneOn(false);
}
}
}
private final BroadcastReceiver bluetoothBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (null != action && action.equals(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)) {
int state = intent.getIntExtra(BluetoothHeadset.EXTRA_STATE, -1);
switch (state) {
case BluetoothHeadset.STATE_CONNECTED:
Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): BluetoothHeadset.STATE_CONNECTED");
new Handler().postDelayed(() -> connectBluetooth(), DEFAULT_BLUETOOTH_SCO_START_DELAY);
break;
case BluetoothHeadset.STATE_DISCONNECTING:
Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): BluetoothHeadset.STATE_DISCONNECTING");
break;
case BluetoothHeadset.STATE_DISCONNECTED:
Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): BluetoothHeadset.STATE_DISCONNECTED");
stopBluetoothSco();
audioManager.setBluetoothScoOn(false);
break;
default:
break;
}
} else if (null != action && action.equals(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED)) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
switch (state) {
case AudioManager.SCO_AUDIO_STATE_CONNECTED:
Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): AudioManager.SCO_AUDIO_STATE_CONNECTED");
bluetoothState = BluetoothState.Connected;
setOutputType(OutputType.BLUETOOTH);
AdvancedAudioDevice.super.setOutputMode(OutputMode.Handset); // When BT is connected it replaces the handset
break;
case AudioManager.SCO_AUDIO_STATE_ERROR:
Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): AudioManager.SCO_AUDIO_STATE_ERROR");
break;
case AudioManager.SCO_AUDIO_STATE_DISCONNECTED:
Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): AudioManager.SCO_AUDIO_STATE_DISCONNECTED");
restoreAudioAfterBluetoothDisconnect();
bluetoothState = BluetoothState.Disconnected;
break;
case AudioManager.SCO_AUDIO_STATE_CONNECTING:
Log.d(TAG, "bluetoothBroadcastReceiver.onReceive(): AudioManager.SCO_AUDIO_STATE_CONNECTING");
break;
default:
break;
}
}
}
};
private PhoneStateListener phoneStateListener = new PhoneStateListener(){
@Override
public void onCallStateChanged(int state, String incomingNumber) {
Log.d(TAG, "PhoneStateListener.onCallStateChanged()");
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_IDLE:
//Initial state
Log.d(TAG, "PhoneStateListener.onCallStateChanged(): TelephonyManager.CALL_STATE_IDLE");
// We delay a bit here the action of start capturing and rendering again because Android has to
// finish routing audio to the earpiece. It is an Android behaviour we have to deal with.
new Handler().postDelayed(() -> startRendererAndCapturer(), DEFAULT_START_RENDERER_AND_CAPTURER_DELAY);
break;
case TelephonyManager.CALL_STATE_RINGING:
// Incoming call Ringing
Log.d(TAG, "PhoneStateListener.onCallStateChanged(): TelephonyManager.CALL_STATE_RINGING");
stopRendererAndCapturer();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
// Outgoing Call | Accepted incoming call
Log.d(TAG, "PhoneStateListener.onCallStateChanged(): TelephonyManager.CALL_STATE_OFFHOOK");
stopRendererAndCapturer();
break;
default:
Log.d(TAG, "PhoneStateListener.onCallStateChanged() default");
break;
}
}
};
private boolean wasRendering;
private boolean wasCapturing;
private void startRendererAndCapturer() {
if (wasRendering) {
startRenderer();
}
if (wasCapturing) {
startCapturer();
}
}
private void stopRendererAndCapturer() {
if (isRendering) {
stopRenderer();
wasRendering = true;
}
if (isCapturing) {
stopCapturer();
wasCapturing = true;
}
}
private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + ")");
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): ");
//Check if coming back from a complete loss or a transient loss
switch (audioState.getLastKnownFocusState()) {
case AudioManager.AUDIOFOCUS_LOSS:
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL,
audioState.getLastStreamVolume(), 0);
break;
default:
Log.d(TAG, "focusChange = " + focusChange);
break;
}
setOutputType(audioState.getLastOutputType());
connectBluetooth();
forceInvokeConnectBluetooth();
break;
case AudioManager.AUDIOFOCUS_LOSS:
// -1 Loss for indefinite time
Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): AudioManager.AUDIOFOCUS_LOSS");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// -2 Loss for short duration
Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): AudioManager.AUDIOFOCUS_LOSS_TRANSIENT");
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// -3 stay quite in background
Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
audioState.setLastStreamVolume(audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL));
audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 0, 0);
break;
case AudioManager.AUDIOFOCUS_NONE:
Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): AudioManager.AUDIOFOCUS_NONE");
break;
default:
Log.d(TAG, "AudioManager.OnAudioFocusChangeListener.onAudioFocusChange(" + focusChange + "): default");
break;
}
audioState.setLastOutputType(getOutputType());
audioState.setLastKnownFocusState(focusChange);
}
};
private void connectBluetooth() {
Log.d(TAG, "connectBluetooth() called");
audioManager.setBluetoothScoOn(true);
startBluetoothSco();
}
public AdvancedAudioDevice(Context context) {
this.context = context;
try {
recBuffer = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
tempBufRec = new byte[DEFAULT_BUFFER_SIZE];
audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothProfile = null;
int outputBufferSize = DEFAULT_BUFFER_SIZE;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
try {
outputSamplingRate = Integer.parseInt(
audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_SAMPLE_RATE));
} finally {
if (outputSamplingRate == 0) {
outputSamplingRate = DEFAULT_SAMPLE_RATE;
}
}
try {
samplesPerBuffer = Integer.parseInt(
audioManager.getProperty(AudioManager.PROPERTY_OUTPUT_FRAMES_PER_BUFFER));
outputBufferSize = SAMPLE_SIZE_IN_BYTES
* samplesPerBuffer
* NUM_CHANNELS_RENDERING;
} catch(NumberFormatException numberFormatException) {
Log.e(TAG, "DefaultAudioDevice(): " + numberFormatException.getMessage());
} finally {
if (outputBufferSize == 0) {
outputBufferSize = DEFAULT_BUFFER_SIZE;
samplesPerBuffer = DEFAULT_SAMPLES_PER_BUFFER;
}
}
}
try {
playBuffer = ByteBuffer.allocateDirect(outputBufferSize);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
tempBufPlay = new byte[outputBufferSize];
captureSettings = new AudioSettings(captureSamplingRate, NUM_CHANNELS_CAPTURING);
rendererSettings = new AudioSettings(outputSamplingRate, NUM_CHANNELS_RENDERING);
try {
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
} catch (SecurityException e) {
e.printStackTrace();
}
isPhoneStateListenerRegistered = false;
wasCapturing = false;
wasRendering = false;
isPaused = false;
Log.d(TAG, "DefaultAudioDevice() exit " + this);
}
@Override
public boolean initCapturer() {
// get the minimum buffer size that can be used
int minRecBufSize = AudioRecord.getMinBufferSize(
captureSettings.getSampleRate(),
NUM_CHANNELS_CAPTURING == 1 ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT
);
// double size to be more safe
int recBufSize = minRecBufSize * 2;
// release the object
if (noiseSuppressor != null) {
noiseSuppressor.release();
noiseSuppressor = null;
}
if (echoCanceler != null) {
echoCanceler.release();
echoCanceler = null;
}
if (audioRecord != null) {
audioRecord.release();
audioRecord = null;
}
try {
int channelConfig = NUM_CHANNELS_CAPTURING == 1 ? AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO;
audioRecord = new AudioRecord(
AudioSource.VOICE_COMMUNICATION,
captureSettings.getSampleRate(),
channelConfig,
AudioFormat.ENCODING_PCM_16BIT, recBufSize);
if (NoiseSuppressor.isAvailable()) {
noiseSuppressor = NoiseSuppressor.create(audioRecord.getAudioSessionId());
}
if (AcousticEchoCanceler.isAvailable()) {
echoCanceler = AcousticEchoCanceler.create(audioRecord.getAudioSessionId());
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
// Check that the audioRecord is ready to be used.
if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
String errorDescription = String.format(Locale.getDefault(), "Audio capture could not be initialized.\n" +
"Requested parameters\n" +
" Sampling Rate: %d\n" +
" Number of channels: %d\n" +
" Buffer size: %d\n",
captureSettings.getSampleRate(),
captureSettings.getNumChannels(),
minRecBufSize);
Log.e(TAG, errorDescription);
throw new RuntimeException(errorDescription);
}
registerPhoneStateListener();
shutdownCaptureThread = false;
new Thread(captureThread).start();
return true;
}
@Override
public boolean destroyCapturer() {
captureLock.lock();
// release the object
if (null != echoCanceler) {
echoCanceler.release();
echoCanceler = null;
}
if (null != noiseSuppressor) {
noiseSuppressor.release();
noiseSuppressor = null;
}
audioRecord.release();
audioRecord = null;
shutdownCaptureThread = true;
captureEvent.signal();
captureLock.unlock();
unRegisterPhoneStateListener();
wasCapturing = false;
return true;
}
public int getEstimatedCaptureDelay() {
return estimatedCaptureDelay;
}
@Override
public boolean startCapturer() {
if (audioRecord == null) {
throw new IllegalStateException("startCapturer(): startRecording() called on an "
+ "uninitialized AudioRecord");
}
try {
audioRecord.startRecording();
} catch (IllegalStateException e) {
throw new RuntimeException(e.getMessage());
}
captureLock.lock();
isCapturing = true;
captureEvent.signal();
captureLock.unlock();
return true;
}
@Override
public boolean stopCapturer() {
if (audioRecord == null) {
throw new IllegalStateException("stopCapturer(): stop() called on an uninitialized AudioRecord");
}
captureLock.lock();
try {
// Only stop if we are recording.
if (audioRecord.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) {
audioRecord.stop();
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
// Ensure we always unlock
isCapturing = false;
captureLock.unlock();
}
return true;
}
private Runnable captureThread = () -> {
int samplesToRec = captureSamplingRate / 100;
int samplesRead;
try {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
} catch (Exception e) {
Log.e(TAG, "android.os.Process.setThreadPriority(): " + e.getMessage());
}
while (!shutdownCaptureThread) {
captureLock.lock();
try {
if (!this.isCapturing) {
captureEvent.await();
continue;
} else {
if (audioRecord == null) {
continue;
}
int lengthInBytes = (samplesToRec << 1) * NUM_CHANNELS_CAPTURING;
int readBytes = audioRecord.read(tempBufRec, 0, lengthInBytes);
if (readBytes >= 0) {
recBuffer.rewind();
recBuffer.put(tempBufRec);
samplesRead = (readBytes >> 1) / NUM_CHANNELS_CAPTURING;
} else {
switch (readBytes) {
case AudioRecord.ERROR_BAD_VALUE:
throw new RuntimeException("captureThread(): AudioRecord.ERROR_BAD_VALUE");
case AudioRecord.ERROR_INVALID_OPERATION:
throw new RuntimeException("captureThread(): AudioRecord.ERROR_INVALID_OPERATION");
case AudioRecord.ERROR:
default:
throw new RuntimeException("captureThread(): AudioRecord.ERROR or default");
}
}
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
// Ensure we always unlock
captureLock.unlock();
}
getAudioBus().writeCaptureData(recBuffer, samplesRead);
estimatedCaptureDelay = samplesRead * 1000 / captureSamplingRate;
}
};
@Override
public boolean initRenderer() {
// Request audio focus for playback
int result = audioManager.requestAudioFocus(audioFocusChangeListener,
// Use the music stream.
AudioManager.STREAM_VOICE_CALL,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.d("AUDIO_FOCUS", "Audio Focus request GRANTED !");
} else {
Log.e("AUDIO_FOCUS", "Audio Focus request DENIED !");
return false;
}
// initalize default values
bluetoothState = BluetoothState.Disconnected;
/* register for bluetooth sco callbacks and attempt to enable it */
enableBluetoothEvents();
// get the minimum buffer size that can be used
int minPlayBufSize = AudioTrack.getMinBufferSize(
rendererSettings.getSampleRate(),
NUM_CHANNELS_RENDERING == 1 ? AudioFormat.CHANNEL_OUT_MONO : AudioFormat.CHANNEL_OUT_STEREO,
AudioFormat.ENCODING_PCM_16BIT
);
// release the object
if (audioTrack != null) {
audioTrack.release();
audioTrack = null;
}
try {
int channelConfig = (NUM_CHANNELS_RENDERING == 1) ? AudioFormat.CHANNEL_OUT_MONO : AudioFormat.CHANNEL_OUT_STEREO;
audioTrack = new AudioTrack(
AudioManager.STREAM_VOICE_CALL,
rendererSettings.getSampleRate(),
channelConfig,
AudioFormat.ENCODING_PCM_16BIT,
minPlayBufSize >= 6000 ? minPlayBufSize : minPlayBufSize * 2,
AudioTrack.MODE_STREAM
);
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
// Check that the audioRecord is ready to be used.
if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
throw new RuntimeException("Audio renderer not initialized " + rendererSettings.getSampleRate());
}
bufferedPlaySamples = 0;
registerPhoneStateListener();
shutdownRenderThread = false;
new Thread(renderThread).start();
return true;
}
private void destroyAudioTrack() {
rendererLock.lock();
audioTrack.release();
audioTrack = null;
shutdownRenderThread = true;
renderEvent.signal();
rendererLock.unlock();
}
@Override
public boolean destroyRenderer() {
destroyAudioTrack();
disableBluetoothEvents();
unregisterHeadsetReceiver();
audioManager.setSpeakerphoneOn(false);
audioManager.abandonAudioFocus(audioFocusChangeListener);
unRegisterPhoneStateListener();
wasRendering = false;
return true;
}
public int getEstimatedRenderDelay() {
return estimatedRenderDelay;
}
@Override
public boolean startRenderer() {
Log.d("AUDIO_FOCUS", "Start Renderer");
// Enable speakerphone unless headset is connected.
synchronized (bluetoothLock) {
if (BluetoothState.Connected != bluetoothState) {
if (audioManager.isWiredHeadsetOn()) {
Log.d(TAG, "Turn off Speaker phone");
audioManager.setSpeakerphoneOn(false);
} else {
Log.d(TAG, "Turn on Speaker phone");
if (getOutputType() == OutputType.SPEAKER_PHONE) {
audioManager.setSpeakerphoneOn(true);
}
}
}
}
// Start playout.
if (audioTrack == null) {
throw new IllegalStateException("startRenderer(): play() called on uninitialized AudioTrack");
}
try {
audioTrack.play();
} catch (IllegalStateException e) {
throw new RuntimeException(e.getMessage());
}
rendererLock.lock();
isRendering = true;
renderEvent.signal();
rendererLock.unlock();
registerBtReceiver();
registerHeadsetReceiver();
return true;
}
@Override
public boolean stopRenderer() {
Log.d("AUDIO_FOCUS", "Stop Renderer");
if (audioTrack == null) {
throw new IllegalStateException("stopRenderer(): stop() called on uninitialized AudioTrack");
}
rendererLock.lock();
try {
// Only stop if we are playing.
if (audioTrack.getPlayState() == AudioTrack.PLAYSTATE_PLAYING) {
audioTrack.stop();
}
audioTrack.flush();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
isRendering = false;
rendererLock.unlock();
}
audioManagerMode.releaseMode(audioManager);
unregisterHeadsetReceiver();
unregisterBtReceiver();
return true;
}
private Runnable renderThread = () -> {
int samplesToPlay = samplesPerBuffer;
try {
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
} catch (Exception e) {
Log.e(TAG, "android.os.Process.setThreadPriority(): " + e.getMessage());
}
while (!shutdownRenderThread) {
rendererLock.lock();
try {
if (!this.isRendering) {
renderEvent.await();
continue;
} else {
rendererLock.unlock();
// Don't lock on audioBus calls
playBuffer.clear();
int samplesRead = getAudioBus().readRenderData(playBuffer, samplesToPlay);
rendererLock.lock();
// After acquiring the lock again we must check if we are still playing
if (audioTrack == null || !this.isRendering) {
continue;
}
int bytesRead = (samplesRead << 1) * NUM_CHANNELS_RENDERING;
playBuffer.get(tempBufPlay, 0, bytesRead);
int bytesWritten = audioTrack.write(tempBufPlay, 0, bytesRead);
if (bytesWritten > 0) {
// increase by number of written samples
bufferedPlaySamples += (bytesWritten >> 1) / NUM_CHANNELS_RENDERING;
// decrease by number of played samples
int pos = audioTrack.getPlaybackHeadPosition();
if (pos < playPosition) {
// wrap or reset by driver
playPosition = 0;
}
bufferedPlaySamples -= (pos - playPosition);
playPosition = pos;
// we calculate the estimated delay based on the buffered samples
estimatedRenderDelay = bufferedPlaySamples * 1000 / outputSamplingRate;
} else {
switch (bytesWritten) {
case AudioTrack.ERROR_BAD_VALUE:
throw new RuntimeException("renderThread(): AudioTrack.ERROR_BAD_VALUE");
case AudioTrack.ERROR_INVALID_OPERATION:
throw new RuntimeException("renderThread(): AudioTrack.ERROR_INVALID_OPERATION");
case AudioTrack.ERROR:
default:
throw new RuntimeException(
"renderThread(): AudioTrack.ERROR or default");
}
}
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
} finally {
rendererLock.unlock();
}
}
};
@Override
public AudioSettings getCaptureSettings() {
return this.captureSettings;
}
@Override
public AudioSettings getRenderSettings() {
return this.rendererSettings;
}
/*
* Communication modes handling.
*/
public boolean setOutputMode(OutputMode mode) {
//This is public API and also called during initialization
Log.d("AUDIO_FOCUS", "outputmode set to : " + mode);
super.setOutputMode(mode);
if(OutputMode.SpeakerPhone == mode) {
audioState.setLastOutputType(getOutputType());
setOutputType(OutputType.SPEAKER_PHONE);
audioManager.setSpeakerphoneOn(true);
stopBluetoothSco();
audioManager.setBluetoothScoOn(false);
} else {
if (audioState.getLastOutputType() == OutputType.BLUETOOTH || bluetoothState == BluetoothState.Connected) {
connectBluetooth();
} else {
audioState.setLastOutputType(getOutputType());
audioManager.setSpeakerphoneOn(false);
setOutputType(OutputType.EAR_PIECE);
stopBluetoothSco();
audioManager.setBluetoothScoOn(false);
}
}
return true;
}
private boolean isHeadsetReceiverRegistered;
private void registerHeadsetReceiver() {
Log.d(TAG, "registerHeadsetReceiver() called ... isHeadsetReceiverRegistered = " + isHeadsetReceiverRegistered);
if (isHeadsetReceiverRegistered) {
return;
}
context.registerReceiver(headsetBroadcastReceiver, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
isHeadsetReceiverRegistered = true;
}
private void unregisterHeadsetReceiver() {
Log.d(TAG, "unregisterHeadsetReceiver() called .. isHeadsetReceiverRegistered = " + isHeadsetReceiverRegistered);
if (!isHeadsetReceiverRegistered) {
return;
}
context.unregisterReceiver(headsetBroadcastReceiver);
isHeadsetReceiverRegistered = false;
}
private boolean isBluetoothHeadSetReceiverRegistered;
private void registerBtReceiver() {
Log.d(TAG, "registerBtReceiver() called .. isBluetoothHeadSetReceiverRegistered = " + isBluetoothHeadSetReceiverRegistered);
if (isBluetoothHeadSetReceiverRegistered) {
return;
}
IntentFilter btFilter = new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED);
btFilter.addAction(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
context.registerReceiver(bluetoothBroadcastReceiver, btFilter);
// Register receiver for change in audio connection state of the Headset profile.
context.registerReceiver(bluetoothHeadsetReceiver, new IntentFilter(BluetoothHeadset.ACTION_AUDIO_STATE_CHANGED));
isBluetoothHeadSetReceiverRegistered = true;
}
private void unregisterBtReceiver() {
Log.d(TAG, "unregisterBtReceiver() called .. bluetoothHeadSetReceiverRegistered = " + isBluetoothHeadSetReceiverRegistered);
if (!isBluetoothHeadSetReceiverRegistered) {
return;
}
context.unregisterReceiver(bluetoothBroadcastReceiver);
context.unregisterReceiver(bluetoothHeadsetReceiver);
isBluetoothHeadSetReceiverRegistered = false;