description.cpp 35 KB

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