/
AudioConnection.java
682 lines (611 loc) · 25.6 KB
/
AudioConnection.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
/*
* Copyright 2015-2017 Austin Keener & Michael Ritter & Florian Spieß
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.core.audio;
import com.sun.jna.ptr.PointerByReference;
import gnu.trove.map.TIntLongMap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntLongHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.audio.factory.IAudioSendFactory;
import net.dv8tion.jda.core.audio.factory.IAudioSendSystem;
import net.dv8tion.jda.core.audio.factory.IPacketProvider;
import net.dv8tion.jda.core.audio.hooks.ConnectionStatus;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.User;
import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import net.dv8tion.jda.core.events.ExceptionEvent;
import net.dv8tion.jda.core.managers.impl.AudioManagerImpl;
import net.dv8tion.jda.core.utils.SimpleLog;
import net.dv8tion.jda.core.utils.tuple.Pair;
import org.json.JSONObject;
import tomp2p.opuswrapper.Opus;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class AudioConnection
{
public static final SimpleLog LOG = SimpleLog.getLog(AudioConnection.class);
public static final int OPUS_SAMPLE_RATE = 48000; //(Hz) We want to use the highest of qualities! All the bandwidth!
public static final int OPUS_FRAME_SIZE = 960; //An opus frame size of 960 at 48000hz represents 20 milliseconds of audio.
public static final int OPUS_FRAME_TIME_AMOUNT = 20;//This is 20 milliseconds. We are only dealing with 20ms opus packets.
public static final int OPUS_CHANNEL_COUNT = 2; //We want to use stereo. If the audio given is mono, the encoder promotes it
// to Left and Right mono (stereo that is the same on both sides)
private final TIntLongMap ssrcMap = new TIntLongHashMap();
private final TIntObjectMap<Decoder> opusDecoders = new TIntObjectHashMap<>();
private final HashMap<User, Queue<Pair<Long, short[]>>> combinedQueue = new HashMap<>();
private final String threadIdentifier;
private final AudioWebSocket webSocket;
private DatagramSocket udpSocket;
private VoiceChannel channel;
private volatile AudioSendHandler sendHandler = null;
private volatile AudioReceiveHandler receiveHandler = null;
private PointerByReference opusEncoder;
private ScheduledExecutorService combinedAudioExecutor;
private IAudioSendSystem sendSystem;
private Thread receiveThread;
private long queueTimeout;
private volatile boolean couldReceive = false;
private volatile boolean speaking = false; //Also acts as "couldProvide"
private volatile int silenceCounter = 0;
private boolean sentSilenceOnConnect = false;
private final byte[] silenceBytes = new byte[] {(byte)0xF8, (byte)0xFF, (byte)0xFE};
public AudioConnection(AudioWebSocket webSocket, VoiceChannel channel)
{
this.channel = channel;
this.webSocket = webSocket;
this.webSocket.audioConnection = this;
final JDAImpl api = (JDAImpl) channel.getJDA();
this.threadIdentifier = api.getIdentifierString() + " AudioConnection Guild: " + channel.getGuild().getId();
}
public void ready()
{
Thread readyThread = new Thread(AudioManagerImpl.AUDIO_THREADS, () ->
{
final long timeout = getGuild().getAudioManager().getConnectTimeout();
final long started = System.currentTimeMillis();
boolean connectionTimeout = false;
while (!webSocket.isReady())
{
if (timeout > 0 && System.currentTimeMillis() - started > timeout)
{
connectionTimeout = true;
break;
}
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
LOG.fatal(e);
Thread.currentThread().interrupt();
}
}
if (!connectionTimeout)
{
this.udpSocket = webSocket.getUdpSocket();
setupSendSystem();
setupReceiveSystem();
}
else
{
webSocket.close(ConnectionStatus.ERROR_CONNECTION_TIMEOUT);
}
});
readyThread.setUncaughtExceptionHandler((thread, throwable) ->
{
LOG.fatal(throwable);
JDAImpl api = (JDAImpl) getJDA();
api.getEventManager().handle(new ExceptionEvent(api, throwable, true));
});
readyThread.setDaemon(true);
readyThread.setName(threadIdentifier + " Ready Thread");
readyThread.start();
}
public void setSendingHandler(AudioSendHandler handler)
{
this.sendHandler = handler;
setupSendSystem();
}
public void setReceivingHandler(AudioReceiveHandler handler)
{
this.receiveHandler = handler;
setupReceiveSystem();
}
public void setQueueTimeout(long queueTimeout)
{
this.queueTimeout = queueTimeout;
}
public VoiceChannel getChannel()
{
return channel;
}
public void setChannel(VoiceChannel channel)
{
this.channel = channel;
}
public JDA getJDA()
{
return channel.getJDA();
}
public Guild getGuild()
{
return channel.getGuild();
}
public void removeUserSSRC(long userId)
{
final AtomicInteger ssrcRef = new AtomicInteger(0);
final boolean modified = ssrcMap.retainEntries((ssrc, id) ->
{
final boolean isEntry = id == userId;
if (isEntry)
ssrcRef.set(ssrc);
// if isEntry == true we don't want to retain it
return !isEntry;
});
if (!modified)
return;
final Decoder decoder = opusDecoders.remove(ssrcRef.get());
if (decoder != null) // cleanup decoder
decoder.close();
}
protected void updateUserSSRC(int ssrc, long userId)
{
if (ssrcMap.containsKey(ssrc))
{
long previousId = ssrcMap.get(ssrc);
if (previousId != userId)
{
//Different User already existed with this ssrc. What should we do? Just replace? Probably should nuke the old opusDecoder.
//Log for now and see if any user report the error.
LOG.fatal("Yeah.. So.. JDA received a UserSSRC update for an ssrc that already had a User set. Inform DV8FromTheWorld.\n" +
"ChannelId: " + channel.getId() + " SSRC: " + ssrc + " oldId: " + previousId + " newId: " + userId);
}
}
else
{
ssrcMap.put(ssrc, userId);
//Only create a decoder if we are actively handling received audio.
if (receiveThread != null)
opusDecoders.put(ssrc, new Decoder(ssrc));
}
}
public void close(ConnectionStatus closeStatus)
{
shutdown();
webSocket.close(closeStatus);
}
public synchronized void shutdown()
{
// setSpeaking(false);
if (sendSystem != null)
{
sendSystem.shutdown();
sendSystem = null;
}
if (receiveThread != null)
{
receiveThread.interrupt();
receiveThread = null;
}
if (combinedAudioExecutor != null)
{
combinedAudioExecutor.shutdownNow();
combinedAudioExecutor = null;
}
if (opusEncoder != null)
{
Opus.INSTANCE.opus_encoder_destroy(opusEncoder);
opusEncoder = null;
}
opusDecoders.valueCollection().forEach(Decoder::close);
opusDecoders.clear();
}
private synchronized void setupSendSystem()
{
if (udpSocket != null && !udpSocket.isClosed() && sendHandler != null && sendSystem == null)
{
IntBuffer error = IntBuffer.allocate(4);
opusEncoder = Opus.INSTANCE.opus_encoder_create(OPUS_SAMPLE_RATE, OPUS_CHANNEL_COUNT, Opus.OPUS_APPLICATION_AUDIO, error);
IAudioSendFactory factory = ((JDAImpl) channel.getJDA()).getAudioSendFactory();
sendSystem = factory.createSendSystem(new PacketProvider());
sendSystem.start();
}
else if (sendHandler == null && sendSystem != null)
{
sendSystem.shutdown();
sendSystem = null;
if (opusEncoder != null)
{
Opus.INSTANCE.opus_encoder_destroy(opusEncoder);
opusEncoder = null;
}
}
}
private synchronized void setupReceiveSystem()
{
if (udpSocket != null && !udpSocket.isClosed() && receiveHandler != null && receiveThread == null)
{
setupReceiveThread();
}
else if (receiveHandler == null && receiveThread != null)
{
receiveThread.interrupt();
receiveThread = null;
if (combinedAudioExecutor != null)
{
combinedAudioExecutor.shutdownNow();
combinedAudioExecutor = null;
}
opusDecoders.valueCollection().forEach(Decoder::close);
opusDecoders.clear();
}
else if (receiveHandler != null && !receiveHandler.canReceiveCombined() && combinedAudioExecutor != null)
{
combinedAudioExecutor.shutdownNow();
combinedAudioExecutor = null;
}
}
private synchronized void setupReceiveThread()
{
if (receiveThread == null)
{
receiveThread = new Thread(AudioManagerImpl.AUDIO_THREADS, () ->
{
try
{
udpSocket.setSoTimeout(1000);
}
catch (SocketException e)
{
LOG.fatal(e);
}
while (!udpSocket.isClosed() && !Thread.currentThread().isInterrupted())
{
DatagramPacket receivedPacket = new DatagramPacket(new byte[1920], 1920);
try
{
udpSocket.receive(receivedPacket);
if (receiveHandler != null && (receiveHandler.canReceiveUser() || receiveHandler.canReceiveCombined()) && webSocket.getSecretKey() != null)
{
if (!couldReceive)
{
couldReceive = true;
sendSilentPackets();
}
AudioPacket decryptedPacket = AudioPacket.decryptAudioPacket(receivedPacket, webSocket.getSecretKey());
if (decryptedPacket == null)
continue;
int ssrc = decryptedPacket.getSSRC();
final long userId = ssrcMap.get(ssrc);
Decoder decoder = opusDecoders.get(ssrc);
if (userId == ssrcMap.getNoEntryValue())
{
byte[] audio = decryptedPacket.getEncodedAudio();
//If the bytes are silence, then this was caused by a User joining the voice channel,
// and as such, we haven't yet received information to pair the SSRC with the UserId.
if (!Arrays.equals(audio, silenceBytes))
LOG.debug("Received audio data with an unknown SSRC id. Ignoring");
continue;
}
if (decoder == null)
{
opusDecoders.put(ssrc, decoder = new Decoder(ssrc));
}
if (!decoder.isInOrder(decryptedPacket.getSequence()))
{
LOG.trace("Got out-of-order audio packet. Ignoring.");
continue;
}
User user = getJDA().getUserById(userId);
if (user == null)
{
LOG.warn("Received audio data with a known SSRC, but the userId associate with the SSRC is unknown to JDA!");
continue;
}
// if (decoder.wasPacketLost(decryptedPacket.getSequence()))
// {
// LOG.debug("Packet(s) missed. Using Opus packetloss-compensation.");
// short[] decodedAudio = decoder.decodeFromOpus(null);
// receiveHandler.handleUserAudio(new UserAudio(user, decodedAudio));
// }
short[] decodedAudio = decoder.decodeFromOpus(decryptedPacket);
//If decodedAudio is null, then the Opus decode failed, so throw away the packet.
if (decodedAudio == null)
{
//decoder error logged in method
continue;
}
if (receiveHandler.canReceiveUser())
{
receiveHandler.handleUserAudio(new UserAudio(user, decodedAudio));
}
if (receiveHandler.canReceiveCombined())
{
Queue<Pair<Long, short[]>> queue = combinedQueue.get(user);
if (queue == null)
{
queue = new ConcurrentLinkedQueue<>();
combinedQueue.put(user, queue);
}
queue.add(Pair.of(System.currentTimeMillis(), decodedAudio));
}
}
else if (couldReceive)
{
couldReceive = false;
sendSilentPackets();
}
}
catch (SocketTimeoutException e)
{
//Ignore. We set a low timeout so that we wont block forever so we can properly shutdown the loop.
}
catch (SocketException e)
{
//The socket was closed while we were listening for the next packet.
//This is expected. Ignore the exception. The thread will exit during the next while
// iteration because the udpSocket.isClosed() will return true.
}
catch (Exception e)
{
LOG.fatal(e);
}
}
});
receiveThread.setUncaughtExceptionHandler((thread, throwable) ->
{
LOG.fatal(throwable);
JDAImpl api = (JDAImpl) getJDA();
api.getEventManager().handle(new ExceptionEvent(api, throwable, true));
});
receiveThread.setDaemon(true);
receiveThread.setName(threadIdentifier + " Receiving Thread");
receiveThread.start();
}
if (receiveHandler.canReceiveCombined())
{
setupCombinedExecutor();
}
}
private synchronized void setupCombinedExecutor()
{
if (combinedAudioExecutor == null)
{
combinedAudioExecutor = Executors.newSingleThreadScheduledExecutor((task) ->
{
final Thread t = new Thread(AudioManagerImpl.AUDIO_THREADS, task, threadIdentifier + " Combined Thread");
t.setDaemon(true);
t.setUncaughtExceptionHandler((thread, throwable) ->
{
LOG.fatal(throwable);
JDAImpl api = (JDAImpl) getJDA();
api.getEventManager().handle(new ExceptionEvent(api, throwable, true));
});
return t;
});
combinedAudioExecutor.scheduleAtFixedRate(() ->
{
try
{
List<User> users = new LinkedList<>();
List<short[]> audioParts = new LinkedList<>();
if (receiveHandler != null && receiveHandler.canReceiveCombined())
{
long currentTime = System.currentTimeMillis();
for (Map.Entry<User, Queue<Pair<Long, short[]>>> entry : combinedQueue.entrySet())
{
User user = entry.getKey();
Queue<Pair<Long, short[]>> queue = entry.getValue();
if (queue.isEmpty())
continue;
Pair<Long, short[]> audioData = queue.poll();
//Make sure the audio packet is younger than 100ms
while (audioData != null && currentTime - audioData.getLeft() > queueTimeout)
{
audioData = queue.poll();
}
//If none of the audio packets were younger than 100ms, then there is nothing to add.
if (audioData == null)
{
continue;
}
users.add(user);
audioParts.add(audioData.getRight());
}
if (!audioParts.isEmpty())
{
int audioLength = audioParts.get(0).length;
short[] mix = new short[1920]; //960 PCM samples for each channel
int sample;
for (int i = 0; i < audioLength; i++)
{
sample = 0;
for (short[] audio : audioParts)
{
sample += audio[i];
}
if (sample > Short.MAX_VALUE)
mix[i] = Short.MAX_VALUE;
else if (sample < Short.MIN_VALUE)
mix[i] = Short.MIN_VALUE;
else
mix[i] = (short) sample;
}
receiveHandler.handleCombinedAudio(new CombinedAudio(users, mix));
}
else
{
//No audio to mix, provide 20 MS of silence. (960 PCM samples for each channel)
receiveHandler.handleCombinedAudio(new CombinedAudio(Collections.emptyList(), new short[1920]));
}
}
}
catch (Exception e)
{
LOG.fatal(e);
}
}, 0, 20, TimeUnit.MILLISECONDS);
}
}
private byte[] encodeToOpus(byte[] rawAudio)
{
ShortBuffer nonEncodedBuffer = ShortBuffer.allocate(rawAudio.length / 2);
ByteBuffer encoded = ByteBuffer.allocate(4096);
for (int i = 0; i < rawAudio.length; i += 2)
{
int firstByte = (0x000000FF & rawAudio[i]); //Promotes to int and handles the fact that it was unsigned.
int secondByte = (0x000000FF & rawAudio[i + 1]); //
//Combines the 2 bytes into a short. Opus deals with unsigned shorts, not bytes.
short toShort = (short) ((firstByte << 8) | secondByte);
nonEncodedBuffer.put(toShort);
}
nonEncodedBuffer.flip();
//TODO: check for 0 / negative value for error.
int result = Opus.INSTANCE.opus_encode(opusEncoder, nonEncodedBuffer, OPUS_FRAME_SIZE, encoded, encoded.capacity());
//ENCODING STOPS HERE
byte[] audio = new byte[result];
encoded.get(audio);
return audio;
}
private void setSpeaking(boolean isSpeaking)
{
this.speaking = isSpeaking;
JSONObject obj = new JSONObject()
.put("speaking", isSpeaking)
.put("delay", 0);
webSocket.send(VoiceCode.USER_SPEAKING_UPDATE, obj);
if (!isSpeaking)
sendSilentPackets();
}
//Actual logic for this is in the Sending Thread.
private void sendSilentPackets()
{
silenceCounter = 0;
}
public AudioWebSocket getWebSocket()
{
return webSocket;
}
@Override
protected void finalize() throws Throwable
{
shutdown();
}
private class PacketProvider implements IPacketProvider
{
char seq = 0; //Sequence of audio packets. Used to determine the order of the packets.
int timestamp = 0; //Used to sync up our packets within the same timeframe of other people talking.
@Override
public String getIdentifier()
{
return threadIdentifier;
}
@Override
public VoiceChannel getConnectedChannel()
{
return AudioConnection.this.channel;
}
@Override
public DatagramSocket getUdpSocket()
{
return AudioConnection.this.udpSocket;
}
@Override
public DatagramPacket getNextPacket(boolean changeTalking)
{
DatagramPacket nextPacket = null;
try
{
if (sentSilenceOnConnect && sendHandler != null && sendHandler.canProvide())
{
silenceCounter = -1;
byte[] rawAudio = sendHandler.provide20MsAudio();
if (rawAudio == null || rawAudio.length == 0)
{
if (speaking && changeTalking)
setSpeaking(false);
}
else
{
if (!sendHandler.isOpus())
{
rawAudio = encodeToOpus(rawAudio);
}
AudioPacket packet = new AudioPacket(seq, timestamp, webSocket.getSSRC(), rawAudio);
if (!speaking)
setSpeaking(true);
nextPacket = packet.asEncryptedUdpPacket(webSocket.getAddress(), webSocket.getSecretKey());
if (seq + 1 > Character.MAX_VALUE)
seq = 0;
else
seq++;
}
}
else if (silenceCounter > -1)
{
AudioPacket packet = new AudioPacket(seq, timestamp, webSocket.getSSRC(), silenceBytes);
nextPacket = packet.asEncryptedUdpPacket(webSocket.getAddress(), webSocket.getSecretKey());
if (seq + 1 > Character.MAX_VALUE)
seq = 0;
else
seq++;
if (++silenceCounter > 10)
{
silenceCounter = -1;
sentSilenceOnConnect = true;
}
}
else if (speaking && changeTalking)
setSpeaking(false);
}
catch (Exception e)
{
LOG.fatal(e);
}
if (nextPacket != null)
timestamp += OPUS_FRAME_SIZE;
return nextPacket;
}
@Override
public void onConnectionError(ConnectionStatus status)
{
LOG.warn("IAudioSendSystem reported a connection error of: " + status);
LOG.warn("Shutting down AudioConnection.");
webSocket.close(status);
}
@Override
public void onConnectionLost()
{
LOG.warn("Closing AudioConnection due to inability to send audio packets.");
LOG.warn("Cannot send audio packet because JDA cannot navigate the route to Discord.\n" +
"Are you sure you have internet connection? It is likely that you've lost connection.");
webSocket.close(ConnectionStatus.ERROR_LOST_CONNECTION);
}
}
}