description.cpp 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421
  1. /**
  2. * Copyright (c) 2019-2020 Paul-Louis Ageneau
  3. * Copyright (c) 2020 Staz Modrzynski
  4. *
  5. * This Source Code Form is subject to the terms of the Mozilla Public
  6. * License, v. 2.0. If a copy of the MPL was not distributed with this
  7. * file, You can obtain one at https://mozilla.org/MPL/2.0/.
  8. */
  9. #include "description.hpp"
  10. #include "impl/internals.hpp"
  11. #include "impl/utils.hpp"
  12. #include <algorithm>
  13. #include <array>
  14. #include <cctype>
  15. #include <chrono>
  16. #include <iostream>
  17. #include <random>
  18. #include <sstream>
  19. #include <unordered_map>
  20. using std::chrono::system_clock;
  21. namespace {
  22. using std::string;
  23. using std::string_view;
  24. inline bool match_prefix(string_view str, string_view prefix) {
  25. return str.size() >= prefix.size() &&
  26. std::mismatch(prefix.begin(), prefix.end(), str.begin()).first == prefix.end();
  27. }
  28. inline void trim_end(string &str) {
  29. str.erase(
  30. std::find_if(str.rbegin(), str.rend(), [](char c) { return !std::isspace(c); }).base(),
  31. str.end());
  32. }
  33. inline string get_first_line(const string &str) {
  34. string line;
  35. std::istringstream ss(str);
  36. std::getline(ss, line);
  37. return line;
  38. }
  39. inline std::pair<string_view, string_view> parse_pair(string_view attr) {
  40. string_view key, value;
  41. if (size_t separator = attr.find(':'); separator != string::npos) {
  42. key = attr.substr(0, separator);
  43. value = attr.substr(separator + 1);
  44. } else {
  45. key = attr;
  46. }
  47. return std::make_pair(std::move(key), std::move(value));
  48. }
  49. template <typename T> T to_integer(string_view s) {
  50. const string str(s);
  51. try {
  52. return std::is_signed<T>::value ? T(std::stol(str)) : T(std::stoul(str));
  53. } catch (...) {
  54. throw std::invalid_argument("Invalid integer \"" + str + "\" in description");
  55. }
  56. }
  57. } // namespace
  58. namespace rtc {
  59. namespace utils = impl::utils;
  60. Description::Description(const string &sdp, Type type, Role role)
  61. : mType(Type::Unspec), mRole(role) {
  62. hintType(type);
  63. int index = -1;
  64. shared_ptr<Entry> current;
  65. std::istringstream ss(sdp);
  66. while (ss) {
  67. string line;
  68. std::getline(ss, line);
  69. trim_end(line);
  70. if (line.empty())
  71. continue;
  72. if (match_prefix(line, "m=")) { // Media description line (aka m-line)
  73. current = createEntry(line.substr(2), std::to_string(++index), Direction::Unknown);
  74. } else if (match_prefix(line, "o=")) { // Origin line
  75. std::istringstream origin(line.substr(2));
  76. origin >> mUsername >> mSessionId;
  77. } else if (match_prefix(line, "a=")) { // Attribute line
  78. string attr = line.substr(2);
  79. auto [key, value] = parse_pair(attr);
  80. if (key == "setup") {
  81. if (value == "active")
  82. mRole = Role::Active;
  83. else if (value == "passive")
  84. mRole = Role::Passive;
  85. else
  86. mRole = Role::ActPass;
  87. } else if (key == "fingerprint") {
  88. // RFC 8122: The fingerprint attribute may be either a session-level or a
  89. // media-level SDP attribute. If it is a session-level attribute, it applies to all
  90. // TLS sessions for which no media-level fingerprint attribute is defined.
  91. if (!mFingerprint || index == 0) { // first media overrides session-level
  92. auto fingerprintExploded = utils::explode(string(value), ' ');
  93. if (fingerprintExploded.size() != 2) {
  94. PLOG_WARNING << "Unknown SDP fingerprint format: " << value;
  95. continue;
  96. }
  97. auto first = fingerprintExploded.at(0);
  98. std::transform(first.begin(), first.end(), first.begin(),
  99. [](char c) { return char(std::tolower(c)); });
  100. std::optional<CertificateFingerprint::Algorithm> fingerprintAlgorithm;
  101. for (auto a : std::array<CertificateFingerprint::Algorithm, 5>{
  102. CertificateFingerprint::Algorithm::Sha1,
  103. CertificateFingerprint::Algorithm::Sha224,
  104. CertificateFingerprint::Algorithm::Sha256,
  105. CertificateFingerprint::Algorithm::Sha384,
  106. CertificateFingerprint::Algorithm::Sha512}) {
  107. if (first == CertificateFingerprint::AlgorithmIdentifier(a)) {
  108. fingerprintAlgorithm = a;
  109. break;
  110. }
  111. }
  112. if (fingerprintAlgorithm.has_value()) {
  113. setFingerprint(CertificateFingerprint{
  114. fingerprintAlgorithm.value(), std::move(fingerprintExploded.at(1))});
  115. } else {
  116. PLOG_WARNING << "Unknown certificate fingerprint algorithm: " << first;
  117. }
  118. }
  119. } else if (key == "ice-ufrag") {
  120. // RFC 8839: The "ice-pwd" and "ice-ufrag" attributes can appear at either the
  121. // session-level or media-level. When present in both, the value in the media-level
  122. // takes precedence.
  123. if (!mIceUfrag || index == 0) // media-level for first media overrides session-level
  124. mIceUfrag = value;
  125. } else if (key == "ice-pwd") {
  126. // RFC 8839: The "ice-pwd" and "ice-ufrag" attributes can appear at either the
  127. // session-level or media-level. When present in both, the value in the media-level
  128. // takes precedence.
  129. if (!mIcePwd || index == 0) // media-level for first media overrides session-level
  130. mIcePwd = value;
  131. } else if (key == "ice-options") {
  132. // RFC 8839: The "ice-options" attribute is a session-level and media-level
  133. // attribute.
  134. if (mIceOptions.empty())
  135. mIceOptions = utils::explode(string(value), ',');
  136. } else if (key == "candidate") {
  137. addCandidate(Candidate(attr, bundleMid()));
  138. } else if (key == "end-of-candidates") {
  139. mEnded = true;
  140. } else if (current) {
  141. current->parseSdpLine(std::move(line));
  142. } else {
  143. mAttributes.emplace_back(attr);
  144. }
  145. } else if (current) {
  146. current->parseSdpLine(std::move(line));
  147. }
  148. }
  149. if (mUsername.empty())
  150. mUsername = "rtc";
  151. if (mSessionId.empty()) {
  152. auto uniform = std::bind(std::uniform_int_distribution<uint32_t>(), utils::random_engine());
  153. mSessionId = std::to_string(uniform());
  154. }
  155. }
  156. Description::Description(const string &sdp, string typeString)
  157. : Description(sdp, !typeString.empty() ? stringToType(typeString) : Type::Unspec,
  158. Role::ActPass) {}
  159. Description::Type Description::type() const { return mType; }
  160. string Description::typeString() const { return typeToString(mType); }
  161. Description::Role Description::role() const { return mRole; }
  162. string Description::bundleMid() const {
  163. // Get the mid of the first non-removed media
  164. for (const auto &entry : mEntries)
  165. if (!entry->isRemoved())
  166. return entry->mid();
  167. return "0";
  168. }
  169. optional<string> Description::iceUfrag() const { return mIceUfrag; }
  170. std::vector<string> Description::iceOptions() const { return mIceOptions; }
  171. optional<string> Description::icePwd() const { return mIcePwd; }
  172. optional<CertificateFingerprint> Description::fingerprint() const { return mFingerprint; }
  173. bool Description::ended() const { return mEnded; }
  174. void Description::hintType(Type type) {
  175. if (mType == Type::Unspec)
  176. mType = type;
  177. }
  178. void Description::addIceOption(string option) {
  179. if (std::find(mIceOptions.begin(), mIceOptions.end(), option) == mIceOptions.end())
  180. mIceOptions.emplace_back(std::move(option));
  181. }
  182. void Description::removeIceOption(const string &option) {
  183. mIceOptions.erase(std::remove(mIceOptions.begin(), mIceOptions.end(), option),
  184. mIceOptions.end());
  185. }
  186. void Description::setIceAttribute(string ufrag, string pwd) {
  187. mIceUfrag = std::move(ufrag);
  188. mIcePwd = std::move(pwd);
  189. }
  190. void Description::setFingerprint(CertificateFingerprint f) {
  191. if (!f.isValid())
  192. throw std::invalid_argument("Invalid " +
  193. CertificateFingerprint::AlgorithmIdentifier(f.algorithm) +
  194. " fingerprint \"" + f.value + "\"");
  195. std::transform(f.value.begin(), f.value.end(), f.value.begin(),
  196. [](char c) { return char(std::toupper(c)); });
  197. mFingerprint = std::move(f);
  198. }
  199. std::vector<string> Description::Entry::attributes() const { return mAttributes; }
  200. void Description::Entry::addAttribute(string attr) {
  201. if (std::find(mAttributes.begin(), mAttributes.end(), attr) == mAttributes.end())
  202. mAttributes.emplace_back(std::move(attr));
  203. }
  204. void Description::Entry::removeAttribute(const string &attr) {
  205. mAttributes.erase(
  206. std::remove_if(mAttributes.begin(), mAttributes.end(),
  207. [&](const auto &a) { return a == attr || parse_pair(a).first == attr; }),
  208. mAttributes.end());
  209. }
  210. std::vector<Candidate> Description::candidates() const { return mCandidates; }
  211. std::vector<Candidate> Description::extractCandidates() {
  212. std::vector<Candidate> result;
  213. std::swap(mCandidates, result);
  214. mEnded = false;
  215. return result;
  216. }
  217. bool Description::hasCandidate(const Candidate &candidate) const {
  218. return std::find(mCandidates.begin(), mCandidates.end(), candidate) != mCandidates.end();
  219. }
  220. void Description::addCandidate(Candidate candidate) {
  221. candidate.hintMid(bundleMid());
  222. if (!hasCandidate(candidate))
  223. mCandidates.emplace_back(std::move(candidate));
  224. }
  225. void Description::addCandidates(std::vector<Candidate> candidates) {
  226. for (Candidate candidate : candidates)
  227. addCandidate(std::move(candidate));
  228. }
  229. void Description::endCandidates() { mEnded = true; }
  230. Description::operator string() const { return generateSdp("\r\n"); }
  231. string Description::generateSdp(string_view eol) const {
  232. std::ostringstream sdp;
  233. // Header
  234. sdp << "v=0" << eol;
  235. sdp << "o=" << mUsername << " " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
  236. sdp << "s=-" << eol;
  237. sdp << "t=0 0" << eol;
  238. // BUNDLE (RFC 8843 Negotiating Media Multiplexing Using the Session Description Protocol)
  239. // https://www.rfc-editor.org/rfc/rfc8843.html
  240. std::ostringstream bundleGroup;
  241. for (const auto &entry : mEntries)
  242. if (!entry->isRemoved())
  243. bundleGroup << ' ' << entry->mid();
  244. if (!bundleGroup.str().empty())
  245. sdp << "a=group:BUNDLE" << bundleGroup.str() << eol;
  246. // Lip-sync
  247. std::ostringstream lsGroup;
  248. for (const auto &entry : mEntries)
  249. if (!entry->isRemoved() && entry != mApplication)
  250. lsGroup << ' ' << entry->mid();
  251. if (!lsGroup.str().empty())
  252. sdp << "a=group:LS" << lsGroup.str() << eol;
  253. // Session-level attributes
  254. sdp << "a=msid-semantic:WMS *" << eol;
  255. if (!mIceOptions.empty())
  256. sdp << "a=ice-options:" << utils::implode(mIceOptions, ',') << eol;
  257. if (mFingerprint)
  258. sdp << "a=fingerprint:"
  259. << CertificateFingerprint::AlgorithmIdentifier(mFingerprint->algorithm) << " "
  260. << mFingerprint->value << eol;
  261. for (const auto &attr : mAttributes)
  262. sdp << "a=" << attr << eol;
  263. auto cand = defaultCandidate();
  264. const string addr = cand && cand->isResolved()
  265. ? (string(cand->family() == Candidate::Family::Ipv6 ? "IP6" : "IP4") +
  266. " " + *cand->address())
  267. : "IP4 0.0.0.0";
  268. const uint16_t port =
  269. cand && cand->isResolved() ? *cand->port() : 9; // Port 9 is the discard protocol
  270. // Entries
  271. bool first = true;
  272. for (const auto &entry : mEntries) {
  273. sdp << entry->generateSdp(eol, addr, port);
  274. // RFC 8829: Attributes that SDP permits to be at either the session level or the media level
  275. // SHOULD generally be at the media level even if they are identical.
  276. sdp << "a=setup:" << mRole << eol;
  277. if (mIceUfrag)
  278. sdp << "a=ice-ufrag:" << *mIceUfrag << eol;
  279. if (mIcePwd)
  280. sdp << "a=ice-pwd:" << *mIcePwd << eol;
  281. if (!entry->isRemoved() && std::exchange(first, false)) {
  282. // Candidates
  283. for (const auto &candidate : mCandidates)
  284. sdp << string(candidate) << eol;
  285. if (mEnded)
  286. sdp << "a=end-of-candidates" << eol;
  287. }
  288. }
  289. return sdp.str();
  290. }
  291. string Description::generateApplicationSdp(string_view eol) const {
  292. std::ostringstream sdp;
  293. // Header
  294. sdp << "v=0" << eol;
  295. sdp << "o=" << mUsername << " " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
  296. sdp << "s=-" << eol;
  297. sdp << "t=0 0" << eol;
  298. auto cand = defaultCandidate();
  299. const string addr = cand && cand->isResolved()
  300. ? (string(cand->family() == Candidate::Family::Ipv6 ? "IP6" : "IP4") +
  301. " " + *cand->address())
  302. : "IP4 0.0.0.0";
  303. const uint16_t port =
  304. cand && cand->isResolved() ? *cand->port() : 9; // Port 9 is the discard protocol
  305. // Session-level attributes
  306. sdp << "a=msid-semantic:WMS *" << eol;
  307. if (!mIceOptions.empty())
  308. sdp << "a=ice-options:" << utils::implode(mIceOptions, ',') << eol;
  309. for (const auto &attr : mAttributes)
  310. sdp << "a=" << attr << eol;
  311. // Application
  312. auto app = mApplication ? mApplication : std::make_shared<Application>();
  313. sdp << app->generateSdp(eol, addr, port);
  314. // Media-level attributes
  315. sdp << "a=setup:" << mRole << eol;
  316. if (mIceUfrag)
  317. sdp << "a=ice-ufrag:" << *mIceUfrag << eol;
  318. if (mIcePwd)
  319. sdp << "a=ice-pwd:" << *mIcePwd << eol;
  320. if (mFingerprint)
  321. sdp << "a=fingerprint:"
  322. << CertificateFingerprint::AlgorithmIdentifier(mFingerprint->algorithm) << " "
  323. << mFingerprint->value << eol;
  324. // Candidates
  325. for (const auto &candidate : mCandidates)
  326. sdp << string(candidate) << eol;
  327. if (mEnded)
  328. sdp << "a=end-of-candidates" << eol;
  329. return sdp.str();
  330. }
  331. optional<Candidate> Description::defaultCandidate() const {
  332. // Return the first host candidate with highest priority, favoring IPv4
  333. optional<Candidate> result;
  334. for (const auto &c : mCandidates) {
  335. if (c.type() == Candidate::Type::Host) {
  336. if (!result ||
  337. (result->family() == Candidate::Family::Ipv6 &&
  338. c.family() == Candidate::Family::Ipv4) ||
  339. (result->family() == c.family() && result->priority() < c.priority()))
  340. result.emplace(c);
  341. }
  342. }
  343. return result;
  344. }
  345. shared_ptr<Description::Entry> Description::createEntry(string mline, string mid, Direction dir) {
  346. string type = mline.substr(0, mline.find(' '));
  347. if (type == "application") {
  348. removeApplication();
  349. mApplication = std::make_shared<Application>(mline, std::move(mid));
  350. mEntries.emplace_back(mApplication);
  351. return mApplication;
  352. } else {
  353. auto media = std::make_shared<Media>(std::move(mline), std::move(mid), dir);
  354. mEntries.emplace_back(media);
  355. return media;
  356. }
  357. }
  358. void Description::removeApplication() {
  359. if (!mApplication)
  360. return;
  361. auto it = std::find(mEntries.begin(), mEntries.end(), mApplication);
  362. if (it != mEntries.end())
  363. mEntries.erase(it);
  364. mApplication.reset();
  365. }
  366. bool Description::hasApplication() const { return mApplication && !mApplication->isRemoved(); }
  367. bool Description::hasAudioOrVideo() const {
  368. for (auto entry : mEntries)
  369. if (entry != mApplication && !entry->isRemoved())
  370. return true;
  371. return false;
  372. }
  373. bool Description::hasMid(string_view mid) const {
  374. for (const auto &entry : mEntries)
  375. if (entry->mid() == mid)
  376. return true;
  377. return false;
  378. }
  379. int Description::addMedia(Media media) {
  380. mEntries.emplace_back(std::make_shared<Media>(std::move(media)));
  381. return int(mEntries.size()) - 1;
  382. }
  383. int Description::addMedia(Application application) {
  384. removeApplication();
  385. mApplication = std::make_shared<Application>(std::move(application));
  386. mEntries.emplace_back(mApplication);
  387. return int(mEntries.size()) - 1;
  388. }
  389. int Description::addApplication(string mid) { return addMedia(Application(std::move(mid))); }
  390. const Description::Application *Description::application() const { return mApplication.get(); }
  391. Description::Application *Description::application() { return mApplication.get(); }
  392. int Description::addVideo(string mid, Direction dir) {
  393. return addMedia(Video(std::move(mid), dir));
  394. }
  395. int Description::addAudio(string mid, Direction dir) {
  396. return addMedia(Audio(std::move(mid), dir));
  397. }
  398. void Description::clearMedia() {
  399. mEntries.clear();
  400. mApplication.reset();
  401. }
  402. variant<Description::Media *, Description::Application *> Description::media(int index) {
  403. if (index < 0 || index >= int(mEntries.size()))
  404. throw std::out_of_range("Media index out of range");
  405. const auto &entry = mEntries[index];
  406. if (entry == mApplication) {
  407. auto result = dynamic_cast<Application *>(entry.get());
  408. if (!result)
  409. throw std::logic_error("Bad type of application in description");
  410. return result;
  411. } else {
  412. auto result = dynamic_cast<Media *>(entry.get());
  413. if (!result)
  414. throw std::logic_error("Bad type of media in description");
  415. return result;
  416. }
  417. }
  418. variant<const Description::Media *, const Description::Application *> Description::media(int index) const {
  419. if (index < 0 || index >= int(mEntries.size()))
  420. throw std::out_of_range("Media index out of range");
  421. const auto &entry = mEntries[index];
  422. if (entry == mApplication) {
  423. auto result = dynamic_cast<Application *>(entry.get());
  424. if (!result)
  425. throw std::logic_error("Bad type of application in description");
  426. return result;
  427. } else {
  428. auto result = dynamic_cast<Media *>(entry.get());
  429. if (!result)
  430. throw std::logic_error("Bad type of media in description");
  431. return result;
  432. }
  433. }
  434. int Description::mediaCount() const { return int(mEntries.size()); }
  435. Description::Entry::Entry(const string &mline, string mid, Direction dir)
  436. : mMid(std::move(mid)), mDirection(dir) {
  437. uint16_t port = 0;
  438. std::istringstream ss(match_prefix(mline, "m=") ? mline.substr(2) : mline);
  439. ss >> mType;
  440. ss >> port;
  441. ss >> mProtocol;
  442. ss >> std::ws;
  443. std::getline(ss, mDescription);
  444. if (mType.empty() || mProtocol.empty())
  445. throw std::invalid_argument("Invalid media description line");
  446. // RFC 3264: Existing media streams are removed by creating a new SDP with the port number for
  447. // that stream set to zero.
  448. // RFC 8843: If the offerer assigns a zero port value to a bundled "m=" section, but does not
  449. // include an SDP 'bundle-only' attribute in the "m=" section, it is an indication that the
  450. // offerer wants to disable the "m=" section.
  451. mIsRemoved = (port == 0);
  452. }
  453. string Description::Entry::type() const { return mType; }
  454. string Description::Entry::protocol() const { return mProtocol; }
  455. string Description::Entry::description() const { return mDescription; }
  456. string Description::Entry::mid() const { return mMid; }
  457. Description::Direction Description::Entry::direction() const { return mDirection; }
  458. void Description::Entry::setDirection(Direction dir) { mDirection = dir; }
  459. bool Description::Entry::isRemoved() const { return mIsRemoved; }
  460. void Description::Entry::markRemoved() { mIsRemoved = true; }
  461. std::vector<string> Description::attributes() const { return mAttributes; }
  462. void Description::addAttribute(string attr) {
  463. if (std::find(mAttributes.begin(), mAttributes.end(), attr) == mAttributes.end())
  464. mAttributes.emplace_back(std::move(attr));
  465. }
  466. void Description::Entry::addRid(string rid) { mRids.emplace_back(rid); }
  467. void Description::removeAttribute(const string &attr) {
  468. mAttributes.erase(
  469. std::remove_if(mAttributes.begin(), mAttributes.end(),
  470. [&](const auto &a) { return a == attr || parse_pair(a).first == attr; }),
  471. mAttributes.end());
  472. }
  473. std::vector<int> Description::Entry::extIds() {
  474. std::vector<int> result;
  475. for (auto it = mExtMaps.begin(); it != mExtMaps.end(); ++it)
  476. result.push_back(it->first);
  477. return result;
  478. }
  479. Description::Entry::ExtMap *Description::Entry::extMap(int id) {
  480. auto it = mExtMaps.find(id);
  481. if (it == mExtMaps.end())
  482. throw std::invalid_argument("extmap not found");
  483. return &it->second;
  484. }
  485. const Description::Entry::ExtMap *Description::Entry::extMap(int id) const {
  486. auto it = mExtMaps.find(id);
  487. if (it == mExtMaps.end())
  488. throw std::invalid_argument("extmap not found");
  489. return &it->second;
  490. }
  491. void Description::Entry::addExtMap(ExtMap map) {
  492. auto id = map.id;
  493. mExtMaps.emplace(id, std::move(map));
  494. }
  495. void Description::Entry::removeExtMap(int id) { mExtMaps.erase(id); }
  496. Description::Entry::operator string() const { return generateSdp("\r\n", "IP4 0.0.0.0", 9); }
  497. string Description::Entry::generateSdp(string_view eol, string_view addr, uint16_t port) const {
  498. std::ostringstream sdp;
  499. // RFC 3264: Existing media streams are removed by creating a new SDP with the port number for
  500. // that stream set to zero. [...] A stream that is offered with a port of zero MUST be marked
  501. // with port zero in the answer.
  502. sdp << "m=" << type() << ' ' << (mIsRemoved ? 0 : port) << ' ' << protocol() << ' '
  503. << description() << eol;
  504. sdp << "c=IN " << addr << eol;
  505. sdp << generateSdpLines(eol);
  506. return sdp.str();
  507. }
  508. string Description::Entry::generateSdpLines(string_view eol) const {
  509. std::ostringstream sdp;
  510. sdp << "a=mid:" << mMid << eol;
  511. for (auto it = mExtMaps.begin(); it != mExtMaps.end(); ++it) {
  512. auto &map = it->second;
  513. sdp << "a=extmap:" << map.id;
  514. if (map.direction != Direction::Unknown)
  515. sdp << '/' << map.direction;
  516. sdp << ' ' << map.uri;
  517. if (!map.attributes.empty())
  518. sdp << ' ' << map.attributes;
  519. sdp << eol;
  520. }
  521. if (mDirection != Direction::Unknown)
  522. sdp << "a=" << mDirection << eol;
  523. for (const auto &attr : mAttributes) {
  524. if (mRids.size() != 0 && match_prefix(attr, "ssrc:")) {
  525. continue;
  526. }
  527. sdp << "a=" << attr << eol;
  528. }
  529. for (const auto &rid : mRids) {
  530. sdp << "a=rid:" << rid << " send" << eol;
  531. }
  532. if (mRids.size() != 0) {
  533. sdp << "a=simulcast:send ";
  534. bool first = true;
  535. for (const auto &rid : mRids) {
  536. if (first) {
  537. first = false;
  538. } else {
  539. sdp << ";";
  540. }
  541. sdp << rid;
  542. }
  543. sdp << eol;
  544. }
  545. return sdp.str();
  546. }
  547. void Description::Entry::parseSdpLine(string_view line) {
  548. if (match_prefix(line, "a=")) {
  549. string_view attr = line.substr(2);
  550. auto [key, value] = parse_pair(attr);
  551. if (key == "mid") {
  552. mMid = value;
  553. } else if (key == "extmap") {
  554. auto id = Description::Media::ExtMap::parseId(value);
  555. auto it = mExtMaps.find(id);
  556. if (it == mExtMaps.end())
  557. it = mExtMaps.insert(std::make_pair(id, Description::Media::ExtMap(value))).first;
  558. else
  559. it->second.setDescription(value);
  560. } else if (attr == "sendonly")
  561. mDirection = Direction::SendOnly;
  562. else if (attr == "recvonly")
  563. mDirection = Direction::RecvOnly;
  564. else if (key == "sendrecv")
  565. mDirection = Direction::SendRecv;
  566. else if (key == "inactive")
  567. mDirection = Direction::Inactive;
  568. else if (key == "bundle-only") {
  569. // RFC 8843: When an offerer generates a subsequent offer, in which it wants to disable
  570. // a bundled "m=" section from a BUNDLE group, the offerer [...] MUST NOT assign an SDP
  571. // 'bundle-only' attribute to the "m=" section.
  572. mIsRemoved = false;
  573. } else {
  574. mAttributes.emplace_back(attr);
  575. }
  576. }
  577. }
  578. int Description::Entry::ExtMap::parseId(string_view description) {
  579. size_t p = description.find(' ');
  580. return to_integer<int>(description.substr(0, p));
  581. }
  582. Description::Entry::ExtMap::ExtMap(int id, string uri, Direction direction) {
  583. this->id = id;
  584. this->uri = std::move(uri);
  585. this->direction = direction;
  586. }
  587. Description::Entry::ExtMap::ExtMap(string_view description) { setDescription(description); }
  588. void Description::Entry::ExtMap::setDescription(string_view description) {
  589. const size_t uriStart = description.find(' ');
  590. if (uriStart == string::npos)
  591. throw std::invalid_argument("Invalid description for extmap");
  592. const string_view idAndDirection = description.substr(0, uriStart);
  593. const size_t idSplit = idAndDirection.find('/');
  594. if (idSplit == string::npos) {
  595. this->id = to_integer<int>(idAndDirection);
  596. } else {
  597. this->id = to_integer<int>(idAndDirection.substr(0, idSplit));
  598. const string_view directionStr = idAndDirection.substr(idSplit + 1);
  599. if (directionStr == "sendonly")
  600. this->direction = Direction::SendOnly;
  601. else if (directionStr == "recvonly")
  602. this->direction = Direction::RecvOnly;
  603. else if (directionStr == "sendrecv")
  604. this->direction = Direction::SendRecv;
  605. else if (directionStr == "inactive")
  606. this->direction = Direction::Inactive;
  607. else
  608. throw std::invalid_argument("Invalid direction for extmap");
  609. }
  610. const string_view uriAndAttributes = description.substr(uriStart + 1);
  611. const size_t attributeSplit = uriAndAttributes.find(' ');
  612. if (attributeSplit == string::npos)
  613. this->uri = uriAndAttributes;
  614. else {
  615. this->uri = uriAndAttributes.substr(0, attributeSplit);
  616. this->attributes = uriAndAttributes.substr(attributeSplit + 1);
  617. }
  618. }
  619. void Description::Media::addSSRC(uint32_t ssrc, optional<string> name, optional<string> msid,
  620. optional<string> trackId) {
  621. if (name) {
  622. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " cname:" + *name);
  623. mCNameMap.emplace(ssrc, *name);
  624. } else {
  625. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc));
  626. }
  627. if (msid) {
  628. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " msid:" + *msid + " " +
  629. trackId.value_or(*msid));
  630. mAttributes.emplace_back("msid:" + *msid + " " + trackId.value_or(*msid));
  631. }
  632. mSsrcs.emplace_back(ssrc);
  633. }
  634. void Description::Media::removeSSRC(uint32_t ssrc) {
  635. string prefix = "ssrc:" + std::to_string(ssrc);
  636. mAttributes.erase(std::remove_if(mAttributes.begin(), mAttributes.end(),
  637. [&](const auto &a) { return match_prefix(a, prefix); }),
  638. mAttributes.end());
  639. mSsrcs.erase(std::remove(mSsrcs.begin(), mSsrcs.end(), ssrc), mSsrcs.end());
  640. }
  641. void Description::Media::replaceSSRC(uint32_t old, uint32_t ssrc, optional<string> name,
  642. optional<string> msid, optional<string> trackID) {
  643. removeSSRC(old);
  644. addSSRC(ssrc, std::move(name), std::move(msid), std::move(trackID));
  645. }
  646. bool Description::Media::hasSSRC(uint32_t ssrc) const {
  647. return std::find(mSsrcs.begin(), mSsrcs.end(), ssrc) != mSsrcs.end();
  648. }
  649. void Description::Media::clearSSRCs() {
  650. auto it = mAttributes.begin();
  651. while (it != mAttributes.end()) {
  652. if (match_prefix(*it, "ssrc:"))
  653. it = mAttributes.erase(it);
  654. else
  655. ++it;
  656. }
  657. mSsrcs.clear();
  658. mCNameMap.clear();
  659. }
  660. std::vector<uint32_t> Description::Media::getSSRCs() const { return mSsrcs; }
  661. optional<string> Description::Media::getCNameForSsrc(uint32_t ssrc) const {
  662. auto it = mCNameMap.find(ssrc);
  663. if (it != mCNameMap.end()) {
  664. return it->second;
  665. }
  666. return nullopt;
  667. }
  668. Description::Application::Application(string mid)
  669. : Entry("application 9 UDP/DTLS/SCTP webrtc-datachannel", std::move(mid), Direction::SendRecv) {
  670. }
  671. Description::Application::Application(const string &mline, string mid)
  672. : Entry(mline, std::move(mid), Direction::SendRecv) {}
  673. Description::Application Description::Application::reciprocate() const {
  674. Application reciprocated(*this);
  675. reciprocated.mMaxMessageSize.reset();
  676. return reciprocated;
  677. }
  678. void Description::Application::setSctpPort(uint16_t port) { mSctpPort = port; }
  679. void Description::Application::hintSctpPort(uint16_t port) { mSctpPort = mSctpPort.value_or(port); }
  680. void Description::Application::setMaxMessageSize(size_t size) { mMaxMessageSize = size; }
  681. optional<uint16_t> Description::Application::sctpPort() const { return mSctpPort; }
  682. optional<size_t> Description::Application::maxMessageSize() const { return mMaxMessageSize; }
  683. string Description::Application::generateSdpLines(string_view eol) const {
  684. std::ostringstream sdp;
  685. sdp << Entry::generateSdpLines(eol);
  686. if (mSctpPort)
  687. sdp << "a=sctp-port:" << *mSctpPort << eol;
  688. if (mMaxMessageSize)
  689. sdp << "a=max-message-size:" << *mMaxMessageSize << eol;
  690. return sdp.str();
  691. }
  692. void Description::Application::parseSdpLine(string_view line) {
  693. if (match_prefix(line, "a=")) {
  694. string_view attr = line.substr(2);
  695. auto [key, value] = parse_pair(attr);
  696. if (key == "sctp-port") {
  697. mSctpPort = to_integer<uint16_t>(value);
  698. } else if (key == "max-message-size") {
  699. mMaxMessageSize = to_integer<size_t>(value);
  700. } else {
  701. Entry::parseSdpLine(line);
  702. }
  703. } else {
  704. Entry::parseSdpLine(line);
  705. }
  706. }
  707. Description::Media::Media(const string &mline, string mid, Direction dir)
  708. : Entry(mline, std::move(mid), dir) {
  709. std::istringstream ss(Entry::description());
  710. int payloadType;
  711. while (ss >> payloadType)
  712. mOrderedPayloadTypes.push_back(payloadType);
  713. }
  714. Description::Media::Media(const string &sdp) : Media(get_first_line(sdp), "", Direction::Unknown) {
  715. string line;
  716. std::istringstream ss(sdp);
  717. std::getline(ss, line); // discard first line
  718. while (ss) {
  719. std::getline(ss, line);
  720. trim_end(line);
  721. if (line.empty())
  722. continue;
  723. parseSdpLine(line);
  724. }
  725. if (mid().empty())
  726. throw std::invalid_argument("Missing mid in media description");
  727. }
  728. string Description::Media::description() const {
  729. std::ostringstream ss;
  730. for (auto it = mOrderedPayloadTypes.begin(); it != mOrderedPayloadTypes.end(); ++it) {
  731. if (it != mOrderedPayloadTypes.begin())
  732. ss << ' ';
  733. ss << *it;
  734. }
  735. return ss.str();
  736. }
  737. Description::Media Description::Media::reciprocate() const {
  738. Media reciprocated(*this);
  739. // Invert direction
  740. switch (reciprocated.direction()) {
  741. case Direction::RecvOnly:
  742. reciprocated.setDirection(Direction::SendOnly);
  743. break;
  744. case Direction::SendOnly:
  745. reciprocated.setDirection(Direction::RecvOnly);
  746. break;
  747. default:
  748. // We are good
  749. break;
  750. }
  751. // Invert directions of extmap
  752. auto &extMaps = reciprocated.mExtMaps;
  753. for (auto it = extMaps.begin(); it != extMaps.end(); ++it) {
  754. auto &map = it->second;
  755. switch (map.direction) {
  756. case Direction::RecvOnly:
  757. map.direction = Direction::SendOnly;
  758. break;
  759. case Direction::SendOnly:
  760. map.direction = Direction::RecvOnly;
  761. break;
  762. default:
  763. // We are good
  764. break;
  765. }
  766. }
  767. // Clear sent SSRCs
  768. reciprocated.clearSSRCs();
  769. // Remove rtcp-rsize attribute as Reduced-Size RTCP is not supported (see RFC 5506)
  770. reciprocated.removeAttribute("rtcp-rsize");
  771. return reciprocated;
  772. }
  773. int Description::Media::bitrate() const { return mBas; }
  774. void Description::Media::setBitrate(int bitrate) { mBas = bitrate; }
  775. bool Description::Media::hasPayloadType(int payloadType) const {
  776. return mRtpMaps.find(payloadType) != mRtpMaps.end();
  777. }
  778. std::vector<int> Description::Media::payloadTypes() const { return mOrderedPayloadTypes; }
  779. Description::Media::RtpMap *Description::Media::rtpMap(int payloadType) {
  780. auto it = mRtpMaps.find(payloadType);
  781. if (it == mRtpMaps.end())
  782. throw std::invalid_argument("rtpmap not found");
  783. return &it->second;
  784. }
  785. const Description::Media::RtpMap *Description::Media::rtpMap(int payloadType) const {
  786. auto it = mRtpMaps.find(payloadType);
  787. if (it == mRtpMaps.end())
  788. throw std::invalid_argument("rtpmap not found");
  789. return &it->second;
  790. }
  791. void Description::Media::addRtpMap(RtpMap map) {
  792. int payloadType = map.payloadType;
  793. if (std::find(mOrderedPayloadTypes.begin(), mOrderedPayloadTypes.end(), payloadType) ==
  794. mOrderedPayloadTypes.end())
  795. mOrderedPayloadTypes.push_back(payloadType);
  796. mRtpMaps.emplace(payloadType, std::move(map));
  797. }
  798. void Description::Media::removeRtpMap(int payloadType) {
  799. // Remove the actual format
  800. mOrderedPayloadTypes.erase(
  801. std::remove(mOrderedPayloadTypes.begin(), mOrderedPayloadTypes.end(), payloadType),
  802. mOrderedPayloadTypes.end());
  803. mRtpMaps.erase(payloadType);
  804. // Remove any other rtpmaps that depend on the format we just removed
  805. auto it = mRtpMaps.begin();
  806. while (it != mRtpMaps.end()) {
  807. const auto &fmtps = it->second.fmtps;
  808. if (std::find(fmtps.begin(), fmtps.end(), "apt=" + std::to_string(payloadType)) !=
  809. fmtps.end()) {
  810. mOrderedPayloadTypes.erase(
  811. std::remove(mOrderedPayloadTypes.begin(), mOrderedPayloadTypes.end(), it->first),
  812. mOrderedPayloadTypes.end());
  813. it = mRtpMaps.erase(it);
  814. } else {
  815. ++it;
  816. }
  817. }
  818. }
  819. void Description::Media::removeFormat(const string &format) {
  820. std::vector<int> payloadTypes;
  821. for (const auto &it : mRtpMaps) {
  822. if (it.second.format == format)
  823. payloadTypes.push_back(it.first);
  824. }
  825. for (int pt : payloadTypes)
  826. removeRtpMap(pt);
  827. }
  828. void Description::Media::addRtxCodec(int payloadType, int origPayloadType, unsigned int clockRate) {
  829. RtpMap rtp(std::to_string(payloadType) + " RTX/" + std::to_string(clockRate));
  830. rtp.fmtps.emplace_back("apt=" + std::to_string(origPayloadType));
  831. addRtpMap(rtp);
  832. }
  833. string Description::Media::generateSdpLines(string_view eol) const {
  834. std::ostringstream sdp;
  835. if (mBas >= 0)
  836. sdp << "b=AS:" << mBas << eol;
  837. sdp << Entry::generateSdpLines(eol);
  838. sdp << "a=rtcp-mux" << eol;
  839. for (auto it = mRtpMaps.begin(); it != mRtpMaps.end(); ++it) {
  840. auto &map = it->second;
  841. // Create the a=rtpmap
  842. sdp << "a=rtpmap:" << map.payloadType << ' ' << map.format << '/' << map.clockRate;
  843. if (!map.encParams.empty())
  844. sdp << '/' << map.encParams;
  845. sdp << eol;
  846. for (const auto &val : map.rtcpFbs)
  847. sdp << "a=rtcp-fb:" << map.payloadType << ' ' << val << eol;
  848. for (const auto &val : map.fmtps)
  849. sdp << "a=fmtp:" << map.payloadType << ' ' << val << eol;
  850. }
  851. return sdp.str();
  852. }
  853. void Description::Media::parseSdpLine(string_view line) {
  854. if (match_prefix(line, "a=")) {
  855. string_view attr = line.substr(2);
  856. auto [key, value] = parse_pair(attr);
  857. if (key == "rtpmap") {
  858. auto pt = Description::Media::RtpMap::parsePayloadType(value);
  859. auto it = mRtpMaps.find(pt);
  860. if (it == mRtpMaps.end())
  861. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(value))).first;
  862. else
  863. it->second.setDescription(value);
  864. } else if (key == "rtcp-fb") {
  865. size_t p = value.find(' ');
  866. int pt = to_integer<int>(value.substr(0, p));
  867. auto it = mRtpMaps.find(pt);
  868. if (it == mRtpMaps.end())
  869. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(pt))).first;
  870. it->second.rtcpFbs.emplace_back(value.substr(p + 1));
  871. } else if (key == "fmtp") {
  872. size_t p = value.find(' ');
  873. int pt = to_integer<int>(value.substr(0, p));
  874. auto it = mRtpMaps.find(pt);
  875. if (it == mRtpMaps.end())
  876. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(pt))).first;
  877. it->second.fmtps.emplace_back(value.substr(p + 1));
  878. } else if (key == "rtcp-mux") {
  879. // always added
  880. } else if (key == "ssrc") {
  881. auto ssrc = to_integer<uint32_t>(value);
  882. if (!hasSSRC(ssrc))
  883. mSsrcs.emplace_back(ssrc);
  884. auto cnamePos = value.find("cname:");
  885. if (cnamePos != string::npos) {
  886. auto cname = value.substr(cnamePos + 6);
  887. mCNameMap.emplace(ssrc, cname);
  888. }
  889. mAttributes.emplace_back(attr);
  890. } else {
  891. Entry::parseSdpLine(line);
  892. }
  893. } else if (match_prefix(line, "b=AS")) {
  894. mBas = to_integer<int>(line.substr(line.find(':') + 1));
  895. } else {
  896. Entry::parseSdpLine(line);
  897. }
  898. }
  899. Description::Media::RtpMap::RtpMap(int payloadType) {
  900. this->payloadType = payloadType;
  901. this->clockRate = 0;
  902. }
  903. int Description::Media::RtpMap::parsePayloadType(string_view mline) {
  904. size_t p = mline.find(' ');
  905. return to_integer<int>(mline.substr(0, p));
  906. }
  907. Description::Media::RtpMap::RtpMap(string_view description) { setDescription(description); }
  908. void Description::Media::RtpMap::setDescription(string_view description) {
  909. size_t p = description.find(' ');
  910. if (p == string::npos)
  911. throw std::invalid_argument("Invalid format description for rtpmap");
  912. this->payloadType = to_integer<int>(description.substr(0, p));
  913. string_view line = description.substr(p + 1);
  914. size_t spl = line.find('/');
  915. if (spl == string::npos)
  916. throw std::invalid_argument("Invalid format description for rtpmap");
  917. this->format = line.substr(0, spl);
  918. line = line.substr(spl + 1);
  919. spl = line.find('/');
  920. if (spl == string::npos) {
  921. spl = line.find(' ');
  922. }
  923. if (spl == string::npos)
  924. this->clockRate = to_integer<int>(line);
  925. else {
  926. this->clockRate = to_integer<int>(line.substr(0, spl));
  927. this->encParams = line.substr(spl + 1);
  928. }
  929. }
  930. void Description::Media::RtpMap::addFeedback(string fb) {
  931. if (std::find(rtcpFbs.begin(), rtcpFbs.end(), fb) == rtcpFbs.end())
  932. rtcpFbs.emplace_back(std::move(fb));
  933. }
  934. void Description::Media::RtpMap::removeFeedback(const string &str) {
  935. auto it = rtcpFbs.begin();
  936. while (it != rtcpFbs.end()) {
  937. if (it->find(str) != string::npos)
  938. it = rtcpFbs.erase(it);
  939. else
  940. it++;
  941. }
  942. }
  943. void Description::Media::RtpMap::addParameter(string p) {
  944. if (std::find(fmtps.begin(), fmtps.end(), p) == fmtps.end())
  945. fmtps.emplace_back(std::move(p));
  946. }
  947. void Description::Media::RtpMap::removeParameter(const string &str) {
  948. fmtps.erase(std::remove_if(fmtps.begin(), fmtps.end(),
  949. [&](const auto &p) { return p.find(str) != string::npos; }),
  950. fmtps.end());
  951. }
  952. Description::Audio::Audio(string mid, Direction dir)
  953. : Media("audio 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  954. void Description::Audio::addAudioCodec(int payloadType, string codec, optional<string> profile) {
  955. if (codec.find('/') == string::npos) {
  956. if (codec == "PCMA" || codec == "PCMU")
  957. codec += "/8000/1";
  958. else
  959. codec += "/48000/2";
  960. }
  961. RtpMap map(std::to_string(payloadType) + ' ' + codec);
  962. if (profile)
  963. map.fmtps.emplace_back(*profile);
  964. addRtpMap(map);
  965. }
  966. void Description::Audio::addOpusCodec(int payloadType, optional<string> profile) {
  967. addAudioCodec(payloadType, "opus", profile);
  968. }
  969. void Description::Audio::addPCMACodec(int payloadType, optional<string> profile) {
  970. addAudioCodec(payloadType, "PCMA", profile);
  971. }
  972. void Description::Audio::addPCMUCodec(int payloadType, optional<string> profile) {
  973. addAudioCodec(payloadType, "PCMU", profile);
  974. }
  975. void Description::Audio::addAACCodec(int payloadType, optional<string> profile) {
  976. if (profile) {
  977. addAudioCodec(payloadType, "MP4A-LATM", profile);
  978. } else {
  979. addAudioCodec(payloadType, "MP4A-LATM", "cpresent=1");
  980. }
  981. }
  982. Description::Video::Video(string mid, Direction dir)
  983. : Media("video 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  984. void Description::Video::addVideoCodec(int payloadType, string codec, optional<string> profile) {
  985. if (codec.find('/') == string::npos)
  986. codec += "/90000";
  987. RtpMap map(std::to_string(payloadType) + ' ' + codec);
  988. map.addFeedback("nack");
  989. map.addFeedback("nack pli");
  990. // map.addFB("ccm fir");
  991. map.addFeedback("goog-remb");
  992. if (profile)
  993. map.fmtps.emplace_back(*profile);
  994. addRtpMap(map);
  995. /* TODO
  996. * TIL that Firefox does not properly support the negotiation of RTX! It works, but doesn't
  997. * negotiate the SSRC so we have no idea what SSRC is RTX going to be. Three solutions: One) we
  998. * don't negotitate it and (maybe) break RTX support with Edge. Two) we do negotiate it and
  999. * rebuild the original packet before we send it distribute it to each track. Three) we complain
  1000. * to mozilla. This one probably won't do much.
  1001. */
  1002. // RTX Packets
  1003. // Format rtx(std::to_string(payloadType+1) + " rtx/90000");
  1004. // // TODO rtx-time is how long can a request be stashed for before needing to resend it.
  1005. // Needs to be parameterized rtx.addAttribute("apt=" + std::to_string(payloadType) +
  1006. // ";rtx-time=3000"); addFormat(rtx);
  1007. }
  1008. void Description::Video::addH264Codec(int payloadType, optional<string> profile) {
  1009. addVideoCodec(payloadType, "H264", profile);
  1010. }
  1011. void Description::Video::addH265Codec(int payloadType, optional<string> profile) {
  1012. addVideoCodec(payloadType, "H265", profile);
  1013. }
  1014. void Description::Video::addVP8Codec(int payloadType, optional<string> profile) {
  1015. addVideoCodec(payloadType, "VP8", profile);
  1016. }
  1017. void Description::Video::addVP9Codec(int payloadType, optional<string> profile) {
  1018. addVideoCodec(payloadType, "VP9", profile);
  1019. }
  1020. void Description::Video::addAV1Codec(int payloadType, optional<string> profile) {
  1021. addVideoCodec(payloadType, "AV1", profile);
  1022. }
  1023. Description::Type Description::stringToType(const string &typeString) {
  1024. using TypeMap_t = std::unordered_map<string, Type>;
  1025. static const TypeMap_t TypeMap = {{"unspec", Type::Unspec},
  1026. {"offer", Type::Offer},
  1027. {"answer", Type::Answer},
  1028. {"pranswer", Type::Pranswer},
  1029. {"rollback", Type::Rollback}};
  1030. auto it = TypeMap.find(typeString);
  1031. return it != TypeMap.end() ? it->second : Type::Unspec;
  1032. }
  1033. string Description::typeToString(Type type) {
  1034. switch (type) {
  1035. case Type::Unspec:
  1036. return "unspec";
  1037. case Type::Offer:
  1038. return "offer";
  1039. case Type::Answer:
  1040. return "answer";
  1041. case Type::Pranswer:
  1042. return "pranswer";
  1043. case Type::Rollback:
  1044. return "rollback";
  1045. default:
  1046. return "unknown";
  1047. }
  1048. }
  1049. size_t
  1050. CertificateFingerprint::AlgorithmSize(CertificateFingerprint::Algorithm fingerprintAlgorithm) {
  1051. switch (fingerprintAlgorithm) {
  1052. case CertificateFingerprint::Algorithm::Sha1:
  1053. return 20;
  1054. case CertificateFingerprint::Algorithm::Sha224:
  1055. return 28;
  1056. case CertificateFingerprint::Algorithm::Sha256:
  1057. return 32;
  1058. case CertificateFingerprint::Algorithm::Sha384:
  1059. return 48;
  1060. case CertificateFingerprint::Algorithm::Sha512:
  1061. return 64;
  1062. default:
  1063. return 0;
  1064. }
  1065. }
  1066. std::string CertificateFingerprint::AlgorithmIdentifier(
  1067. CertificateFingerprint::Algorithm fingerprintAlgorithm) {
  1068. switch (fingerprintAlgorithm) {
  1069. case CertificateFingerprint::Algorithm::Sha1:
  1070. return "sha-1";
  1071. case CertificateFingerprint::Algorithm::Sha224:
  1072. return "sha-224";
  1073. case CertificateFingerprint::Algorithm::Sha256:
  1074. return "sha-256";
  1075. case CertificateFingerprint::Algorithm::Sha384:
  1076. return "sha-384";
  1077. case CertificateFingerprint::Algorithm::Sha512:
  1078. return "sha-512";
  1079. default:
  1080. return "unknown";
  1081. }
  1082. }
  1083. bool CertificateFingerprint::isValid() const {
  1084. size_t expectedSize = AlgorithmSize(this->algorithm);
  1085. if (expectedSize == 0 || this->value.size() != expectedSize * 3 - 1) {
  1086. return false;
  1087. }
  1088. for (size_t i = 0; i < this->value.size(); ++i) {
  1089. if (i % 3 == 2) {
  1090. if (this->value[i] != ':')
  1091. return false;
  1092. } else {
  1093. if (!std::isxdigit(this->value[i]))
  1094. return false;
  1095. }
  1096. }
  1097. return true;
  1098. }
  1099. std::ostream &operator<<(std::ostream &out, const Description &description) {
  1100. return out << string(description);
  1101. }
  1102. std::ostream &operator<<(std::ostream &out, Description::Type type) {
  1103. return out << Description::typeToString(type);
  1104. }
  1105. std::ostream &operator<<(std::ostream &out, Description::Role role) {
  1106. using Role = Description::Role;
  1107. // Used for SDP generation, do not change
  1108. switch (role) {
  1109. case Role::Active:
  1110. out << "active";
  1111. break;
  1112. case Role::Passive:
  1113. out << "passive";
  1114. break;
  1115. default:
  1116. out << "actpass";
  1117. break;
  1118. }
  1119. return out;
  1120. }
  1121. std::ostream &operator<<(std::ostream &out, const Description::Direction &direction) {
  1122. // Used for SDP generation, do not change
  1123. switch (direction) {
  1124. case Description::Direction::RecvOnly:
  1125. out << "recvonly";
  1126. break;
  1127. case Description::Direction::SendOnly:
  1128. out << "sendonly";
  1129. break;
  1130. case Description::Direction::SendRecv:
  1131. out << "sendrecv";
  1132. break;
  1133. case Description::Direction::Inactive:
  1134. out << "inactive";
  1135. break;
  1136. case Description::Direction::Unknown:
  1137. default:
  1138. out << "unknown";
  1139. break;
  1140. }
  1141. return out;
  1142. }
  1143. } // namespace rtc