forked from paullouisageneau/libdatachannel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdescription.cpp
1327 lines (1058 loc) · 38 KB
/
description.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) 2019-2020 Paul-Louis Ageneau
* Copyright (c) 2020 Staz Modrzynski
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "description.hpp"
#include "impl/internals.hpp"
#include "impl/utils.hpp"
#include <algorithm>
#include <array>
#include <cctype>
#include <chrono>
#include <iostream>
#include <random>
#include <sstream>
#include <unordered_map>
using std::chrono::system_clock;
namespace {
using std::string;
using std::string_view;
inline bool match_prefix(string_view str, string_view prefix) {
return str.size() >= prefix.size() &&
std::mismatch(prefix.begin(), prefix.end(), str.begin()).first == prefix.end();
}
inline void trim_begin(string &str) {
str.erase(str.begin(),
std::find_if(str.begin(), str.end(), [](char c) { return !std::isspace(c); }));
}
inline void trim_end(string &str) {
str.erase(
std::find_if(str.rbegin(), str.rend(), [](char c) { return !std::isspace(c); }).base(),
str.end());
}
inline std::pair<string_view, string_view> parse_pair(string_view attr) {
string_view key, value;
if (size_t separator = attr.find(':'); separator != string::npos) {
key = attr.substr(0, separator);
value = attr.substr(separator + 1);
} else {
key = attr;
}
return std::make_pair(std::move(key), std::move(value));
}
template <typename T> T to_integer(string_view s) {
const string str(s);
try {
return std::is_signed<T>::value ? T(std::stol(str)) : T(std::stoul(str));
} catch (...) {
throw std::invalid_argument("Invalid integer \"" + str + "\" in description");
}
}
inline bool is_sha256_fingerprint(string_view f) {
if (f.size() != 32 * 3 - 1)
return false;
for (size_t i = 0; i < f.size(); ++i) {
if (i % 3 == 2) {
if (f[i] != ':')
return false;
} else {
if (!std::isxdigit(f[i]))
return false;
}
}
return true;
}
} // namespace
namespace rtc {
namespace utils = impl::utils;
Description::Description(const string &sdp, Type type, Role role)
: mType(Type::Unspec), mRole(role) {
hintType(type);
int index = -1;
shared_ptr<Entry> current;
std::istringstream ss(sdp);
while (ss) {
string line;
std::getline(ss, line);
trim_end(line);
if (line.empty())
continue;
if (match_prefix(line, "m=")) { // Media description line (aka m-line)
current = createEntry(line.substr(2), std::to_string(++index), Direction::Unknown);
} else if (match_prefix(line, "o=")) { // Origin line
std::istringstream origin(line.substr(2));
origin >> mUsername >> mSessionId;
} else if (match_prefix(line, "a=")) { // Attribute line
string attr = line.substr(2);
auto [key, value] = parse_pair(attr);
if (key == "setup") {
if (value == "active")
mRole = Role::Active;
else if (value == "passive")
mRole = Role::Passive;
else
mRole = Role::ActPass;
} else if (key == "fingerprint") {
// RFC 8122: The fingerprint attribute may be either a session-level or a
// media-level SDP attribute. If it is a session-level attribute, it applies to all
// TLS sessions for which no media-level fingerprint attribute is defined.
if (!mFingerprint || index == 0) { // first media overrides session-level
if (match_prefix(value, "sha-256 ") || match_prefix(value, "SHA-256 ")) {
string fingerprint{value.substr(8)};
trim_begin(fingerprint);
setFingerprint(std::move(fingerprint));
} else {
PLOG_WARNING << "Unknown SDP fingerprint format: " << value;
}
}
} else if (key == "ice-ufrag") {
// RFC 8839: The "ice-pwd" and "ice-ufrag" attributes can appear at either the
// session-level or media-level. When present in both, the value in the media-level
// takes precedence.
if (!mIceUfrag || index == 0) // media-level for first media overrides session-level
mIceUfrag = value;
} else if (key == "ice-pwd") {
// RFC 8839: The "ice-pwd" and "ice-ufrag" attributes can appear at either the
// session-level or media-level. When present in both, the value in the media-level
// takes precedence.
if (!mIcePwd || index == 0) // media-level for first media overrides session-level
mIcePwd = value;
} else if (key == "ice-options") {
// RFC 8839: The "ice-options" attribute is a session-level and media-level
// attribute.
if (mIceOptions.empty())
mIceOptions = utils::explode(string(value), ',');
} else if (key == "candidate") {
addCandidate(Candidate(attr, bundleMid()));
} else if (key == "end-of-candidates") {
mEnded = true;
} else if (current) {
current->parseSdpLine(std::move(line));
} else {
mAttributes.emplace_back(attr);
}
} else if (current) {
current->parseSdpLine(std::move(line));
}
}
if (mUsername.empty())
mUsername = "rtc";
if (mSessionId.empty()) {
auto uniform = std::bind(std::uniform_int_distribution<uint32_t>(), utils::random_engine());
mSessionId = std::to_string(uniform());
}
}
Description::Description(const string &sdp, string typeString)
: Description(sdp, !typeString.empty() ? stringToType(typeString) : Type::Unspec,
Role::ActPass) {}
Description::Type Description::type() const { return mType; }
string Description::typeString() const { return typeToString(mType); }
Description::Role Description::role() const { return mRole; }
string Description::bundleMid() const {
// Get the mid of the first non-removed media
for (const auto &entry : mEntries)
if (!entry->isRemoved())
return entry->mid();
return "0";
}
optional<string> Description::iceUfrag() const { return mIceUfrag; }
std::vector<string> Description::iceOptions() const { return mIceOptions; }
optional<string> Description::icePwd() const { return mIcePwd; }
optional<string> Description::fingerprint() const { return mFingerprint; }
bool Description::ended() const { return mEnded; }
void Description::hintType(Type type) {
if (mType == Type::Unspec)
mType = type;
}
void Description::setFingerprint(string fingerprint) {
if (!is_sha256_fingerprint(fingerprint))
throw std::invalid_argument("Invalid SHA256 fingerprint \"" + fingerprint + "\"");
std::transform(fingerprint.begin(), fingerprint.end(), fingerprint.begin(),
[](char c) { return char(std::toupper(c)); });
mFingerprint.emplace(std::move(fingerprint));
}
void Description::addIceOption(string option) {
if (std::find(mIceOptions.begin(), mIceOptions.end(), option) == mIceOptions.end())
mIceOptions.emplace_back(std::move(option));
}
void Description::removeIceOption(const string &option) {
mIceOptions.erase(std::remove(mIceOptions.begin(), mIceOptions.end(), option),
mIceOptions.end());
}
std::vector<string> Description::Entry::attributes() const { return mAttributes; }
void Description::Entry::addAttribute(string attr) {
if (std::find(mAttributes.begin(), mAttributes.end(), attr) == mAttributes.end())
mAttributes.emplace_back(std::move(attr));
}
void Description::Entry::removeAttribute(const string &attr) {
mAttributes.erase(
std::remove_if(mAttributes.begin(), mAttributes.end(),
[&](const auto &a) { return a == attr || parse_pair(a).first == attr; }),
mAttributes.end());
}
std::vector<Candidate> Description::candidates() const { return mCandidates; }
std::vector<Candidate> Description::extractCandidates() {
std::vector<Candidate> result;
std::swap(mCandidates, result);
mEnded = false;
return result;
}
bool Description::hasCandidate(const Candidate &candidate) const {
return std::find(mCandidates.begin(), mCandidates.end(), candidate) != mCandidates.end();
}
void Description::addCandidate(Candidate candidate) {
candidate.hintMid(bundleMid());
if (!hasCandidate(candidate))
mCandidates.emplace_back(std::move(candidate));
}
void Description::addCandidates(std::vector<Candidate> candidates) {
for (Candidate candidate : candidates)
addCandidate(std::move(candidate));
}
void Description::endCandidates() { mEnded = true; }
Description::operator string() const { return generateSdp("\r\n"); }
string Description::generateSdp(string_view eol) const {
std::ostringstream sdp;
// Header
sdp << "v=0" << eol;
sdp << "o=" << mUsername << " " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
sdp << "s=-" << eol;
sdp << "t=0 0" << eol;
// BUNDLE (RFC 8843 Negotiating Media Multiplexing Using the Session Description Protocol)
// https://www.rfc-editor.org/rfc/rfc8843.html
std::ostringstream bundleGroup;
for (const auto &entry : mEntries)
if (!entry->isRemoved())
bundleGroup << ' ' << entry->mid();
if (!bundleGroup.str().empty())
sdp << "a=group:BUNDLE" << bundleGroup.str() << eol;
// Lip-sync
std::ostringstream lsGroup;
for (const auto &entry : mEntries)
if (!entry->isRemoved() && entry != mApplication)
lsGroup << ' ' << entry->mid();
if (!lsGroup.str().empty())
sdp << "a=group:LS" << lsGroup.str() << eol;
// Session-level attributes
sdp << "a=msid-semantic:WMS *" << eol;
sdp << "a=setup:" << mRole << eol;
if (mIceUfrag)
sdp << "a=ice-ufrag:" << *mIceUfrag << eol;
if (mIcePwd)
sdp << "a=ice-pwd:" << *mIcePwd << eol;
if (!mIceOptions.empty())
sdp << "a=ice-options:" << utils::implode(mIceOptions, ',') << eol;
if (mFingerprint)
sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
for (const auto &attr : mAttributes)
sdp << "a=" << attr << eol;
auto cand = defaultCandidate();
const string addr = cand && cand->isResolved()
? (string(cand->family() == Candidate::Family::Ipv6 ? "IP6" : "IP4") +
" " + *cand->address())
: "IP4 0.0.0.0";
const uint16_t port =
cand && cand->isResolved() ? *cand->port() : 9; // Port 9 is the discard protocol
// Entries
bool first = true;
for (const auto &entry : mEntries) {
sdp << entry->generateSdp(eol, addr, port);
if (!entry->isRemoved() && std::exchange(first, false)) {
// Candidates
for (const auto &candidate : mCandidates)
sdp << string(candidate) << eol;
if (mEnded)
sdp << "a=end-of-candidates" << eol;
}
}
return sdp.str();
}
string Description::generateApplicationSdp(string_view eol) const {
std::ostringstream sdp;
// Header
sdp << "v=0" << eol;
sdp << "o=" << mUsername << " " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
sdp << "s=-" << eol;
sdp << "t=0 0" << eol;
auto cand = defaultCandidate();
const string addr = cand && cand->isResolved()
? (string(cand->family() == Candidate::Family::Ipv6 ? "IP6" : "IP4") +
" " + *cand->address())
: "IP4 0.0.0.0";
const uint16_t port =
cand && cand->isResolved() ? *cand->port() : 9; // Port 9 is the discard protocol
// Application
auto app = mApplication ? mApplication : std::make_shared<Application>();
sdp << app->generateSdp(eol, addr, port);
// Session-level attributes
sdp << "a=msid-semantic:WMS *" << eol;
sdp << "a=setup:" << mRole << eol;
if (mIceUfrag)
sdp << "a=ice-ufrag:" << *mIceUfrag << eol;
if (mIcePwd)
sdp << "a=ice-pwd:" << *mIcePwd << eol;
if (!mIceOptions.empty())
sdp << "a=ice-options:" << utils::implode(mIceOptions, ',') << eol;
if (mFingerprint)
sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
for (const auto &attr : mAttributes)
sdp << "a=" << attr << eol;
// Candidates
for (const auto &candidate : mCandidates)
sdp << string(candidate) << eol;
if (mEnded)
sdp << "a=end-of-candidates" << eol;
return sdp.str();
}
optional<Candidate> Description::defaultCandidate() const {
// Return the first host candidate with highest priority, favoring IPv4
optional<Candidate> result;
for (const auto &c : mCandidates) {
if (c.type() == Candidate::Type::Host) {
if (!result ||
(result->family() == Candidate::Family::Ipv6 &&
c.family() == Candidate::Family::Ipv4) ||
(result->family() == c.family() && result->priority() < c.priority()))
result.emplace(c);
}
}
return result;
}
shared_ptr<Description::Entry> Description::createEntry(string mline, string mid, Direction dir) {
string type = mline.substr(0, mline.find(' '));
if (type == "application") {
removeApplication();
mApplication = std::make_shared<Application>(mline, std::move(mid));
mEntries.emplace_back(mApplication);
return mApplication;
} else {
auto media = std::make_shared<Media>(std::move(mline), std::move(mid), dir);
mEntries.emplace_back(media);
return media;
}
}
void Description::removeApplication() {
if (!mApplication)
return;
auto it = std::find(mEntries.begin(), mEntries.end(), mApplication);
if (it != mEntries.end())
mEntries.erase(it);
mApplication.reset();
}
bool Description::hasApplication() const { return mApplication && !mApplication->isRemoved(); }
bool Description::hasAudioOrVideo() const {
for (auto entry : mEntries)
if (entry != mApplication && !entry->isRemoved())
return true;
return false;
}
bool Description::hasMid(string_view mid) const {
for (const auto &entry : mEntries)
if (entry->mid() == mid)
return true;
return false;
}
int Description::addMedia(Media media) {
mEntries.emplace_back(std::make_shared<Media>(std::move(media)));
return int(mEntries.size()) - 1;
}
int Description::addMedia(Application application) {
removeApplication();
mApplication = std::make_shared<Application>(std::move(application));
mEntries.emplace_back(mApplication);
return int(mEntries.size()) - 1;
}
int Description::addApplication(string mid) { return addMedia(Application(std::move(mid))); }
const Description::Application *Description::application() const { return mApplication.get(); }
Description::Application *Description::application() { return mApplication.get(); }
int Description::addVideo(string mid, Direction dir) {
return addMedia(Video(std::move(mid), dir));
}
int Description::addAudio(string mid, Direction dir) {
return addMedia(Audio(std::move(mid), dir));
}
void Description::clearMedia() {
mEntries.clear();
mApplication.reset();
}
variant<Description::Media *, Description::Application *> Description::media(unsigned int index) {
if (index >= mEntries.size())
throw std::out_of_range("Media index out of range");
const auto &entry = mEntries[index];
if (entry == mApplication) {
auto result = dynamic_cast<Application *>(entry.get());
if (!result)
throw std::logic_error("Bad type of application in description");
return result;
} else {
auto result = dynamic_cast<Media *>(entry.get());
if (!result)
throw std::logic_error("Bad type of media in description");
return result;
}
}
variant<const Description::Media *, const Description::Application *>
Description::media(unsigned int index) const {
if (index >= mEntries.size())
throw std::out_of_range("Media index out of range");
const auto &entry = mEntries[index];
if (entry == mApplication) {
auto result = dynamic_cast<Application *>(entry.get());
if (!result)
throw std::logic_error("Bad type of application in description");
return result;
} else {
auto result = dynamic_cast<Media *>(entry.get());
if (!result)
throw std::logic_error("Bad type of media in description");
return result;
}
}
unsigned int Description::mediaCount() const { return unsigned(mEntries.size()); }
Description::Entry::Entry(const string &mline, string mid, Direction dir)
: mMid(std::move(mid)), mDirection(dir) {
uint16_t port;
std::istringstream ss(mline);
ss >> mType;
ss >> port;
ss >> mDescription;
// RFC 3264: Existing media streams are removed by creating a new SDP with the port number for
// that stream set to zero.
// RFC 8843: If the offerer assigns a zero port value to a bundled "m=" section, but does not
// include an SDP 'bundle-only' attribute in the "m=" section, it is an indication that the
// offerer wants to disable the "m=" section.
mIsRemoved = (port == 0);
}
string Description::Entry::type() const { return mType; }
string Description::Entry::description() const { return mDescription; }
string Description::Entry::mid() const { return mMid; }
Description::Direction Description::Entry::direction() const { return mDirection; }
void Description::Entry::setDirection(Direction dir) { mDirection = dir; }
bool Description::Entry::isRemoved() const { return mIsRemoved; }
void Description::Entry::markRemoved() { mIsRemoved = true; }
std::vector<string> Description::attributes() const { return mAttributes; }
void Description::addAttribute(string attr) {
if (std::find(mAttributes.begin(), mAttributes.end(), attr) == mAttributes.end())
mAttributes.emplace_back(std::move(attr));
}
void Description::Entry::addRid(string rid) { mRids.emplace_back(rid); }
void Description::removeAttribute(const string &attr) {
mAttributes.erase(
std::remove_if(mAttributes.begin(), mAttributes.end(),
[&](const auto &a) { return a == attr || parse_pair(a).first == attr; }),
mAttributes.end());
}
std::vector<int> Description::Entry::extIds() {
std::vector<int> result;
for (auto it = mExtMaps.begin(); it != mExtMaps.end(); ++it)
result.push_back(it->first);
return result;
}
Description::Entry::ExtMap *Description::Entry::extMap(int id) {
auto it = mExtMaps.find(id);
if (it == mExtMaps.end())
throw std::invalid_argument("extmap not found");
return &it->second;
}
const Description::Entry::ExtMap *Description::Entry::extMap(int id) const {
auto it = mExtMaps.find(id);
if (it == mExtMaps.end())
throw std::invalid_argument("extmap not found");
return &it->second;
}
void Description::Entry::addExtMap(ExtMap map) {
auto id = map.id;
mExtMaps.emplace(id, std::move(map));
}
void Description::Entry::removeExtMap(int id) { mExtMaps.erase(id); }
Description::Entry::operator string() const { return generateSdp("\r\n", "IP4 0.0.0.0", 9); }
string Description::Entry::generateSdp(string_view eol, string_view addr, uint16_t port) const {
std::ostringstream sdp;
// RFC 3264: Existing media streams are removed by creating a new SDP with the port number for
// that stream set to zero. [...] A stream that is offered with a port of zero MUST be marked
// with port zero in the answer.
sdp << "m=" << type() << ' ' << (mIsRemoved ? 0 : port) << ' ' << description() << eol;
sdp << "c=IN " << addr << eol;
sdp << generateSdpLines(eol);
return sdp.str();
}
string Description::Entry::generateSdpLines(string_view eol) const {
std::ostringstream sdp;
sdp << "a=mid:" << mMid << eol;
for (auto it = mExtMaps.begin(); it != mExtMaps.end(); ++it) {
auto &map = it->second;
sdp << "a=extmap:" << map.id;
if (map.direction != Direction::Unknown)
sdp << '/' << map.direction;
sdp << ' ' << map.uri;
if (!map.attributes.empty())
sdp << ' ' << map.attributes;
sdp << eol;
}
if (mDirection != Direction::Unknown)
sdp << "a=" << mDirection << eol;
for (const auto &attr : mAttributes) {
if (mRids.size() != 0 && match_prefix(attr, "ssrc:")) {
continue;
}
sdp << "a=" << attr << eol;
}
for (const auto &rid : mRids) {
sdp << "a=rid:" << rid << " send" << eol;
}
if (mRids.size() != 0) {
sdp << "a=simulcast:send ";
bool first = true;
for (const auto &rid : mRids) {
if (first) {
first = false;
} else {
sdp << ";";
}
sdp << rid;
}
sdp << eol;
}
return sdp.str();
}
void Description::Entry::parseSdpLine(string_view line) {
if (match_prefix(line, "a=")) {
string_view attr = line.substr(2);
auto [key, value] = parse_pair(attr);
if (key == "mid") {
mMid = value;
} else if (key == "extmap") {
auto id = Description::Media::ExtMap::parseId(value);
auto it = mExtMaps.find(id);
if (it == mExtMaps.end())
it = mExtMaps.insert(std::make_pair(id, Description::Media::ExtMap(value))).first;
else
it->second.setDescription(value);
} else if (attr == "sendonly")
mDirection = Direction::SendOnly;
else if (attr == "recvonly")
mDirection = Direction::RecvOnly;
else if (key == "sendrecv")
mDirection = Direction::SendRecv;
else if (key == "inactive")
mDirection = Direction::Inactive;
else if (key == "bundle-only") {
// RFC 8843: When an offerer generates a subsequent offer, in which it wants to disable
// a bundled "m=" section from a BUNDLE group, the offerer [...] MUST NOT assign an SDP
// 'bundle-only' attribute to the "m=" section.
mIsRemoved = false;
} else {
mAttributes.emplace_back(attr);
}
}
}
int Description::Entry::ExtMap::parseId(string_view description) {
size_t p = description.find(' ');
return to_integer<int>(description.substr(0, p));
}
Description::Entry::ExtMap::ExtMap(int id, string uri, Direction direction) {
this->id = id;
this->uri = std::move(uri);
this->direction = direction;
}
Description::Entry::ExtMap::ExtMap(string_view description) { setDescription(description); }
void Description::Entry::ExtMap::setDescription(string_view description) {
const size_t uriStart = description.find(' ');
if (uriStart == string::npos)
throw std::invalid_argument("Invalid description for extmap");
const string_view idAndDirection = description.substr(0, uriStart);
const size_t idSplit = idAndDirection.find('/');
if (idSplit == string::npos) {
this->id = to_integer<int>(idAndDirection);
} else {
this->id = to_integer<int>(idAndDirection.substr(0, idSplit));
const string_view directionStr = idAndDirection.substr(idSplit + 1);
if (directionStr == "sendonly")
this->direction = Direction::SendOnly;
else if (directionStr == "recvonly")
this->direction = Direction::RecvOnly;
else if (directionStr == "sendrecv")
this->direction = Direction::SendRecv;
else if (directionStr == "inactive")
this->direction = Direction::Inactive;
else
throw std::invalid_argument("Invalid direction for extmap");
}
const string_view uriAndAttributes = description.substr(uriStart + 1);
const size_t attributeSplit = uriAndAttributes.find(' ');
if (attributeSplit == string::npos)
this->uri = uriAndAttributes;
else {
this->uri = uriAndAttributes.substr(0, attributeSplit);
this->attributes = uriAndAttributes.substr(attributeSplit + 1);
}
}
void Description::Media::addSSRC(uint32_t ssrc, optional<string> name, optional<string> msid,
optional<string> trackId) {
if (name) {
mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " cname:" + *name);
mCNameMap.emplace(ssrc, *name);
} else {
mAttributes.emplace_back("ssrc:" + std::to_string(ssrc));
}
if (msid) {
mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " msid:" + *msid + " " +
trackId.value_or(*msid));
mAttributes.emplace_back("msid:" + *msid + " " + trackId.value_or(*msid));
}
mSsrcs.emplace_back(ssrc);
}
void Description::Media::removeSSRC(uint32_t ssrc) {
string prefix = "ssrc:" + std::to_string(ssrc);
mAttributes.erase(std::remove_if(mAttributes.begin(), mAttributes.end(),
[&](const auto &a) { return match_prefix(a, prefix); }),
mAttributes.end());
mSsrcs.erase(std::remove(mSsrcs.begin(), mSsrcs.end(), ssrc), mSsrcs.end());
}
void Description::Media::replaceSSRC(uint32_t old, uint32_t ssrc, optional<string> name,
optional<string> msid, optional<string> trackID) {
removeSSRC(old);
addSSRC(ssrc, std::move(name), std::move(msid), std::move(trackID));
}
bool Description::Media::hasSSRC(uint32_t ssrc) const {
return std::find(mSsrcs.begin(), mSsrcs.end(), ssrc) != mSsrcs.end();
}
void Description::Media::clearSSRCs() {
auto it = mAttributes.begin();
while (it != mAttributes.end()) {
if (match_prefix(*it, "ssrc:"))
it = mAttributes.erase(it);
else
++it;
}
mSsrcs.clear();
mCNameMap.clear();
}
std::vector<uint32_t> Description::Media::getSSRCs() const { return mSsrcs; }
optional<string> Description::Media::getCNameForSsrc(uint32_t ssrc) const {
auto it = mCNameMap.find(ssrc);
if (it != mCNameMap.end()) {
return it->second;
}
return nullopt;
}
Description::Application::Application(string mid)
: Entry("application 9 UDP/DTLS/SCTP", std::move(mid), Direction::SendRecv) {}
Description::Application::Application(const string &mline, string mid)
: Entry(mline, std::move(mid), Direction::SendRecv) {}
string Description::Application::description() const {
return Entry::description() + " webrtc-datachannel";
}
Description::Application Description::Application::reciprocate() const {
Application reciprocated(*this);
reciprocated.mMaxMessageSize.reset();
return reciprocated;
}
void Description::Application::setSctpPort(uint16_t port) { mSctpPort = port; }
void Description::Application::hintSctpPort(uint16_t port) { mSctpPort = mSctpPort.value_or(port); }
void Description::Application::setMaxMessageSize(size_t size) { mMaxMessageSize = size; }
optional<uint16_t> Description::Application::sctpPort() const { return mSctpPort; }
optional<size_t> Description::Application::maxMessageSize() const { return mMaxMessageSize; }
string Description::Application::generateSdpLines(string_view eol) const {
std::ostringstream sdp;
sdp << Entry::generateSdpLines(eol);
if (mSctpPort)
sdp << "a=sctp-port:" << *mSctpPort << eol;
if (mMaxMessageSize)
sdp << "a=max-message-size:" << *mMaxMessageSize << eol;
return sdp.str();
}
void Description::Application::parseSdpLine(string_view line) {
if (match_prefix(line, "a=")) {
string_view attr = line.substr(2);
auto [key, value] = parse_pair(attr);
if (key == "sctp-port") {
mSctpPort = to_integer<uint16_t>(value);
} else if (key == "max-message-size") {
mMaxMessageSize = to_integer<size_t>(value);
} else {
Entry::parseSdpLine(line);
}
} else {
Entry::parseSdpLine(line);
}
}
Description::Media::Media(const string &sdp) : Entry(sdp, "", Direction::Unknown) {
std::istringstream ss(sdp);
while (ss) {
string line;
std::getline(ss, line);
trim_end(line);
if (line.empty())
continue;
parseSdpLine(line);
}
if (mid().empty())
throw std::invalid_argument("Missing mid in media description");
}
Description::Media::Media(const string &mline, string mid, Direction dir)
: Entry(mline, std::move(mid), dir) {}
string Description::Media::description() const {
std::ostringstream desc;
desc << Entry::description();
for (auto it = mRtpMaps.begin(); it != mRtpMaps.end(); ++it)
desc << ' ' << it->first;
return desc.str();
}
Description::Media Description::Media::reciprocate() const {
Media reciprocated(*this);
// Invert direction
switch (reciprocated.direction()) {
case Direction::RecvOnly:
reciprocated.setDirection(Direction::SendOnly);
break;
case Direction::SendOnly:
reciprocated.setDirection(Direction::RecvOnly);
break;
default:
// We are good
break;
}
// Invert directions of extmap
auto &extMaps = reciprocated.mExtMaps;
for (auto it = extMaps.begin(); it != extMaps.end(); ++it) {
auto &map = it->second;
switch (map.direction) {
case Direction::RecvOnly:
map.direction = Direction::SendOnly;
break;
case Direction::SendOnly:
map.direction = Direction::RecvOnly;
break;
default:
// We are good
break;
}
}
// Clear sent SSRCs
reciprocated.clearSSRCs();
// Remove rtcp-rsize attribute as Reduced-Size RTCP is not supported (see RFC 5506)
reciprocated.removeAttribute("rtcp-rsize");
return reciprocated;
}
int Description::Media::bitrate() const { return mBas; }
void Description::Media::setBitrate(int bitrate) { mBas = bitrate; }
bool Description::Media::hasPayloadType(int payloadType) const {
return mRtpMaps.find(payloadType) != mRtpMaps.end();
}
std::vector<int> Description::Media::payloadTypes() const {
std::vector<int> result;
result.reserve(mRtpMaps.size());
for (auto it = mRtpMaps.begin(); it != mRtpMaps.end(); ++it)
result.push_back(it->first);
return result;
}
Description::Media::RtpMap *Description::Media::rtpMap(int payloadType) {
auto it = mRtpMaps.find(payloadType);
if (it == mRtpMaps.end())
throw std::invalid_argument("rtpmap not found");
return &it->second;
}
const Description::Media::RtpMap *Description::Media::rtpMap(int payloadType) const {
auto it = mRtpMaps.find(payloadType);
if (it == mRtpMaps.end())
throw std::invalid_argument("rtpmap not found");
return &it->second;
}
void Description::Media::addRtpMap(RtpMap map) {
auto payloadType = map.payloadType;
mRtpMaps.emplace(payloadType, std::move(map));
}
void Description::Media::removeRtpMap(int payloadType) {
// Remove the actual format
mRtpMaps.erase(payloadType);
// Remove any other rtpmaps that depend on the format we just removed
auto it = mRtpMaps.begin();
while (it != mRtpMaps.end()) {
const auto &fmtps = it->second.fmtps;
if (std::find(fmtps.begin(), fmtps.end(), "apt=" + std::to_string(payloadType)) !=
fmtps.end())
it = mRtpMaps.erase(it);
else
++it;
}
}
void Description::Media::removeFormat(const string &format) {
std::vector<int> payloadTypes;
for (const auto &it : mRtpMaps) {
if (it.second.format == format)
payloadTypes.push_back(it.first);
}
for (int pt : payloadTypes)
removeRtpMap(pt);