-
-
Notifications
You must be signed in to change notification settings - Fork 49
/
Copy pathmanager.cpp
3345 lines (2800 loc) · 92.4 KB
/
manager.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-2021 Savoir-faire Linux Inc.
*
* Author: Alexandre Bourget <alexandre.bourget@savoirfairelinux.com>
* Author: Yan Morin <yan.morin@savoirfairelinux.com>
* Author: Laurielle Lea <laurielle.lea@savoirfairelinux.com>
* Author: Emmanuel Milou <emmanuel.milou@savoirfairelinux.com>
* Author: Alexandre Savard <alexandre.savard@savoirfairelinux.com>
* Author: Guillaume Carmel-Archambault <guillaume.carmel-archambault@savoirfairelinux.com>
* Author: Tristan Matthews <tristan.matthews@savoirfairelinux.com>
* Author: Guillaume Roguez <guillaume.roguez@savoirfairelinux.com>
* Author: Adrien Béraud <adrien.beraud@savoirfairelinux.com>
* Author: Philippe Gorley <philippe.gorley@savoirfairelinux.com>
* Author: Aline Gondim Santos <aline.gondimsantos@savoirfairelinux.com>
*
* 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 3 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.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "manager.h"
#include "logger.h"
#include "account_schema.h"
#include "fileutils.h"
#include "map_utils.h"
#include "account.h"
#include "string_utils.h"
#include "jamidht/jamiaccount.h"
#include "sip/sipvoiplink.h"
#include "account.h"
#include <opendht/rng.h>
using random_device = dht::crypto::random_device;
#include "call_factory.h"
#include "sip/sip_utils.h"
#include "sip/sipvoiplink.h"
#include "sip/sipaccount.h"
#include "im/instant_messaging.h"
#include "config/yamlparser.h"
#if HAVE_ALSA
#include "audio/alsa/alsalayer.h"
#endif
#include "media/localrecordermanager.h"
#include "audio/sound/tonelist.h"
#include "audio/sound/dtmf.h"
#include "audio/ringbufferpool.h"
#ifdef ENABLE_PLUGIN
#include "plugin/jamipluginmanager.h"
#include "plugin/streamdata.h"
#endif
#ifdef ENABLE_VIDEO
#include "client/videomanager.h"
#include "video/video_scaler.h"
#endif
#include "conference.h"
#include "ice_transport.h"
#include "client/ring_signal.h"
#include "dring/call_const.h"
#include "dring/account_const.h"
#include "libav_utils.h"
#include "video/sinkclient.h"
#include "media/video/video_mixer.h"
#include "audio/tonecontrol.h"
#include "data_transfer.h"
#include "dring/media_const.h"
#include <libavutil/ffversion.h>
#include <opendht/thread_pool.h>
#include <asio/io_context.hpp>
#include <asio/executor_work_guard.hpp>
#ifndef WIN32
#include <sys/time.h>
#include <sys/resource.h>
#endif
#ifdef TARGET_OS_IOS
#include <CoreFoundation/CoreFoundation.h>
#endif
#include <cerrno>
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <memory>
#include <mutex>
#include <list>
#include <random>
namespace jami {
/** To store conference objects by conference ids */
using ConferenceMap = std::map<std::string, std::shared_ptr<Conference>>;
/** To store uniquely a list of Call ids */
using CallIDSet = std::set<std::string>;
static constexpr std::chrono::seconds ICE_INIT_TIMEOUT {10};
static constexpr const char* PACKAGE_OLD = "ring";
std::atomic_bool Manager::initialized = {false};
static void
copy_over(const std::string& srcPath, const std::string& destPath)
{
std::ifstream src = fileutils::ifstream(srcPath.c_str());
std::ofstream dest = fileutils::ofstream(destPath.c_str());
dest << src.rdbuf();
src.close();
dest.close();
}
// Creates a backup of the file at "path" with a .bak suffix appended
static void
make_backup(const std::string& path)
{
const std::string backup_path(path + ".bak");
copy_over(path, backup_path);
}
// Restore last backup of the configuration file
static void
restore_backup(const std::string& path)
{
const std::string backup_path(path + ".bak");
copy_over(backup_path, path);
}
void
check_rename(const std::string& old_dir, const std::string& new_dir)
{
if (old_dir == new_dir or not fileutils::isDirectory(old_dir))
return;
if (not fileutils::isDirectory(new_dir)) {
JAMI_WARN() << "Migrating " << old_dir << " to " << new_dir;
std::rename(old_dir.c_str(), new_dir.c_str());
} else {
for (const auto& file : fileutils::readDirectory(old_dir)) {
auto old_dest = fileutils::getFullPath(old_dir, file);
auto new_dest = fileutils::getFullPath(new_dir, file);
if (fileutils::isDirectory(old_dest) and fileutils::isDirectory(new_dest)) {
check_rename(old_dest, new_dest);
} else {
JAMI_WARN() << "Migrating " << old_dest << " to " << new_dest;
std::rename(old_dest.c_str(), new_dest.c_str());
}
}
fileutils::removeAll(old_dir);
}
}
/**
* Set OpenDHT's log level based on the DHTLOGLEVEL environment variable.
* DHTLOGLEVEL = 0 minimum logging (=disable)
* DHTLOGLEVEL = 1 (=ERROR only)
* DHTLOGLEVEL = 2 (+=WARN)
* DHTLOGLEVEL = 3 maximum logging (+=DEBUG)
*/
/** Environment variable used to set OpenDHT's logging level */
static constexpr const char* DHTLOGLEVEL = "DHTLOGLEVEL";
static void
setDhtLogLevel()
{
#ifndef RING_UWP
char* envvar = getenv(DHTLOGLEVEL);
int level = 0;
if (envvar != nullptr) {
if (not(std::istringstream(envvar) >> level))
level = 0;
// From 0 (min) to 3 (max)
level = std::max(0, std::min(level, 3));
JAMI_DBG("DHTLOGLEVEL=%u", level);
}
Manager::instance().dhtLogLevel = level;
#else
Manager::instance().dhtLogLevel = 0;
#endif
}
/**
* Set pjsip's log level based on the SIPLOGLEVEL environment variable.
* SIPLOGLEVEL = 0 minimum logging
* SIPLOGLEVEL = 6 maximum logging
*/
/** Environment variable used to set pjsip's logging level */
static constexpr const char* SIPLOGLEVEL = "SIPLOGLEVEL";
static void
setSipLogLevel()
{
#ifndef RING_UWP
char* envvar = getenv(SIPLOGLEVEL);
int level = 0;
if (envvar != nullptr) {
if (not(std::istringstream(envvar) >> level))
level = 0;
// From 0 (min) to 6 (max)
level = std::max(0, std::min(level, 6));
}
#else
int level = 0;
#endif
pj_log_set_level(level);
pj_log_set_log_func([](int level, const char* data, int /*len*/) {
if (level < 2)
JAMI_ERR() << data;
else if (level < 4)
JAMI_WARN() << data;
else
JAMI_DBG() << data;
});
}
/**
* Set gnutls's log level based on the RING_TLS_LOGLEVEL environment variable.
* RING_TLS_LOGLEVEL = 0 minimum logging (default)
* RING_TLS_LOGLEVEL = 9 maximum logging
*/
static constexpr int RING_TLS_LOGLEVEL = 0;
static void
tls_print_logs(int level, const char* msg)
{
JAMI_XDBG("[%d]GnuTLS: %s", level, msg);
}
static void
setGnuTlsLogLevel()
{
#ifndef RING_UWP
char* envvar = getenv("RING_TLS_LOGLEVEL");
int level = RING_TLS_LOGLEVEL;
if (envvar != nullptr) {
int var_level;
if (std::istringstream(envvar) >> var_level)
level = var_level;
// From 0 (min) to 9 (max)
level = std::max(0, std::min(level, 9));
}
gnutls_global_set_log_level(level);
#else
gnutls_global_set_log_level(RING_TLS_LOGLEVEL);
#endif
gnutls_global_set_log_function(tls_print_logs);
}
//==============================================================================
struct Manager::ManagerPimpl
{
explicit ManagerPimpl(Manager& base);
bool parseConfiguration();
/*
* Play one tone
* @return false if the driver is uninitialize
*/
void playATone(Tone::ToneId toneId);
int getCurrentDeviceIndex(AudioDeviceType type);
/**
* Process remaining participant given a conference and the current call id.
* Mainly called when a participant is detached or hagned up
* @param current call id
* @param conference pointer
*/
void processRemainingParticipants(Conference& conf);
/**
* Create config directory in home user and return configuration file path
*/
std::string retrieveConfigPath() const;
void unsetCurrentCall();
void switchCall(const std::string& id);
void switchCall(const std::shared_ptr<Call>& call);
/**
* Add incoming callid to the waiting list
* @param id std::string to add
*/
void addWaitingCall(const std::string& id);
/**
* Remove incoming callid to the waiting list
* @param id std::string to remove
*/
void removeWaitingCall(const std::string& id);
void loadAccount(const YAML::Node& item, int& errorCount);
void sendTextMessageToConference(const Conference& conf,
const std::map<std::string, std::string>& messages,
const std::string& from) const noexcept;
void bindCallToConference(Call& call, Conference& conf);
void addMainParticipant(Conference& conf);
template<class T>
std::shared_ptr<T> findAccount(const std::function<bool(const std::shared_ptr<T>&)>&);
void initAudioDriver();
Manager& base_; // pimpl back-pointer
std::shared_ptr<asio::io_context> ioContext_;
std::thread ioContextRunner_;
/** Main scheduler */
ScheduledExecutor scheduler_;
std::atomic_bool autoAnswer_ {false};
/** Application wide tone controller */
ToneControl toneCtrl_;
std::unique_ptr<AudioDeviceGuard> toneDeviceGuard_;
/** Current Call ID */
std::string currentCall_;
/** Protected current call access */
std::mutex currentCallMutex_;
/** Audio layer */
std::shared_ptr<AudioLayer> audiodriver_ {nullptr};
std::array<std::atomic_uint, 3> audioStreamUsers_ {};
// Main thread
std::unique_ptr<DTMF> dtmfKey_;
/** Buffer to generate DTMF */
AudioBuffer dtmfBuf_;
// To handle volume control
// short speakerVolume_;
// short micVolume_;
// End of sound variable
/**
* Mutex used to protect audio layer
*/
std::mutex audioLayerMutex_;
/**
* Waiting Call Vectors
*/
CallIDSet waitingCalls_;
/**
* Protect waiting call list, access by many voip/audio threads
*/
std::mutex waitingCallsMutex_;
/**
* Path of the ConfigFile
*/
std::string path_;
/**
* Instance of the RingBufferPool for the whole application
*
* In order to send signal to other parts of the application, one must pass through the
* RingBufferMananger. Audio instances must be registered into the RingBufferMananger and bound
* together via the Manager.
*
*/
std::unique_ptr<RingBufferPool> ringbufferpool_;
// Map containing conference pointers
ConferenceMap conferenceMap_;
std::atomic_bool finished_ {false};
std::mt19937_64 rand_;
/* ICE support */
std::unique_ptr<IceTransportFactory> ice_tf_;
/* Sink ID mapping */
std::map<std::string, std::weak_ptr<video::SinkClient>> sinkMap_;
#ifdef ENABLE_VIDEO
std::unique_ptr<VideoManager> videoManager_;
#endif
std::unique_ptr<SIPVoIPLink> sipLink_;
#ifdef ENABLE_PLUGIN
/* Jami Plugin Manager */
JamiPluginManager jami_plugin_manager;
#endif
};
Manager::ManagerPimpl::ManagerPimpl(Manager& base)
: base_(base)
, ioContext_(std::make_shared<asio::io_context>())
, toneCtrl_(base.preferences)
, dtmfBuf_(0, AudioFormat::MONO())
, ringbufferpool_(new RingBufferPool)
, rand_(dht::crypto::getSeededRandomEngine<std::mt19937_64>())
#ifdef ENABLE_VIDEO
, videoManager_(new VideoManager)
#endif
{
jami::libav_utils::av_init();
ioContextRunner_ = std::thread([context = ioContext_]() {
try {
auto work = asio::make_work_guard(*context);
context->run();
} catch (const std::exception& ex) {
JAMI_ERR("Unexpected io_context thread exception: %s", ex.what());
}
});
}
bool
Manager::ManagerPimpl::parseConfiguration()
{
bool result = true;
try {
std::ifstream file = fileutils::ifstream(path_);
YAML::Node parsedFile = YAML::Load(file);
file.close();
const int error_count = base_.loadAccountMap(parsedFile);
if (error_count > 0) {
JAMI_WARN("Errors while parsing %s", path_.c_str());
result = false;
}
} catch (const YAML::BadFile& e) {
JAMI_WARN("Could not open configuration file");
result = false;
}
return result;
}
/**
* Multi Thread
*/
void
Manager::ManagerPimpl::playATone(Tone::ToneId toneId)
{
if (not base_.voipPreferences.getPlayTones())
return;
std::lock_guard<std::mutex> lock(audioLayerMutex_);
if (not audiodriver_) {
JAMI_ERR("Audio layer not initialized");
return;
}
auto oldGuard = std::move(toneDeviceGuard_);
toneDeviceGuard_ = base_.startAudioStream(AudioDeviceType::PLAYBACK);
audiodriver_->flushUrgent();
toneCtrl_.play(toneId);
}
int
Manager::ManagerPimpl::getCurrentDeviceIndex(AudioDeviceType type)
{
if (not audiodriver_)
return -1;
switch (type) {
case AudioDeviceType::PLAYBACK:
return audiodriver_->getIndexPlayback();
case AudioDeviceType::RINGTONE:
return audiodriver_->getIndexRingtone();
case AudioDeviceType::CAPTURE:
return audiodriver_->getIndexCapture();
default:
return -1;
}
}
void
Manager::ManagerPimpl::processRemainingParticipants(Conference& conf)
{
const std::string current_call_id(base_.getCurrentCallId());
ParticipantSet participants(conf.getParticipantList());
const size_t n = participants.size();
JAMI_DBG("Process remaining %zu participant(s) from conference %s", n, conf.getConfID().c_str());
if (n > 1) {
// Reset ringbuffer's readpointers
for (const auto& p : participants)
base_.getRingBufferPool().flush(p);
base_.getRingBufferPool().flush(RingBufferPool::DEFAULT_ID);
} else if (n == 1) {
// this call is the last participant, hence
// the conference is over
auto p = participants.begin();
if (auto call = base_.getCallFromCallID(*p)) {
// if we are not listening to this conference and not a rendez-vous
auto w = call->getAccount();
auto account = w.lock();
if (!account) {
JAMI_ERR("No account detected");
return;
}
if (account->isRendezVous())
return;
call->setConfId("");
if (current_call_id != conf.getConfID())
base_.onHoldCall(call->getCallId());
else
switchCall(call);
}
JAMI_DBG("No remaining participants, remove conference");
base_.removeConference(conf.getConfID());
} else {
JAMI_DBG("No remaining participants, remove conference");
base_.removeConference(conf.getConfID());
unsetCurrentCall();
}
}
/**
* Initialization: Main Thread
*/
std::string
Manager::ManagerPimpl::retrieveConfigPath() const
{
static const char* const PROGNAME = "dring";
return fileutils::get_config_dir() + DIR_SEPARATOR_STR + PROGNAME + ".yml";
}
void
Manager::ManagerPimpl::unsetCurrentCall()
{
currentCall_ = "";
}
void
Manager::ManagerPimpl::switchCall(const std::string& id)
{
std::lock_guard<std::mutex> m(currentCallMutex_);
JAMI_DBG("----- Switch current call id to '%s' -----", not id.empty() ? id.c_str() : "none");
currentCall_ = id;
}
void
Manager::ManagerPimpl::switchCall(const std::shared_ptr<Call>& call)
{
switchCall(call->getCallId());
}
void
Manager::ManagerPimpl::addWaitingCall(const std::string& id)
{
std::lock_guard<std::mutex> m(waitingCallsMutex_);
waitingCalls_.insert(id);
}
void
Manager::ManagerPimpl::removeWaitingCall(const std::string& id)
{
std::lock_guard<std::mutex> m(waitingCallsMutex_);
waitingCalls_.erase(id);
}
void
Manager::ManagerPimpl::loadAccount(const YAML::Node& node, int& errorCount)
{
using yaml_utils::parseValue;
std::string accountType;
parseValue(node, "type", accountType);
std::string accountid;
parseValue(node, "id", accountid);
if (!accountid.empty()) {
if (base_.accountFactory.isSupportedType(accountType.c_str())) {
if (auto a = base_.accountFactory.createAccount(accountType.c_str(), accountid)) {
a->unserialize(node);
} else {
JAMI_ERR("Failed to create account type \"%s\"", accountType.c_str());
++errorCount;
}
} else {
JAMI_WARN("Ignoring unknown account type \"%s\"", accountType.c_str());
}
}
}
// THREAD=VoIP
void
Manager::ManagerPimpl::sendTextMessageToConference(const Conference& conf,
const std::map<std::string, std::string>& messages,
const std::string& from) const noexcept
{
ParticipantSet participants(conf.getParticipantList());
for (const auto& call_id : participants) {
try {
auto call = base_.getCallFromCallID(call_id);
if (not call)
throw std::runtime_error("no associated call");
call->sendTextMessage(messages, from);
} catch (const std::exception& e) {
JAMI_ERR("Failed to send message to conference participant %s: %s",
call_id.c_str(),
e.what());
}
}
}
void
Manager::ManagerPimpl::bindCallToConference(Call& call, Conference& conf)
{
const auto& call_id = call.getCallId();
const auto& conf_id = conf.getConfID();
const auto& state = call.getStateStr();
// ensure that calls are only in one conference at a time
if (base_.isConferenceParticipant(call_id))
base_.detachParticipant(call_id);
JAMI_DBG("[call:%s] bind to conference %s (callState=%s)",
call_id.c_str(),
conf_id.c_str(),
state.c_str());
base_.getRingBufferPool().unBindAll(call_id);
conf.add(call_id);
call.setConfId(conf_id);
if (state == "HOLD") {
conf.bindParticipant(call_id);
base_.offHoldCall(call_id);
} else if (state == "INCOMING") {
conf.bindParticipant(call_id);
base_.answerCall(call_id);
} else if (state == "CURRENT") {
conf.bindParticipant(call_id);
} else if (state == "INACTIVE") {
conf.bindParticipant(call_id);
base_.answerCall(call_id);
} else
JAMI_WARN("[call:%s] call state %s not recognized for conference",
call_id.c_str(),
state.c_str());
}
//==============================================================================
Manager&
Manager::instance()
{
// Meyers singleton
static Manager instance;
// This will give a warning that can be ignored the first time instance()
// is called...subsequent warnings are more serious
if (not Manager::initialized)
JAMI_DBG("Not initialized");
return instance;
}
Manager::Manager()
: preferences()
, voipPreferences()
, audioPreference()
, shortcutPreferences()
#ifdef ENABLE_PLUGIN
, pluginPreferences()
#endif
#ifdef ENABLE_VIDEO
, videoPreferences()
#endif
, callFactory()
, accountFactory()
, dataTransfers(std::make_unique<DataTransferFacade>())
, pimpl_(new ManagerPimpl(*this))
{}
Manager::~Manager() {}
void
Manager::setAutoAnswer(bool enable)
{
pimpl_->autoAnswer_ = enable;
}
void
Manager::init(const std::string& config_file)
{
// FIXME: this is no good
initialized = true;
#ifndef WIN32
// Set the max number of open files.
struct rlimit nofiles;
if (getrlimit(RLIMIT_NOFILE, &nofiles) == 0) {
if (nofiles.rlim_cur < nofiles.rlim_max && nofiles.rlim_cur < 1024u) {
nofiles.rlim_cur = std::min<rlim_t>(nofiles.rlim_max, 8192u);
setrlimit(RLIMIT_NOFILE, &nofiles);
}
}
#endif
#define PJSIP_TRY(ret) \
do { \
if ((ret) != PJ_SUCCESS) \
throw std::runtime_error(#ret " failed"); \
} while (0)
srand(time(nullptr)); // to get random number for RANDOM_PORT
// Initialize PJSIP (SIP and ICE implementation)
PJSIP_TRY(pj_init());
setSipLogLevel();
PJSIP_TRY(pjlib_util_init());
PJSIP_TRY(pjnath_init());
#undef PJSIP_TRY
setGnuTlsLogLevel();
JAMI_DBG("Using PJSIP version %s for %s", pj_get_version(), PJ_OS_NAME);
JAMI_DBG("Using GnuTLS version %s", gnutls_check_version(nullptr));
JAMI_DBG("Using OpenDHT version %s", dht::version());
JAMI_DBG("Using FFmpeg version %s", av_version_info());
setDhtLogLevel();
// Manager can restart without being recreated (Unit tests)
// So only create the SipLink once
pimpl_->sipLink_ = std::make_unique<SIPVoIPLink>();
check_rename(fileutils::get_cache_dir(PACKAGE_OLD), fileutils::get_cache_dir());
check_rename(fileutils::get_data_dir(PACKAGE_OLD), fileutils::get_data_dir());
check_rename(fileutils::get_config_dir(PACKAGE_OLD), fileutils::get_config_dir());
pimpl_->ice_tf_.reset(new IceTransportFactory());
pimpl_->path_ = config_file.empty() ? pimpl_->retrieveConfigPath() : config_file;
JAMI_DBG("Configuration file path: %s", pimpl_->path_.c_str());
bool no_errors = true;
// manager can restart without being recreated (Unit tests)
pimpl_->finished_ = false;
try {
no_errors = pimpl_->parseConfiguration();
} catch (const YAML::Exception& e) {
JAMI_ERR("%s", e.what());
no_errors = false;
}
// Some VoIP services support SIP/TLS and SRTP, but do not set the
// correct schema in the INVITE request. For more details, see:
// https://trac.pjsip.org/repos/ticket/1735
if (voipPreferences.getDisableSecureDlgCheck()) {
pjsip_cfg()->endpt.disable_secure_dlg_check = PJ_TRUE;
}
// always back up last error-free configuration
if (no_errors) {
make_backup(pimpl_->path_);
} else {
// restore previous configuration
JAMI_WARN("Restoring last working configuration");
try {
// remove accounts from broken configuration
removeAccounts();
restore_backup(pimpl_->path_);
pimpl_->parseConfiguration();
} catch (const YAML::Exception& e) {
JAMI_ERR("%s", e.what());
JAMI_WARN("Restoring backup failed");
}
}
{
std::lock_guard<std::mutex> lock(pimpl_->audioLayerMutex_);
pimpl_->initAudioDriver();
if (pimpl_->audiodriver_) {
pimpl_->toneCtrl_.setSampleRate(pimpl_->audiodriver_->getSampleRate());
pimpl_->dtmfKey_.reset(new DTMF(getRingBufferPool().getInternalSamplingRate()));
}
}
registerAccounts();
}
void
Manager::finish() noexcept
{
bool expected = false;
if (not pimpl_->finished_.compare_exchange_strong(expected, true))
return;
try {
// Forbid call creation
callFactory.forbid();
// Hangup all remaining active calls
JAMI_DBG("Hangup %zu remaining call(s)", callFactory.callCount());
for (const auto call : callFactory.getAllCalls())
hangupCall(call->getCallId());
callFactory.clear();
for (const auto& account : getAllAccounts<JamiAccount>()) {
if (account->getRegistrationState() == RegistrationState::INITIALIZING)
removeAccount(account->getAccountID(), true);
}
saveConfig();
// Disconnect accounts, close link stacks and free allocated ressources
unregisterAccounts();
accountFactory.clear();
{
std::lock_guard<std::mutex> lock(pimpl_->audioLayerMutex_);
pimpl_->audiodriver_.reset();
}
// Flush remaining tasks (free lambda' with capture)
pimpl_->scheduler_.stop();
dht::ThreadPool::io().join();
dht::ThreadPool::computation().join();
// IceTransportFactory should be stopped after the io pool
// as some ICE are destroyed in a ioPool (see ConnectionManager)
// Also, it must be called before pj_shutdown to avoid any problem
pimpl_->ice_tf_.reset();
// NOTE: sipLink_->shutdown() is needed because this will perform
// sipTransportBroker->shutdown(); which will call Manager::instance().sipVoIPLink()
// so the pointer MUST NOT be resetted at this point
pimpl_->sipLink_->shutdown();
pimpl_->sipLink_.reset();
pj_shutdown();
if (!pimpl_->ioContext_->stopped()) {
pimpl_->ioContext_->reset(); // allow to finish
pimpl_->ioContext_->stop(); // make thread stop
}
if (pimpl_->ioContextRunner_.joinable())
pimpl_->ioContextRunner_.join();
} catch (const VoipLinkException& err) {
JAMI_ERR("%s", err.what());
}
}
bool
Manager::isCurrentCall(const Call& call) const
{
return pimpl_->currentCall_ == call.getCallId();
}
bool
Manager::hasCurrentCall() const
{
for (const auto& call : callFactory.getAllCalls()) {
if (!call->isSubcall() && call->getStateStr() == DRing::Call::StateEvent::CURRENT)
return true;
}
return false;
}
std::shared_ptr<Call>
Manager::getCurrentCall() const
{
return getCallFromCallID(pimpl_->currentCall_);
}
const std::string&
Manager::getCurrentCallId() const
{
return pimpl_->currentCall_;
}
void
Manager::unregisterAccounts()
{
for (const auto& account : getAllAccounts()) {
if (account->isEnabled())
account->doUnregister();
}
}
///////////////////////////////////////////////////////////////////////////////
// Management of events' IP-phone user
///////////////////////////////////////////////////////////////////////////////
/* Main Thread */
std::string
Manager::outgoingCall(const std::string& account_id,
const std::string& to,
const std::string& conf_id,
const std::map<std::string, std::string>& volatileCallDetails)
{
if (not conf_id.empty() and not isConference(conf_id)) {
JAMI_ERR("outgoingCall() failed, invalid conference id");
return {};
}
JAMI_DBG() << "try outgoing call to '" << to << "'"
<< " with account '" << account_id << "'";
std::shared_ptr<Call> call;
try {
call = newOutgoingCall(trim(to), account_id, volatileCallDetails);
} catch (const std::exception& e) {
JAMI_ERR("%s", e.what());
return {};
}
if (not call)
return {};
auto call_id = call->getCallId();
stopTone();
pimpl_->switchCall(call);
call->setConfId(conf_id);
return call_id;
}
// THREAD=Main : for outgoing Call
bool
Manager::answerCall(const std::string& call_id)
{
JAMI_INFO("Answer call %s", call_id.c_str());
bool result = true;
auto call = getCallFromCallID(call_id);
if (!call) {
JAMI_ERR("Call %s is NULL", call_id.c_str());
return false;
}
if (call->getConnectionState() != Call::ConnectionState::RINGING) {
// The call is already answered
return true;
}