/
PeerConnectionManager.cpp
executable file
·979 lines (860 loc) · 32.2 KB
/
PeerConnectionManager.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
/* ---------------------------------------------------------------------------
** This software is in the public domain, furnished "as is", without technical
** support, and with no warranty, express or implied, as to its usefulness for
** any purpose.
**
** PeerConnectionManager.cpp
**
** -------------------------------------------------------------------------*/
#include <iostream>
#include <fstream>
#include <utility>
#include "api/video_codecs/builtin_video_decoder_factory.h"
#include "api/video_codecs/builtin_video_encoder_factory.h"
#include "api/audio_codecs/builtin_audio_encoder_factory.h"
#include "api/audio_codecs/builtin_audio_decoder_factory.h"
#include "api/test/fakeconstraints.h"
#include "PeerConnectionManager.h"
#include "V4l2AlsaMap.h"
#include "CapturerFactory.h"
#ifdef HAVE_LIVE555
#include "rtspaudiocapturer.h"
#endif
// Names used for a IceCandidate JSON object.
const char kCandidateSdpMidName[] = "sdpMid";
const char kCandidateSdpMlineIndexName[] = "sdpMLineIndex";
const char kCandidateSdpName[] = "candidate";
// Names used for a SessionDescription JSON object.
const char kSessionDescriptionTypeName[] = "type";
const char kSessionDescriptionSdpName[] = "sdp";
/* ---------------------------------------------------------------------------
** helpers that should be moved somewhere else
** -------------------------------------------------------------------------*/
#ifdef WIN32
std::string getServerIpFromClientIp(int clientip) {
return "127.0.0.1";
}
#else
#include <net/if.h>
#include <ifaddrs.h>
std::string getServerIpFromClientIp(int clientip) {
std::string serverAddress;
char host[NI_MAXHOST];
struct ifaddrs *ifaddr = NULL;
if (getifaddrs(&ifaddr) == 0)
{
for (struct ifaddrs* ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
if ( (ifa->ifa_netmask != NULL) && (ifa->ifa_netmask->sa_family == AF_INET) && (ifa->ifa_addr != NULL) && (ifa->ifa_addr->sa_family == AF_INET) )
{
struct sockaddr_in* addr = (struct sockaddr_in*)ifa->ifa_addr;
struct sockaddr_in* mask = (struct sockaddr_in*)ifa->ifa_netmask;
if ( (addr->sin_addr.s_addr & mask->sin_addr.s_addr) == (clientip & mask->sin_addr.s_addr) )
{
if (getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, sizeof(host), NULL, 0, NI_NUMERICHOST) == 0)
{
serverAddress = host;
break;
}
}
}
}
}
freeifaddrs(ifaddr);
return serverAddress;
}
#endif
struct IceServer {
std::string url;
std::string user;
std::string pass;
};
IceServer getIceServerFromUrl(const std::string & url, const std::string& clientIp = "") {
IceServer srv;
srv.url = url;
std::size_t pos = url.find_first_of(':');
if (pos != std::string::npos)
{
std::string protocol = url.substr(0, pos);
std::string uri = url.substr(pos + 1);
std::string credentials;
std::size_t pos = uri.find('@');
if (pos != std::string::npos)
{
credentials = uri.substr(0, pos);
uri = uri.substr(pos + 1);
}
if ( (uri.find("0.0.0.0:") == 0) && (clientIp.empty() == false)) {
// answer with ip that is on same network as client
std::string clienturl = getServerIpFromClientIp(inet_addr(clientIp.c_str()));
clienturl += uri.substr(uri.find_first_of(':'));
uri = clienturl;
}
srv.url = protocol + ":" + uri;
if (!credentials.empty()) {
pos = credentials.find(':');
if (pos == std::string::npos)
{
srv.user = credentials;
}
else
{
srv.user = credentials.substr(0, pos);
srv.pass = credentials.substr(pos + 1);
}
}
}
return srv;
}
/* ---------------------------------------------------------------------------
** Constructor
** -------------------------------------------------------------------------*/
PeerConnectionManager::PeerConnectionManager( const std::list<std::string> & iceServerList
, const std::map<std::string,std::string> & urlVideoList
, const std::map<std::string,std::string> & urlAudioList
, const webrtc::AudioDeviceModule::AudioLayer audioLayer
, const std::string& publishFilter)
: audioDeviceModule_(webrtc::AudioDeviceModule::Create(0, audioLayer))
, audioDecoderfactory_(webrtc::CreateBuiltinAudioDecoderFactory())
, peer_connection_factory_(webrtc::CreatePeerConnectionFactory(NULL,
rtc::Thread::Current(),
NULL,
audioDeviceModule_,
webrtc::CreateBuiltinAudioEncoderFactory(),
audioDecoderfactory_,
webrtc::CreateBuiltinVideoEncoderFactory(),
webrtc::CreateBuiltinVideoDecoderFactory(),
NULL, NULL))
, iceServerList_(iceServerList)
, m_urlVideoList(urlVideoList)
, m_urlAudioList(urlAudioList)
, m_publishFilter(publishFilter)
{
// build video audio map
m_videoaudiomap = getV4l2AlsaMap();
}
/* ---------------------------------------------------------------------------
** Destructor
** -------------------------------------------------------------------------*/
PeerConnectionManager::~PeerConnectionManager()
{
}
/* ---------------------------------------------------------------------------
** return deviceList as JSON vector
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getMediaList()
{
Json::Value value(Json::arrayValue);
const std::list<std::string> videoCaptureDevice = CapturerFactory::GetVideoCaptureDeviceList(m_publishFilter);
for (auto videoDevice : videoCaptureDevice) {
Json::Value media;
media["video"] = videoDevice;
std::map<std::string,std::string>::iterator it = m_videoaudiomap.find(videoDevice);
if (it != m_videoaudiomap.end()) {
media["audio"] = it->second;
}
value.append(media);
}
const std::list<std::string> videoList = CapturerFactory::GetVideoSourceList(m_publishFilter);
for (auto videoSource : videoList) {
Json::Value media;
media["video"] = videoSource;
value.append(media);
}
for (auto url : m_urlVideoList)
{
Json::Value media;
media["video"] = url.first;
auto audioIt = m_urlAudioList.find(url.first);
if (audioIt != m_urlAudioList.end())
{
media["audio"] = audioIt->first;
}
value.append(media);
}
return value;
}
/* ---------------------------------------------------------------------------
** return video device List as JSON vector
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getVideoDeviceList()
{
Json::Value value(Json::arrayValue);
const std::list<std::string> videoCaptureDevice = CapturerFactory::GetVideoCaptureDeviceList(m_publishFilter);
for (auto videoDevice : videoCaptureDevice) {
value.append(videoDevice);
}
return value;
}
/* ---------------------------------------------------------------------------
** return audio device List as JSON vector
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getAudioDeviceList()
{
Json::Value value(Json::arrayValue);
if (std::regex_match("audiocap://",m_publishFilter)) {
int16_t num_audioDevices = audioDeviceModule_->RecordingDevices();
RTC_LOG(INFO) << "nb audio devices:" << num_audioDevices;
for (int i = 0; i < num_audioDevices; ++i)
{
char name[webrtc::kAdmMaxDeviceNameSize] = {0};
char id[webrtc::kAdmMaxGuidSize] = {0};
if (audioDeviceModule_->RecordingDeviceName(i, name, id) != -1)
{
RTC_LOG(INFO) << "audio device name:" << name << " id:" << id;
value.append(name);
}
}
}
return value;
}
/* ---------------------------------------------------------------------------
** return iceServers as JSON vector
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getIceServers(const std::string& clientIp)
{
Json::Value urls;
for (auto iceServer : iceServerList_) {
Json::Value server;
Json::Value urlList(Json::arrayValue);
IceServer srv = getIceServerFromUrl(iceServer, clientIp);
RTC_LOG(INFO) << "ICE URL:" << srv.url;
urlList.append(srv.url);
server["urls"] = urlList;
if (srv.user.length() > 0) server["username"] = srv.user;
if (srv.pass.length() > 0) server["credential"] = srv.pass;
urls.append(server);
}
Json::Value iceServers;
iceServers["iceServers"] = urls;
return iceServers;
}
/* ---------------------------------------------------------------------------
** get PeerConnection associated with peerid
** -------------------------------------------------------------------------*/
rtc::scoped_refptr<webrtc::PeerConnectionInterface> PeerConnectionManager::getPeerConnection(const std::string& peerid)
{
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection;
std::map<std::string, PeerConnectionObserver* >::iterator it = peer_connectionobs_map_.find(peerid);
if (it != peer_connectionobs_map_.end())
{
peerConnection = it->second->getPeerConnection();
}
return peerConnection;
}
/* ---------------------------------------------------------------------------
** add ICE candidate to a PeerConnection
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::addIceCandidate(const std::string& peerid, const Json::Value& jmessage)
{
bool result = false;
std::string sdp_mid;
int sdp_mlineindex = 0;
std::string sdp;
if ( !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpMidName, &sdp_mid)
|| !rtc::GetIntFromJsonObject(jmessage, kCandidateSdpMlineIndexName, &sdp_mlineindex)
|| !rtc::GetStringFromJsonObject(jmessage, kCandidateSdpName, &sdp))
{
RTC_LOG(WARNING) << "Can't parse received message:" << jmessage;
}
else
{
std::unique_ptr<webrtc::IceCandidateInterface> candidate(webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, sdp, NULL));
if (!candidate.get())
{
RTC_LOG(WARNING) << "Can't parse received candidate message.";
}
else
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = this->getPeerConnection(peerid);
if (peerConnection)
{
if (!peerConnection->AddIceCandidate(candidate.get()))
{
RTC_LOG(WARNING) << "Failed to apply the received candidate";
}
else
{
result = true;
}
}
}
}
Json::Value answer;
if (result) {
answer = result;
}
return answer;
}
/* ---------------------------------------------------------------------------
** create an offer for a call
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::createOffer(const std::string &peerid, const std::string & videourl, const std::string & audiourl, const std::string & options)
{
RTC_LOG(INFO) << __FUNCTION__ << " video:" << videourl << " audio:" << audiourl << " options:" << options ;
Json::Value offer;
PeerConnectionObserver* peerConnectionObserver = this->CreatePeerConnection(peerid);
if (!peerConnectionObserver)
{
RTC_LOG(LERROR) << "Failed to initialize PeerConnection";
}
else
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = peerConnectionObserver->getPeerConnection();
if (!this->AddStreams(peerConnectionObserver->getPeerConnection(), videourl, audiourl, options))
{
RTC_LOG(WARNING) << "Can't add stream";
}
// register peerid
{
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
peer_connectionobs_map_.insert(std::pair<std::string, PeerConnectionObserver* >(peerid, peerConnectionObserver));
}
// ask to create offer
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions rtcoptions;
peerConnectionObserver->getPeerConnection()->CreateOffer(CreateSessionDescriptionObserver::Create(peerConnectionObserver->getPeerConnection()), rtcoptions);
// waiting for offer
int count=10;
while ( (peerConnectionObserver->getPeerConnection()->local_description() == NULL) && (--count > 0) ) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
// answer with the created offer
const webrtc::SessionDescriptionInterface* desc = peerConnectionObserver->getPeerConnection()->local_description();
if (desc)
{
std::string sdp;
desc->ToString(&sdp);
offer[kSessionDescriptionTypeName] = desc->type();
offer[kSessionDescriptionSdpName] = sdp;
}
else
{
RTC_LOG(LERROR) << "Failed to create offer";
}
}
return offer;
}
/* ---------------------------------------------------------------------------
** set answer to a call initiated by createOffer
** -------------------------------------------------------------------------*/
void PeerConnectionManager::setAnswer(const std::string &peerid, const Json::Value& jmessage)
{
RTC_LOG(INFO) << jmessage;
std::string type;
std::string sdp;
if ( !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type)
|| !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp))
{
RTC_LOG(WARNING) << "Can't parse received message.";
}
else
{
webrtc::SessionDescriptionInterface* session_description(webrtc::CreateSessionDescription(type, sdp, NULL));
if (!session_description)
{
RTC_LOG(WARNING) << "Can't parse received session description message.";
}
else
{
RTC_LOG(LERROR) << "From peerid:" << peerid << " received session description :" << session_description->type();
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = this->getPeerConnection(peerid);
if (peerConnection)
{
peerConnection->SetRemoteDescription(SetSessionDescriptionObserver::Create(peerConnection), session_description);
}
}
}
}
/* ---------------------------------------------------------------------------
** auto-answer to a call
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::call(const std::string & peerid, const std::string & videourl, const std::string & audiourl, const std::string & options, const Json::Value& jmessage)
{
RTC_LOG(INFO) << __FUNCTION__ << " video:" << videourl << " audio:" << audiourl << " options:" << options ;
Json::Value answer;
std::string type;
std::string sdp;
if ( !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionTypeName, &type)
|| !rtc::GetStringFromJsonObject(jmessage, kSessionDescriptionSdpName, &sdp))
{
RTC_LOG(WARNING) << "Can't parse received message.";
}
else
{
PeerConnectionObserver* peerConnectionObserver = this->CreatePeerConnection(peerid);
if (!peerConnectionObserver)
{
RTC_LOG(LERROR) << "Failed to initialize PeerConnectionObserver";
}
else if (!peerConnectionObserver->getPeerConnection().get())
{
RTC_LOG(LERROR) << "Failed to initialize PeerConnection";
delete peerConnectionObserver;
}
else
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = peerConnectionObserver->getPeerConnection();
RTC_LOG(INFO) << "nbStreams local:" << peerConnection->local_streams()->count() << " remote:" << peerConnection->remote_streams()->count() << " localDescription:" << peerConnection->local_description();
// register peerid
{
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
peer_connectionobs_map_.insert(std::pair<std::string, PeerConnectionObserver* >(peerid, peerConnectionObserver));
}
// set remote offer
webrtc::SessionDescriptionInterface* session_description(webrtc::CreateSessionDescription(type, sdp, NULL));
if (!session_description)
{
RTC_LOG(WARNING) << "Can't parse received session description message.";
}
else
{
peerConnection->SetRemoteDescription(SetSessionDescriptionObserver::Create(peerConnection), session_description);
}
// waiting for remote description
int count=10;
while ( (peerConnection->remote_description() == NULL) && (--count > 0) ) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
if (peerConnection->remote_description() == NULL) {
RTC_LOG(WARNING) << "remote_description is NULL";
}
// add local stream
if (!this->AddStreams(peerConnection, videourl, audiourl, options))
{
RTC_LOG(WARNING) << "Can't add stream";
}
// create answer
webrtc::PeerConnectionInterface::RTCOfferAnswerOptions rtcoptions;
rtcoptions.offer_to_receive_video = 0;
rtcoptions.offer_to_receive_audio = 0;
peerConnection->CreateAnswer(CreateSessionDescriptionObserver::Create(peerConnection), rtcoptions);
RTC_LOG(INFO) << "nbStreams local:" << peerConnection->local_streams()->count() << " remote:" << peerConnection->remote_streams()->count()
<< " localDescription:" << peerConnection->local_description()
<< " remoteDescription:" << peerConnection->remote_description();
// waiting for answer
count=10;
while ( (peerConnection->local_description() == NULL) && (--count > 0) ) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
RTC_LOG(INFO) << "nbStreams local:" << peerConnection->local_streams()->count() << " remote:" << peerConnection->remote_streams()->count()
<< " localDescription:" << peerConnection->local_description()
<< " remoteDescription:" << peerConnection->remote_description();
// return the answer
const webrtc::SessionDescriptionInterface* desc = peerConnection->local_description();
if (desc)
{
std::string sdp;
desc->ToString(&sdp);
answer[kSessionDescriptionTypeName] = desc->type();
answer[kSessionDescriptionSdpName] = sdp;
}
else
{
RTC_LOG(LERROR) << "Failed to create answer";
}
}
}
return answer;
}
bool PeerConnectionManager::streamStillUsed(const std::string & streamLabel)
{
bool stillUsed = false;
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
for (auto it: peer_connectionobs_map_)
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = it.second->getPeerConnection();
rtc::scoped_refptr<webrtc::StreamCollectionInterface> localstreams (peerConnection->local_streams());
for (unsigned int i = 0; i<localstreams->count(); i++)
{
if (localstreams->at(i)->id() == streamLabel)
{
stillUsed = true;
break;
}
}
}
return stillUsed;
}
/* ---------------------------------------------------------------------------
** hangup a call
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::hangUp(const std::string &peerid)
{
bool result = false;
RTC_LOG(INFO) << __FUNCTION__ << " " << peerid;
PeerConnectionObserver* pcObserver = NULL;
{
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
std::map<std::string, PeerConnectionObserver* >::iterator it = peer_connectionobs_map_.find(peerid);
if (it != peer_connectionobs_map_.end())
{
pcObserver = it->second;
RTC_LOG(LS_ERROR) << "Close PeerConnection peerid:" << peerid;
peer_connectionobs_map_.erase(it);
}
}
if (pcObserver)
{
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = pcObserver->getPeerConnection();
rtc::scoped_refptr<webrtc::StreamCollectionInterface> localstreams (peerConnection->local_streams());
for (unsigned int i = 0; i<localstreams->count(); i++)
{
std::string streamLabel = localstreams->at(i)->id();
bool stillUsed = this->streamStillUsed(streamLabel);
if (!stillUsed)
{
RTC_LOG(LS_ERROR) << "Close PeerConnection no more used " << streamLabel;
rtc::scoped_refptr<webrtc::MediaStreamInterface> mediaStream;
{
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
std::map<std::string, rtc::scoped_refptr<webrtc::MediaStreamInterface> >::iterator it = stream_map_.find(streamLabel);
if (it != stream_map_.end())
{
mediaStream = it->second;
stream_map_.erase(it);
}
}
RTC_LOG(LS_ERROR) << "Close PeerConnection removed " << streamLabel;
if (mediaStream.get() != NULL) {
// remove video tracks
while (mediaStream->GetVideoTracks().size() > 0)
{
mediaStream->RemoveTrack(mediaStream->GetVideoTracks().at(0));
}
// remove audio tracks
while (mediaStream->GetAudioTracks().size() > 0)
{
mediaStream->RemoveTrack(mediaStream->GetAudioTracks().at(0));
}
mediaStream.release();
}
}
}
delete pcObserver;
result = true;
}
Json::Value answer;
if (result) {
answer = result;
}
return answer;
}
/* ---------------------------------------------------------------------------
** get list ICE candidate associayed with a PeerConnection
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getIceCandidateList(const std::string &peerid)
{
RTC_LOG(INFO) << __FUNCTION__;
Json::Value value;
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
std::map<std::string, PeerConnectionObserver* >::iterator it = peer_connectionobs_map_.find(peerid);
if (it != peer_connectionobs_map_.end())
{
PeerConnectionObserver* obs = it->second;
if (obs)
{
value = obs->getIceCandidateList();
}
else
{
RTC_LOG(LS_ERROR) << "No observer for peer:" << peerid;
}
}
return value;
}
/* ---------------------------------------------------------------------------
** get PeerConnection list
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getPeerConnectionList()
{
Json::Value value(Json::arrayValue);
std::lock_guard<std::mutex> peerlock(m_peerMapMutex);
for (auto it : peer_connectionobs_map_)
{
Json::Value content;
// get local SDP
rtc::scoped_refptr<webrtc::PeerConnectionInterface> peerConnection = it.second->getPeerConnection();
if ( (peerConnection) && (peerConnection->local_description()) ) {
std::string sdp;
peerConnection->local_description()->ToString(&sdp);
content["sdp"] = sdp;
Json::Value streams;
rtc::scoped_refptr<webrtc::StreamCollectionInterface> localstreams (peerConnection->local_streams());
if (localstreams) {
for (unsigned int i = 0; i<localstreams->count(); i++) {
if (localstreams->at(i)) {
Json::Value tracks;
const webrtc::VideoTrackVector& videoTracks = localstreams->at(i)->GetVideoTracks();
for (unsigned int j=0; j<videoTracks.size() ; j++)
{
Json::Value track;
tracks[videoTracks.at(j)->kind()].append(videoTracks.at(j)->id());
}
const webrtc::AudioTrackVector& audioTracks = localstreams->at(i)->GetAudioTracks();
for (unsigned int j=0; j<audioTracks.size() ; j++)
{
Json::Value track;
tracks[audioTracks.at(j)->kind()].append(audioTracks.at(j)->id());
}
Json::Value stream;
stream[localstreams->at(i)->id()] = tracks;
streams.append(stream);
}
}
}
content["streams"] = streams;
}
// get Stats
// content["stats"] = it.second->getStats();
Json::Value pc;
pc[it.first] = content;
value.append(pc);
}
return value;
}
/* ---------------------------------------------------------------------------
** get StreamList list
** -------------------------------------------------------------------------*/
const Json::Value PeerConnectionManager::getStreamList()
{
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
Json::Value value(Json::arrayValue);
for (auto it : stream_map_)
{
value.append(it.first);
}
return value;
}
/* ---------------------------------------------------------------------------
** check if factory is initialized
** -------------------------------------------------------------------------*/
bool PeerConnectionManager::InitializePeerConnection()
{
return (peer_connection_factory_.get() != NULL);
}
/* ---------------------------------------------------------------------------
** create a new PeerConnection
** -------------------------------------------------------------------------*/
PeerConnectionManager::PeerConnectionObserver* PeerConnectionManager::CreatePeerConnection(const std::string& peerid)
{
webrtc::PeerConnectionInterface::RTCConfiguration config;
config.enable_dtls_srtp = true;
for (auto iceServer : iceServerList_) {
webrtc::PeerConnectionInterface::IceServer server;
IceServer srv = getIceServerFromUrl(iceServer);
server.uri = srv.url;
server.username = srv.user;
server.password = srv.pass;
config.servers.push_back(server);
}
RTC_LOG(INFO) << __FUNCTION__ << "CreatePeerConnection peerid:" << peerid;
PeerConnectionObserver* obs = new PeerConnectionObserver(this, peerid, config);
if (!obs)
{
RTC_LOG(LERROR) << __FUNCTION__ << "CreatePeerConnection failed";
}
return obs;
}
/* ---------------------------------------------------------------------------
** get the capturer from its URL
** -------------------------------------------------------------------------*/
rtc::scoped_refptr<webrtc::VideoTrackInterface> PeerConnectionManager::CreateVideoTrack(const std::string & videourl, const std::map<std::string,std::string> & opts)
{
RTC_LOG(INFO) << "videourl:" << videourl;
std::unique_ptr<cricket::VideoCapturer> capturer = CapturerFactory::CreateVideoCapturer(videourl, opts, m_publishFilter);
rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track;
if (!capturer)
{
RTC_LOG(LS_ERROR) << "Cannot create capturer video:" << videourl;
}
else
{
webrtc::FakeConstraints constraints;
std::list<std::string> keyList = { webrtc::MediaConstraintsInterface::kMinWidth, webrtc::MediaConstraintsInterface::kMaxWidth,
webrtc::MediaConstraintsInterface::kMinHeight, webrtc::MediaConstraintsInterface::kMaxHeight,
webrtc::MediaConstraintsInterface::kMinFrameRate, webrtc::MediaConstraintsInterface::kMaxFrameRate,
webrtc::MediaConstraintsInterface::kMinAspectRatio, webrtc::MediaConstraintsInterface::kMaxAspectRatio };
for (auto key : keyList) {
if (opts.find(key) != opts.end()) {
constraints.AddMandatory(key, opts.at(key));
}
}
rtc::scoped_refptr<webrtc::VideoTrackSourceInterface> videoSource = peer_connection_factory_->CreateVideoSource(std::move(capturer), &constraints);
std::string label = videourl + "_video";
label.erase(std::remove_if(label.begin(), label.end(), [](char c) { return c==' '||c==':'|| c=='.' || c=='/'; })
, label.end());
video_track = peer_connection_factory_->CreateVideoTrack(label, videoSource);
}
return video_track;
}
rtc::scoped_refptr<webrtc::AudioTrackInterface> PeerConnectionManager::CreateAudioTrack(const std::string & audiourl, const std::map<std::string,std::string> & opts)
{
RTC_LOG(INFO) << "audiourl:" << audiourl;
rtc::scoped_refptr<webrtc::AudioSourceInterface> audioSource;
if ( (audiourl.find("rtsp://") == 0) && (std::regex_match("rtsp://",m_publishFilter)) )
{
#ifdef HAVE_LIVE555
audioDeviceModule_->Terminate();
audioSource = RTSPAudioSource::Create(audioDecoderfactory_, audiourl, opts);
#endif
}
else if (std::regex_match("audiocap://",m_publishFilter))
{
audioDeviceModule_->Init();
int16_t num_audioDevices = audioDeviceModule_->RecordingDevices();
int16_t idx_audioDevice = -1;
for (int i = 0; i < num_audioDevices; ++i)
{
char name[webrtc::kAdmMaxDeviceNameSize] = {0};
char id[webrtc::kAdmMaxGuidSize] = {0};
if (audioDeviceModule_->RecordingDeviceName(i, name, id) != -1)
{
if (audiourl == name)
{
idx_audioDevice = i;
break;
}
}
}
RTC_LOG(LS_ERROR) << "audiourl:" << audiourl << " idx_audioDevice:" << idx_audioDevice;
if ( (idx_audioDevice >= 0) && (idx_audioDevice < num_audioDevices) )
{
audioDeviceModule_->SetRecordingDevice(idx_audioDevice);
cricket::AudioOptions opt;
audioSource = peer_connection_factory_->CreateAudioSource(opt);
}
}
rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track;
if (!audioSource) {
RTC_LOG(LS_ERROR) << "Cannot create capturer audio:" << audiourl;
} else {
std::string label = audiourl + "_audio";
label.erase(std::remove_if(label.begin(), label.end(), [](char c) { return c==' '||c==':'|| c=='.' || c=='/'; })
, label.end());
audio_track = peer_connection_factory_->CreateAudioTrack(label, audioSource);
}
return audio_track;
}
/* ---------------------------------------------------------------------------
** Add a stream to a PeerConnection
** -------------------------------------------------------------------------*/
bool PeerConnectionManager::AddStreams(webrtc::PeerConnectionInterface* peer_connection, const std::string & videourl, const std::string & audiourl, const std::string & options)
{
bool ret = false;
// look in urlmap
std::string video = videourl;
auto videoit = m_urlVideoList.find(video);
if (videoit != m_urlVideoList.end()) {
video = videoit->second;
}
std::string audio = audiourl;
auto audioit = m_urlAudioList.find(audio);
if (audioit != m_urlAudioList.end()) {
audio = audioit->second;
}
// compute stream label removing space because SDP use label
std::string streamLabel = video + "|" + audio + "|" + options;
streamLabel.erase(std::remove_if(streamLabel.begin(), streamLabel.end(), [](char c) { return c==' '||c==':'|| c=='.' || c=='/'; })
, streamLabel.end());
bool existingStream = false;
{
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
existingStream = (stream_map_.find(streamLabel) != stream_map_.end());
}
if (!existingStream)
{
// compute audiourl if not set
if (audio.empty()) {
if (video.find("rtsp://") == 0) {
audio = video;
} else {
std::map<std::string,std::string>::iterator it = m_videoaudiomap.find(video);
if (it != m_videoaudiomap.end()) {
audio = it->second;
}
}
}
// convert options string into map
std::istringstream is(options);
std::map<std::string,std::string> opts;
std::string key, value;
while(std::getline(std::getline(is, key, '='), value,'&')) {
opts[key] = value;
}
// set bandwidth
if (opts.find("bitrate") != opts.end()) {
int bitrate = std::stoi(opts.at("bitrate"));
webrtc::PeerConnectionInterface::BitrateParameters bitrateParam;
bitrateParam.min_bitrate_bps = absl::optional<int>(bitrate/2);
bitrateParam.current_bitrate_bps = absl::optional<int>(bitrate);
bitrateParam.max_bitrate_bps = absl::optional<int>(bitrate*2);
peer_connection->SetBitrate(bitrateParam);
RTC_LOG(WARNING) << "set bitrate:" << bitrate;
}
// need to create the stream
rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track(this->CreateVideoTrack(video, opts));
rtc::scoped_refptr<webrtc::AudioTrackInterface> audio_track(this->CreateAudioTrack(audio, opts));
rtc::scoped_refptr<webrtc::MediaStreamInterface> stream = peer_connection_factory_->CreateLocalMediaStream(streamLabel);
if (!stream.get())
{
RTC_LOG(LS_ERROR) << "Cannot create stream";
}
else
{
if ( (video_track) && (!stream->AddTrack(video_track)) )
{
RTC_LOG(LS_ERROR) << "Adding VideoTrack to MediaStream failed";
}
if ( (audio_track) && (!stream->AddTrack(audio_track)) )
{
RTC_LOG(LS_ERROR) << "Adding AudioTrack to MediaStream failed";
}
RTC_LOG(INFO) << "Adding Stream to map";
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
stream_map_[streamLabel] = stream;
}
}
{
std::lock_guard<std::mutex> mlock(m_streamMapMutex);
std::map<std::string, rtc::scoped_refptr<webrtc::MediaStreamInterface> >::iterator it = stream_map_.find(streamLabel);
if (it != stream_map_.end())
{
if (!peer_connection->AddStream(it->second))
{
RTC_LOG(LS_ERROR) << "Adding stream to PeerConnection failed";
}
else
{
RTC_LOG(INFO) << "stream added to PeerConnection";
ret = true;
}
}
else
{
RTC_LOG(LS_ERROR) << "Cannot find stream";
}
}
return ret;
}
/* ---------------------------------------------------------------------------
** ICE callback
** -------------------------------------------------------------------------*/
void PeerConnectionManager::PeerConnectionObserver::OnIceCandidate(const webrtc::IceCandidateInterface* candidate)
{
RTC_LOG(INFO) << __FUNCTION__ << " " << candidate->sdp_mline_index();
std::string sdp;
if (!candidate->ToString(&sdp))
{
RTC_LOG(LS_ERROR) << "Failed to serialize candidate";
}
else
{
RTC_LOG(INFO) << sdp;
Json::Value jmessage;
jmessage[kCandidateSdpMidName] = candidate->sdp_mid();
jmessage[kCandidateSdpMlineIndexName] = candidate->sdp_mline_index();
jmessage[kCandidateSdpName] = sdp;
iceCandidateList_.append(jmessage);
}
}