description.cpp 35 KB

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