-
Notifications
You must be signed in to change notification settings - Fork 227
/
Copy pathserver.cpp
1623 lines (1367 loc) · 62.4 KB
/
server.cpp
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
/******************************************************************************\
* Copyright (c) 2004-2024
*
* Author(s):
* Volker Fischer
*
******************************************************************************
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
\******************************************************************************/
#include "server.h"
// CServer implementation ******************************************************
CServer::CServer ( const int iNewMaxNumChan,
const QString& strLoggingFileName,
const QString& strServerBindIP,
const quint16 iPortNumber,
const quint16 iQosNumber,
const QString& strHTMLStatusFileName,
const QString& strDirectoryAddress,
const QString& strServerListFileName,
const QString& strServerInfo,
const QString& strServerListFilter,
const QString& strServerPublicIP,
const QString& strNewWelcomeMessage,
const QString& strRecordingDirName,
const bool bNDisconnectAllClientsOnQuit,
const bool bNUseDoubleSystemFrameSize,
const bool bNUseMultithreading,
const bool bDisableRecording,
const bool bNDelayPan,
const bool bNEnableIPv6,
const ELicenceType eNLicenceType ) :
bUseDoubleSystemFrameSize ( bNUseDoubleSystemFrameSize ),
bUseMultithreading ( bNUseMultithreading ),
iMaxNumChannels ( iNewMaxNumChan ),
iCurNumChannels ( 0 ),
Socket ( this, iPortNumber, iQosNumber, strServerBindIP, bNEnableIPv6 ),
Logging(),
iFrameCount ( 0 ),
bWriteStatusHTMLFile ( false ),
strServerHTMLFileListName ( strHTMLStatusFileName ),
HighPrecisionTimer ( bNUseDoubleSystemFrameSize ),
ServerListManager ( iPortNumber,
strDirectoryAddress,
strServerListFileName,
strServerInfo,
strServerPublicIP,
strServerListFilter,
iNewMaxNumChan,
bNEnableIPv6,
&ConnLessProtocol ),
JamController ( this ),
bDisableRecording ( bDisableRecording ),
bAutoRunMinimized ( false ),
bDelayPan ( bNDelayPan ),
bEnableIPv6 ( bNEnableIPv6 ),
eLicenceType ( eNLicenceType ),
bDisconnectAllClientsOnQuit ( bNDisconnectAllClientsOnQuit ),
pSignalHandler ( CSignalHandler::getSingletonP() )
{
int iOpusError;
int i;
// create OPUS encoder/decoder for each channel (must be done before
// enabling the channels), create a mono and stereo encoder/decoder
// for each channel
for ( i = 0; i < iMaxNumChannels; i++ )
{
// init OPUS -----------------------------------------------------------
OpusMode[i] = opus_custom_mode_create ( SYSTEM_SAMPLE_RATE_HZ, DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES, &iOpusError );
Opus64Mode[i] = opus_custom_mode_create ( SYSTEM_SAMPLE_RATE_HZ, SYSTEM_FRAME_SIZE_SAMPLES, &iOpusError );
// init audio encoders and decoders
OpusEncoderMono[i] = opus_custom_encoder_create ( OpusMode[i], 1, &iOpusError ); // mono encoder legacy
OpusDecoderMono[i] = opus_custom_decoder_create ( OpusMode[i], 1, &iOpusError ); // mono decoder legacy
OpusEncoderStereo[i] = opus_custom_encoder_create ( OpusMode[i], 2, &iOpusError ); // stereo encoder legacy
OpusDecoderStereo[i] = opus_custom_decoder_create ( OpusMode[i], 2, &iOpusError ); // stereo decoder legacy
Opus64EncoderMono[i] = opus_custom_encoder_create ( Opus64Mode[i], 1, &iOpusError ); // mono encoder OPUS64
Opus64DecoderMono[i] = opus_custom_decoder_create ( Opus64Mode[i], 1, &iOpusError ); // mono decoder OPUS64
Opus64EncoderStereo[i] = opus_custom_encoder_create ( Opus64Mode[i], 2, &iOpusError ); // stereo encoder OPUS64
Opus64DecoderStereo[i] = opus_custom_decoder_create ( Opus64Mode[i], 2, &iOpusError ); // stereo decoder OPUS64
// we require a constant bit rate
opus_custom_encoder_ctl ( OpusEncoderMono[i], OPUS_SET_VBR ( 0 ) );
opus_custom_encoder_ctl ( OpusEncoderStereo[i], OPUS_SET_VBR ( 0 ) );
opus_custom_encoder_ctl ( Opus64EncoderMono[i], OPUS_SET_VBR ( 0 ) );
opus_custom_encoder_ctl ( Opus64EncoderStereo[i], OPUS_SET_VBR ( 0 ) );
// for 64 samples frame size we have to adjust the PLC behavior to avoid loud artifacts
opus_custom_encoder_ctl ( Opus64EncoderMono[i], OPUS_SET_PACKET_LOSS_PERC ( 35 ) );
opus_custom_encoder_ctl ( Opus64EncoderStereo[i], OPUS_SET_PACKET_LOSS_PERC ( 35 ) );
// we want as low delay as possible
opus_custom_encoder_ctl ( OpusEncoderMono[i], OPUS_SET_APPLICATION ( OPUS_APPLICATION_RESTRICTED_LOWDELAY ) );
opus_custom_encoder_ctl ( OpusEncoderStereo[i], OPUS_SET_APPLICATION ( OPUS_APPLICATION_RESTRICTED_LOWDELAY ) );
opus_custom_encoder_ctl ( Opus64EncoderMono[i], OPUS_SET_APPLICATION ( OPUS_APPLICATION_RESTRICTED_LOWDELAY ) );
opus_custom_encoder_ctl ( Opus64EncoderStereo[i], OPUS_SET_APPLICATION ( OPUS_APPLICATION_RESTRICTED_LOWDELAY ) );
// set encoder low complexity for legacy 128 samples frame size
opus_custom_encoder_ctl ( OpusEncoderMono[i], OPUS_SET_COMPLEXITY ( 1 ) );
opus_custom_encoder_ctl ( OpusEncoderStereo[i], OPUS_SET_COMPLEXITY ( 1 ) );
// init double-to-normal frame size conversion buffers -----------------
// use worst case memory initialization to avoid allocating memory in
// the time-critical thread
DoubleFrameSizeConvBufIn[i].Init ( 2 /* stereo */ * DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES /* worst case buffer size */ );
DoubleFrameSizeConvBufOut[i].Init ( 2 /* stereo */ * DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES /* worst case buffer size */ );
}
// define colors for chat window identifiers
vstrChatColors.Init ( 6 );
vstrChatColors[0] = "mediumblue";
vstrChatColors[1] = "red";
vstrChatColors[2] = "darkorchid";
vstrChatColors[3] = "green";
vstrChatColors[4] = "maroon";
vstrChatColors[5] = "coral";
// set the server frame size
if ( bUseDoubleSystemFrameSize )
{
iServerFrameSizeSamples = DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES;
}
else
{
iServerFrameSizeSamples = SYSTEM_FRAME_SIZE_SAMPLES;
}
// To avoid audio clitches, in the entire realtime timer audio processing
// routine including the ProcessData no memory must be allocated. Since we
// do not know the required sizes for the vectors, we allocate memory for
// the worst case here:
// allocate worst case memory for the temporary vectors
vecChanIDsCurConChan.Init ( iMaxNumChannels );
vecvecfGains.Init ( iMaxNumChannels );
vecvecfPannings.Init ( iMaxNumChannels );
vecvecsData.Init ( iMaxNumChannels );
vecvecsData2.Init ( iMaxNumChannels );
vecvecsSendData.Init ( iMaxNumChannels );
vecvecfIntermediateProcBuf.Init ( iMaxNumChannels );
vecvecbyCodedData.Init ( iMaxNumChannels );
vecNumAudioChannels.Init ( iMaxNumChannels );
vecNumFrameSizeConvBlocks.Init ( iMaxNumChannels );
vecUseDoubleSysFraSizeConvBuf.Init ( iMaxNumChannels );
vecAudioComprType.Init ( iMaxNumChannels );
for ( i = 0; i < iMaxNumChannels; i++ )
{
// init vectors storing information of all channels
vecvecfGains[i].Init ( iMaxNumChannels );
vecvecfPannings[i].Init ( iMaxNumChannels );
// we always use stereo audio buffers (which is the worst case)
vecvecsData[i].Init ( 2 /* stereo */ * DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES /* worst case buffer size */ );
vecvecsData2[i].Init ( 2 /* stereo */ * DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES /* worst case buffer size */ );
// (note that we only allocate iMaxNumChannels buffers for the send
// and coded data because of the OMP implementation)
vecvecsSendData[i].Init ( 2 /* stereo */ * DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES /* worst case buffer size */ );
// allocate worst case memory for intermediate processing buffers in float precision
vecvecfIntermediateProcBuf[i].Init ( 2 /* stereo */ * DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES /* worst case buffer size */ );
// allocate worst case memory for the coded data
vecvecbyCodedData[i].Init ( MAX_SIZE_BYTES_NETW_BUF );
}
// allocate worst case memory for the channel levels
vecChannelLevels.Init ( iMaxNumChannels );
// enable logging (if requested)
if ( !strLoggingFileName.isEmpty() )
{
Logging.Start ( strLoggingFileName );
}
// HTML status file writing
if ( !strServerHTMLFileListName.isEmpty() )
{
// activate HTML file writing and write initial file
bWriteStatusHTMLFile = true;
WriteHTMLChannelList();
}
// manage welcome message: if the welcome message is a valid link to a local
// file, the content of that file is used as the welcome message (#361)
SetWelcomeMessage ( strNewWelcomeMessage ); // first use given text, may be overwritten
if ( QFileInfo ( strNewWelcomeMessage ).exists() )
{
QFile file ( strNewWelcomeMessage );
if ( file.open ( QIODevice::ReadOnly | QIODevice::Text ) )
{
// use entire file content for the welcome message
SetWelcomeMessage ( file.readAll() );
}
}
// enable jam recording (if requested) - kicks off the thread (note
// that jam recorder needs the frame size which is given to the jam
// recorder in the SetRecordingDir() function)
SetRecordingDir ( strRecordingDirName );
// enable all channels (for the server all channel must be enabled the
// entire life time of the software)
for ( i = 0; i < iMaxNumChannels; i++ )
{
vecChannels[i].SetEnable ( true );
vecChannelOrder[i] = i;
}
int iAvailableCores = QThread::idealThreadCount();
// setup CThreadPool if multithreading is active and possible
if ( bUseMultithreading )
{
if ( iAvailableCores == 1 )
{
qDebug() << "found only one core, disabling multithreading";
bUseMultithreading = false;
}
else
{
// set maximum thread count to available cores; other threads will share at random
iMaxNumThreads = iAvailableCores;
qDebug() << "multithreading enabled, setting thread count to" << iMaxNumThreads;
pThreadPool = std::unique_ptr<CThreadPool> ( new CThreadPool{ static_cast<size_t> ( iMaxNumThreads ) } );
Futures.reserve ( iMaxNumThreads );
}
}
// Connections -------------------------------------------------------------
// connect timer timeout signal
QObject::connect ( &HighPrecisionTimer, &CHighPrecisionTimer::timeout, this, &CServer::OnTimer );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLMessReadyForSending, this, &CServer::OnSendCLProtMessage );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLPingReceived, this, &CServer::OnCLPingReceived );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLPingWithNumClientsReceived, this, &CServer::OnCLPingWithNumClientsReceived );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLRegisterServerReceived, this, &CServer::OnCLRegisterServerReceived );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLRegisterServerExReceived, this, &CServer::OnCLRegisterServerExReceived );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLUnregisterServerReceived, this, &CServer::OnCLUnregisterServerReceived );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLReqServerList, this, &CServer::OnCLReqServerList );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLRegisterServerResp, this, &CServer::OnCLRegisterServerResp );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLSendEmptyMes, this, &CServer::OnCLSendEmptyMes );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLDisconnection, this, &CServer::OnCLDisconnection );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLReqVersionAndOS, this, &CServer::OnCLReqVersionAndOS );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLVersionAndOSReceived, this, &CServer::CLVersionAndOSReceived );
QObject::connect ( &ConnLessProtocol, &CProtocol::CLReqConnClientsList, this, &CServer::OnCLReqConnClientsList );
QObject::connect ( &ServerListManager, &CServerListManager::SvrRegStatusChanged, this, &CServer::SvrRegStatusChanged );
QObject::connect ( &JamController, &recorder::CJamController::RestartRecorder, this, &CServer::RestartRecorder );
QObject::connect ( &JamController, &recorder::CJamController::StopRecorder, this, &CServer::StopRecorder );
QObject::connect ( &JamController, &recorder::CJamController::RecordingSessionStarted, this, &CServer::RecordingSessionStarted );
QObject::connect ( &JamController, &recorder::CJamController::EndRecorderThread, this, &CServer::EndRecorderThread );
QObject::connect ( this, &CServer::Stopped, &JamController, &recorder::CJamController::Stopped );
QObject::connect ( this, &CServer::ClientDisconnected, &JamController, &recorder::CJamController::ClientDisconnected );
qRegisterMetaType<CVector<int16_t>> ( "CVector<int16_t>" );
QObject::connect ( this, &CServer::AudioFrame, &JamController, &recorder::CJamController::AudioFrame );
QObject::connect ( QCoreApplication::instance(), &QCoreApplication::aboutToQuit, this, &CServer::OnAboutToQuit );
QObject::connect ( pSignalHandler, &CSignalHandler::HandledSignal, this, &CServer::OnHandledSignal );
connectChannelSignalsToServerSlots<MAX_NUM_CHANNELS>();
// start the socket (it is important to start the socket after all
// initializations and connections)
Socket.Start();
}
template<unsigned int slotId>
inline void CServer::connectChannelSignalsToServerSlots()
{
int iCurChanID = slotId - 1;
void ( CServer::*pOnSendProtMessCh ) ( CVector<uint8_t> ) = &CServerSlots<slotId>::OnSendProtMessCh;
void ( CServer::*pOnReqConnClientsListCh )() = &CServerSlots<slotId>::OnReqConnClientsListCh;
void ( CServer::*pOnChatTextReceivedCh ) ( QString ) = &CServerSlots<slotId>::OnChatTextReceivedCh;
void ( CServer::*pOnMuteStateHasChangedCh ) ( int, bool ) = &CServerSlots<slotId>::OnMuteStateHasChangedCh;
void ( CServer::*pOnServerAutoSockBufSizeChangeCh ) ( int ) = &CServerSlots<slotId>::OnServerAutoSockBufSizeChangeCh;
// send message
QObject::connect ( &vecChannels[iCurChanID], &CChannel::MessReadyForSending, this, pOnSendProtMessCh );
// request connected clients list
QObject::connect ( &vecChannels[iCurChanID], &CChannel::ReqConnClientsList, this, pOnReqConnClientsListCh );
// channel info has changed
QObject::connect ( &vecChannels[iCurChanID], &CChannel::ChanInfoHasChanged, this, &CServer::CreateAndSendChanListForAllConChannels );
// chat text received
QObject::connect ( &vecChannels[iCurChanID], &CChannel::ChatTextReceived, this, pOnChatTextReceivedCh );
// other mute state has changed
QObject::connect ( &vecChannels[iCurChanID], &CChannel::MuteStateHasChanged, this, pOnMuteStateHasChangedCh );
// auto socket buffer size change
QObject::connect ( &vecChannels[iCurChanID], &CChannel::ServerAutoSockBufSizeChange, this, pOnServerAutoSockBufSizeChangeCh );
connectChannelSignalsToServerSlots<slotId - 1>();
}
template<>
inline void CServer::connectChannelSignalsToServerSlots<0>()
{}
void CServer::CreateAndSendJitBufMessage ( const int iCurChanID, const int iNNumFra ) { vecChannels[iCurChanID].CreateJitBufMes ( iNNumFra ); }
CServer::~CServer()
{
for ( int i = 0; i < iMaxNumChannels; i++ )
{
// free audio encoders and decoders
opus_custom_encoder_destroy ( OpusEncoderMono[i] );
opus_custom_decoder_destroy ( OpusDecoderMono[i] );
opus_custom_encoder_destroy ( OpusEncoderStereo[i] );
opus_custom_decoder_destroy ( OpusDecoderStereo[i] );
opus_custom_encoder_destroy ( Opus64EncoderMono[i] );
opus_custom_decoder_destroy ( Opus64DecoderMono[i] );
opus_custom_encoder_destroy ( Opus64EncoderStereo[i] );
opus_custom_decoder_destroy ( Opus64DecoderStereo[i] );
// free audio modes
opus_custom_mode_destroy ( OpusMode[i] );
opus_custom_mode_destroy ( Opus64Mode[i] );
}
}
void CServer::SendProtMessage ( int iChID, CVector<uint8_t> vecMessage )
{
// the protocol queries me to call the function to send the message
// send it through the network
Socket.SendPacket ( vecMessage, vecChannels[iChID].GetAddress() );
}
void CServer::OnNewConnection ( int iChID, int iTotChans, CHostAddress RecHostAddr )
{
QMutexLocker locker ( &Mutex );
// inform the client about its own ID at the server (note that this
// must be the first message to be sent for a new connection)
vecChannels[iChID].CreateClientIDMes ( iChID );
// Send an empty channel list in order to force clients to reset their
// audio mixer state. This is required to trigger clients to re-send their
// gain levels upon reconnecting after server restarts.
vecChannels[iChID].CreateConClientListMes ( CVector<CChannelInfo> ( 0 ) );
// query support for split messages in the client
vecChannels[iChID].CreateReqSplitMessSupportMes();
// on a new connection we query the network transport properties for the
// audio packets (to use the correct network block size and audio
// compression properties, etc.)
vecChannels[iChID].CreateReqNetwTranspPropsMes();
// this is a new connection, query the jitter buffer size we shall use
// for this client (note that at the same time on a new connection the
// client sends the jitter buffer size by default but maybe we have
// reached a state where this did not happen because of network trouble,
// client or server thinks that the connection was still active, etc.)
vecChannels[iChID].CreateReqJitBufMes();
// A new client connected to the server, the channel list
// at all clients have to be updated. This is done by sending
// a channel name request to the client which causes a channel
// name message to be transmitted to the server. If the server
// receives this message, the channel list will be automatically
// updated (implicitly).
//
// Usually it is not required to send the channel list to the
// client currently connecting since it automatically requests
// the channel list on a new connection (as a result, he will
// usually get the list twice which has no impact on functionality
// but will only increase the network load a tiny little bit). But
// in case the client thinks he is still connected but the server
// was restartet, it is important that we send the channel list
// at this place.
vecChannels[iChID].CreateReqChanInfoMes();
// send welcome message (if enabled)
{
QMutexLocker locker ( &MutexWelcomeMessage );
if ( !strWelcomeMessage.isEmpty() )
{
// create formatted server welcome message and send it just to
// the client which just connected to the server
const QString strWelcomeMessageFormated = WELCOME_MESSAGE_PREFIX + strWelcomeMessage;
vecChannels[iChID].CreateChatTextMes ( strWelcomeMessageFormated );
}
}
// send licence request message (if enabled)
if ( eLicenceType != LT_NO_LICENCE )
{
vecChannels[iChID].CreateLicReqMes ( eLicenceType );
}
// send version info (for, e.g., feature activation in the client)
vecChannels[iChID].CreateVersionAndOSMes();
// send recording state message on connection
vecChannels[iChID].CreateRecorderStateMes ( JamController.GetRecorderState() );
// reset the conversion buffers
DoubleFrameSizeConvBufIn[iChID].Reset();
DoubleFrameSizeConvBufOut[iChID].Reset();
// logging of new connected channel
Logging.AddNewConnection ( RecHostAddr.InetAddr, iTotChans );
}
void CServer::OnServerFull ( CHostAddress RecHostAddr )
{
// note: no mutex required here
// inform the calling client that no channel is free
ConnLessProtocol.CreateCLServerFullMes ( RecHostAddr );
}
void CServer::OnSendCLProtMessage ( CHostAddress InetAddr, CVector<uint8_t> vecMessage )
{
// the protocol queries me to call the function to send the message
// send it through the network
Socket.SendPacket ( vecMessage, InetAddr );
}
void CServer::OnCLDisconnection ( CHostAddress InetAddr )
{
// check if the given address is actually a client which is connected to
// this server, if yes, disconnect it
const int iCurChanID = FindChannel ( InetAddr );
if ( iCurChanID != INVALID_CHANNEL_ID )
{
vecChannels[iCurChanID].Disconnect();
}
}
void CServer::OnAboutToQuit()
{
// if enabled, disconnect all clients on quit
if ( bDisconnectAllClientsOnQuit )
{
QMutexLocker locker ( &Mutex );
for ( int i = 0; i < iMaxNumChannels; i++ )
{
if ( vecChannels[i].IsConnected() )
{
ConnLessProtocol.CreateCLDisconnection ( vecChannels[i].GetAddress() );
}
}
}
Stop();
if ( bWriteStatusHTMLFile )
{
WriteHTMLServerQuit();
}
}
void CServer::OnHandledSignal ( int sigNum )
{
// show the signal number on the console (note that this may not work for Windows)
qDebug() << qUtf8Printable ( QString ( "OnHandledSignal: %1" ).arg ( sigNum ) );
#ifdef _WIN32
// Windows does not actually get OnHandledSignal triggered
QCoreApplication::instance()->exit();
Q_UNUSED ( sigNum )
#else
switch ( sigNum )
{
case SIGUSR1:
RequestNewRecording();
break;
case SIGUSR2:
SetEnableRecording ( !JamController.GetRecordingEnabled() );
break;
case SIGINT:
case SIGTERM:
// This should trigger OnAboutToQuit
QCoreApplication::instance()->exit();
break;
default:
break;
}
#endif
}
void CServer::Start()
{
// only start if not already running
if ( !IsRunning() )
{
// start timer
HighPrecisionTimer.Start();
// emit start signal
emit Started();
}
}
void CServer::Stop()
{
// Under Mac we have the problem that the timer shutdown might
// take some time and therefore we get a lot of "server stopped"
// entries in the log. The following condition shall prevent this.
// For the other OSs this should not hurt either.
if ( IsRunning() )
{
// stop timer
HighPrecisionTimer.Stop();
// logging (add "server stopped" logging entry)
Logging.AddServerStopped();
// emit stopped signal
emit Stopped();
}
}
void CServer::OnTimer()
{
//### TEST: BEGIN ###//
// uncomment next line to do a timer Jitter measurement
// static CTimingMeas JitterMeas ( 1000, "test2.dat" ); JitterMeas.Measure();
//### TEST: END ###//
// Get data from all connected clients -------------------------------------
// some inits
int iNumClients = 0; // init connected client counter
bool bUseMT = false;
int iNumBlocks = 0; // init number of blocks for multithreading
int iMTBlockSize = 0; // init block size for multithreading
bChannelIsNowDisconnected = false; // note that the flag must be a member function since QtConcurrent::run can only take 5 params
{
// Make put and get calls thread safe.
QMutexLocker locker ( &Mutex );
// first, get number and IDs of connected channels
for ( int i = 0; i < iMaxNumChannels; i++ )
{
if ( vecChannels[i].IsConnected() )
{
// add ID and increment counter (note that the vector length is
// according to the worst case scenario, if the number of
// connected clients is less, only a subset of elements of this
// vector are actually used and the others are dummy elements)
vecChanIDsCurConChan[iNumClients] = i;
iNumClients++;
}
}
// use multithreading for any non-zero number of clients
// (overhead is low and it is worth doing for all numbers)
bUseMT = bUseMultithreading && iNumClients > 0;
// prepare and decode connected channels
if ( !bUseMT )
{
// run the OPUS decoder for all data blocks
DecodeReceiveDataBlocks ( this, 0, iNumClients - 1, iNumClients );
}
else
{
// spread work equally among available threads
iNumBlocks = std::min ( iNumClients, iMaxNumThreads );
iMTBlockSize = ( iNumClients - 1 ) / iNumBlocks + 1;
// processing with multithreading
for ( int iBlockCnt = 0; iBlockCnt < iNumBlocks; iBlockCnt++ )
{
// The work for OPUS decoding is distributed over all available processor cores.
// By using the future synchronizer we make sure that all
// threads are done when we leave the timer callback function.
const int iStartChanCnt = iBlockCnt * iMTBlockSize;
const int iStopChanCnt = std::min ( ( iBlockCnt + 1 ) * iMTBlockSize - 1, iNumClients - 1 );
Futures.push_back ( pThreadPool->enqueue ( CServer::DecodeReceiveDataBlocks, this, iStartChanCnt, iStopChanCnt, iNumClients ) );
}
// make sure all concurrent run threads have finished when we leave this function
for ( auto& future : Futures )
{
future.wait();
}
Futures.clear();
}
// a channel is now disconnected, take action on it
if ( bChannelIsNowDisconnected )
{
// update channel list for all currently connected clients
CreateAndSendChanListForAllConChannels();
}
}
// Process data ------------------------------------------------------------
// Check if at least one client is connected. If not, stop server until
// one client is connected.
if ( iNumClients > 0 )
{
// calculate levels for all connected clients
const bool bSendChannelLevels = CreateLevelsForAllConChannels ( iNumClients, vecNumAudioChannels, vecvecsData, vecChannelLevels );
for ( int iChanCnt = 0; iChanCnt < iNumClients; iChanCnt++ )
{
// get actual ID of current channel
const int iCurChanID = vecChanIDsCurConChan[iChanCnt];
// update socket buffer size
vecChannels[iCurChanID].UpdateSocketBufferSize();
// send channel levels if they are ready
if ( bSendChannelLevels )
{
ConnLessProtocol.CreateCLChannelLevelListMes ( vecChannels[iCurChanID].GetAddress(), vecChannelLevels, iNumClients );
}
// export the audio data for recording purpose
if ( JamController.GetRecordingEnabled() )
{
emit AudioFrame ( iCurChanID,
vecChannels[iCurChanID].GetName(),
vecChannels[iCurChanID].GetAddress(),
vecNumAudioChannels[iChanCnt],
vecvecsData[iChanCnt] );
}
// processing without multithreading
if ( !bUseMT )
{
// generate a separate mix for each channel, OPUS encode the
// audio data and transmit the network packet
MixEncodeTransmitData ( iChanCnt, iNumClients );
}
}
// processing with multithreading
if ( bUseMT )
{
for ( int iBlockCnt = 0; iBlockCnt < iNumBlocks; iBlockCnt++ )
{
// Generate a separate mix for each channel, OPUS encode the
// audio data and transmit the network packet. The work is
// distributed over all available processor cores.
// By using the future synchronizer we make sure that all
// threads are done when we leave the timer callback function.
const int iStartChanCnt = iBlockCnt * iMTBlockSize;
const int iStopChanCnt = std::min ( ( iBlockCnt + 1 ) * iMTBlockSize - 1, iNumClients - 1 );
Futures.push_back ( pThreadPool->enqueue ( CServer::MixEncodeTransmitDataBlocks, this, iStartChanCnt, iStopChanCnt, iNumClients ) );
}
// make sure all concurrent run threads have finished when we leave this function
for ( auto& fFuture : Futures )
{
fFuture.wait();
}
Futures.clear();
}
if ( bDelayPan )
{
for ( int i = 0; i < iNumClients; i++ )
{
for ( int j = 0; j < 2 * ( iServerFrameSizeSamples ); j++ )
{
vecvecsData2[i][j] = vecvecsData[i][j];
}
}
}
}
else
{
// Disable server if no clients are connected. In this case the server
// does not consume any significant CPU when no client is connected.
Stop();
}
}
// This is a static method used as a callback, and does not inherit a "this" pointer,
// so it is necessary for the server instance to be passed as a parameter.
void CServer::DecodeReceiveDataBlocks ( CServer* pServer, const int iStartChanCnt, const int iStopChanCnt, const int iNumClients )
{
// loop over all channels in the current block, needed for multithreading support
for ( int iChanCnt = iStartChanCnt; iChanCnt <= iStopChanCnt; iChanCnt++ )
{
pServer->DecodeReceiveData ( iChanCnt, iNumClients );
}
}
// This is a static method used as a callback, and does not inherit a "this" pointer,
// so it is necessary for the server instance to be passed as a parameter.
void CServer::MixEncodeTransmitDataBlocks ( CServer* pServer, const int iStartChanCnt, const int iStopChanCnt, const int iNumClients )
{
// loop over all channels in the current block, needed for multithreading support
for ( int iChanCnt = iStartChanCnt; iChanCnt <= iStopChanCnt; iChanCnt++ )
{
pServer->MixEncodeTransmitData ( iChanCnt, iNumClients );
}
}
void CServer::DecodeReceiveData ( const int iChanCnt, const int iNumClients )
{
int iUnused;
int iClientFrameSizeSamples = 0; // initialize to avoid a compiler warning
OpusCustomDecoder* CurOpusDecoder;
unsigned char* pCurCodedData;
// get actual ID of current channel
const int iCurChanID = vecChanIDsCurConChan[iChanCnt];
// get and store number of audio channels and compression type
vecNumAudioChannels[iChanCnt] = vecChannels[iCurChanID].GetNumAudioChannels();
vecAudioComprType[iChanCnt] = vecChannels[iCurChanID].GetAudioCompressionType();
// get info about required frame size conversion properties
vecUseDoubleSysFraSizeConvBuf[iChanCnt] = ( !bUseDoubleSystemFrameSize && ( vecAudioComprType[iChanCnt] == CT_OPUS ) );
if ( bUseDoubleSystemFrameSize && ( vecAudioComprType[iChanCnt] == CT_OPUS64 ) )
{
vecNumFrameSizeConvBlocks[iChanCnt] = 2;
}
else
{
vecNumFrameSizeConvBlocks[iChanCnt] = 1;
}
// update conversion buffer size (nothing will happen if the size stays the same)
if ( vecUseDoubleSysFraSizeConvBuf[iChanCnt] )
{
DoubleFrameSizeConvBufIn[iCurChanID].SetBufferSize ( DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES * vecNumAudioChannels[iChanCnt] );
DoubleFrameSizeConvBufOut[iCurChanID].SetBufferSize ( DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES * vecNumAudioChannels[iChanCnt] );
}
// select the opus decoder and raw audio frame length
if ( vecAudioComprType[iChanCnt] == CT_OPUS )
{
iClientFrameSizeSamples = DOUBLE_SYSTEM_FRAME_SIZE_SAMPLES;
if ( vecNumAudioChannels[iChanCnt] == 1 )
{
CurOpusDecoder = OpusDecoderMono[iCurChanID];
}
else
{
CurOpusDecoder = OpusDecoderStereo[iCurChanID];
}
}
else if ( vecAudioComprType[iChanCnt] == CT_OPUS64 )
{
iClientFrameSizeSamples = SYSTEM_FRAME_SIZE_SAMPLES;
if ( vecNumAudioChannels[iChanCnt] == 1 )
{
CurOpusDecoder = Opus64DecoderMono[iCurChanID];
}
else
{
CurOpusDecoder = Opus64DecoderStereo[iCurChanID];
}
}
else
{
CurOpusDecoder = nullptr;
}
// get gains of all connected channels
for ( int j = 0; j < iNumClients; j++ )
{
// The second index of "vecvecdGains" does not represent
// the channel ID! Therefore we have to use
// "vecChanIDsCurConChan" to query the IDs of the currently
// connected channels
vecvecfGains[iChanCnt][j] = vecChannels[iCurChanID].GetGain ( vecChanIDsCurConChan[j] );
// consider audio fade-in
vecvecfGains[iChanCnt][j] *= vecChannels[vecChanIDsCurConChan[j]].GetFadeInGain();
// use the fade in of the current channel for all other connected clients
// as well to avoid the client volumes are at 100% when joining a server (#628)
if ( j != iChanCnt )
{
vecvecfGains[iChanCnt][j] *= vecChannels[iCurChanID].GetFadeInGain();
}
// panning
vecvecfPannings[iChanCnt][j] = vecChannels[iCurChanID].GetPan ( vecChanIDsCurConChan[j] );
}
// If the server frame size is smaller than the received OPUS frame size, we need a conversion
// buffer which stores the large buffer.
// Note that we have a shortcut here. If the conversion buffer is not needed, the boolean flag
// is false and the Get() function is not called at all. Therefore if the buffer is not needed
// we do not spend any time in the function but go directly inside the if condition.
if ( ( vecUseDoubleSysFraSizeConvBuf[iChanCnt] == 0 ) ||
!DoubleFrameSizeConvBufIn[iCurChanID].Get ( vecvecsData[iChanCnt], SYSTEM_FRAME_SIZE_SAMPLES * vecNumAudioChannels[iChanCnt] ) )
{
// get current number of OPUS coded bytes
const int iCeltNumCodedBytes = vecChannels[iCurChanID].GetCeltNumCodedBytes();
for ( int iB = 0; iB < vecNumFrameSizeConvBlocks[iChanCnt]; iB++ )
{
// get data
const EGetDataStat eGetStat = vecChannels[iCurChanID].GetData ( vecvecbyCodedData[iChanCnt], iCeltNumCodedBytes );
// if channel was just disconnected, set flag that connected
// client list is sent to all other clients
// and emit the client disconnected signal
if ( eGetStat == GS_CHAN_NOW_DISCONNECTED )
{
if ( JamController.GetRecordingEnabled() )
{
emit ClientDisconnected ( iCurChanID ); // TODO do this outside the mutex lock?
}
FreeChannel ( iCurChanID ); // note that the channel is now not in use
// note that no mutex is needed for this shared resource since it is not a
// read-modify-write operation but an atomic write and also each thread can
// only set it to true and never to false
bChannelIsNowDisconnected = true;
// since the channel is no longer in use, we should return
return;
}
// get pointer to coded data
if ( eGetStat == GS_BUFFER_OK )
{
pCurCodedData = &vecvecbyCodedData[iChanCnt][0];
}
else
{
// for lost packets use null pointer as coded input data
pCurCodedData = nullptr;
}
// OPUS decode received data stream
if ( CurOpusDecoder != nullptr )
{
const int iOffset = iB * SYSTEM_FRAME_SIZE_SAMPLES * vecNumAudioChannels[iChanCnt];
iUnused = opus_custom_decode ( CurOpusDecoder,
pCurCodedData,
iCeltNumCodedBytes,
&vecvecsData[iChanCnt][iOffset],
iClientFrameSizeSamples );
}
}
// a new large frame is ready, if the conversion buffer is required, put it in the buffer
// and read out the small frame size immediately for further processing
if ( vecUseDoubleSysFraSizeConvBuf[iChanCnt] != 0 )
{
DoubleFrameSizeConvBufIn[iCurChanID].PutAll ( vecvecsData[iChanCnt] );
DoubleFrameSizeConvBufIn[iCurChanID].Get ( vecvecsData[iChanCnt], SYSTEM_FRAME_SIZE_SAMPLES * vecNumAudioChannels[iChanCnt] );
}
}
Q_UNUSED ( iUnused )
}
/// @brief Mix all audio data from all clients together, encode and transmit
void CServer::MixEncodeTransmitData ( const int iChanCnt, const int iNumClients )
{
int i, j, k, iUnused;
CVector<float>& vecfIntermProcBuf = vecvecfIntermediateProcBuf[iChanCnt]; // use reference for faster access
CVector<int16_t>& vecsSendData = vecvecsSendData[iChanCnt]; // use reference for faster access
// get actual ID of current channel
const int iCurChanID = vecChanIDsCurConChan[iChanCnt];
// init intermediate processing vector with zeros since we mix all channels on that vector
vecfIntermProcBuf.Reset ( 0 );
// distinguish between stereo and mono mode
if ( vecNumAudioChannels[iChanCnt] == 1 )
{
// Mono target channel -------------------------------------------------
for ( j = 0; j < iNumClients; j++ )
{
// get a reference to the audio data and gain of the current client
const CVector<int16_t>& vecsData = vecvecsData[j];
const float fGain = vecvecfGains[iChanCnt][j];
// if channel gain is 1, avoid multiplication for speed optimization
if ( fGain == 1.0f )
{
if ( vecNumAudioChannels[j] == 1 )
{
// mono
for ( i = 0; i < iServerFrameSizeSamples; i++ )
{
vecfIntermProcBuf[i] += vecsData[i];
}
}
else
{
// stereo: apply stereo-to-mono attenuation
for ( i = 0, k = 0; i < iServerFrameSizeSamples; i++, k += 2 )
{
vecfIntermProcBuf[i] += ( static_cast<float> ( vecsData[k] ) + vecsData[k + 1] ) / 2;
}
}
}
else
{
if ( vecNumAudioChannels[j] == 1 )
{
// mono
for ( i = 0; i < iServerFrameSizeSamples; i++ )
{
vecfIntermProcBuf[i] += vecsData[i] * fGain;
}
}
else
{
// stereo: apply stereo-to-mono attenuation
for ( i = 0, k = 0; i < iServerFrameSizeSamples; i++, k += 2 )
{
vecfIntermProcBuf[i] += fGain * ( static_cast<float> ( vecsData[k] ) + vecsData[k + 1] ) / 2;
}
}
}
}
// convert from double to short with clipping
for ( i = 0; i < iServerFrameSizeSamples; i++ )
{
vecsSendData[i] = Float2Short ( vecfIntermProcBuf[i] );
}
}
else
{
// Stereo target channel -----------------------------------------------
const int maxPanDelay = MAX_DELAY_PANNING_SAMPLES;
int iPanDelL = 0, iPanDelR = 0, iPanDel;
int iLpan, iRpan, iPan;
for ( j = 0; j < iNumClients; j++ )
{
// get a reference to the audio data and gain/pan of the current client
const CVector<int16_t>& vecsData = vecvecsData[j];
const CVector<int16_t>& vecsData2 = vecvecsData2[j];
const float fGain = vecvecfGains[iChanCnt][j];
const float fPan = bDelayPan ? 0.5f : vecvecfPannings[iChanCnt][j];