description.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  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://www.rfc-editor.org/rfc/rfc8843.html
  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 uint16_t port =
  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 uint16_t port =
  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>(mline, 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 && !mApplication->isRemoved(); }
  341. bool Description::hasAudioOrVideo() const {
  342. for (auto entry : mEntries)
  343. if (entry != mApplication && !entry->isRemoved())
  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. uint16_t port;
  413. std::istringstream ss(mline);
  414. ss >> mType;
  415. ss >> port;
  416. ss >> mDescription;
  417. // RFC 3264: Existing media streams are removed by creating a new SDP with the port number for
  418. // that stream set to zero.
  419. mIsRemoved = (port == 0);
  420. }
  421. void Description::Entry::setDirection(Direction dir) { mDirection = dir; }
  422. void Description::Entry::markRemoved() { mIsRemoved = true; }
  423. std::vector<string> Description::attributes() const { return mAttributes; }
  424. void Description::addAttribute(string attr) {
  425. if (std::find(mAttributes.begin(), mAttributes.end(), attr) == mAttributes.end())
  426. mAttributes.emplace_back(std::move(attr));
  427. }
  428. void Description::removeAttribute(const string &attr) {
  429. mAttributes.erase(
  430. std::remove_if(mAttributes.begin(), mAttributes.end(),
  431. [&](const auto &a) { return a == attr || parse_pair(a).first == attr; }),
  432. mAttributes.end());
  433. }
  434. std::vector<int> Description::Entry::extIds() {
  435. std::vector<int> result;
  436. for (auto it = mExtMaps.begin(); it != mExtMaps.end(); ++it)
  437. result.push_back(it->first);
  438. return result;
  439. }
  440. Description::Entry::ExtMap *Description::Entry::extMap(int id) {
  441. auto it = mExtMaps.find(id);
  442. if (it == mExtMaps.end())
  443. throw std::invalid_argument("extmap not found");
  444. return &it->second;
  445. }
  446. void Description::Entry::addExtMap(ExtMap map) {
  447. auto id = map.id;
  448. mExtMaps.emplace(id, std::move(map));
  449. }
  450. void Description::Entry::removeExtMap(int id) { mExtMaps.erase(id); }
  451. Description::Entry::operator string() const { return generateSdp("\r\n", "IP4 0.0.0.0", 9); }
  452. string Description::Entry::generateSdp(string_view eol, string_view addr, uint16_t port) const {
  453. std::ostringstream sdp;
  454. // RFC 3264: Existing media streams are removed by creating a new SDP with the port number for
  455. // that stream set to zero. [...] A stream that is offered with a port of zero MUST be marked
  456. // with port zero in the answer.
  457. sdp << "m=" << type() << ' ' << (mIsRemoved ? 0 : port) << ' ' << description() << eol;
  458. sdp << "c=IN " << addr << eol;
  459. sdp << generateSdpLines(eol);
  460. return sdp.str();
  461. }
  462. string Description::Entry::generateSdpLines(string_view eol) const {
  463. std::ostringstream sdp;
  464. sdp << "a=bundle-only" << eol;
  465. sdp << "a=mid:" << mMid << eol;
  466. for (auto it = mExtMaps.begin(); it != mExtMaps.end(); ++it) {
  467. auto &map = it->second;
  468. sdp << "a=extmap:" << map.id;
  469. switch (map.direction) {
  470. case Direction::SendOnly:
  471. sdp << "/sendonly";
  472. break;
  473. case Direction::RecvOnly:
  474. sdp << "/recvonly";
  475. break;
  476. case Direction::SendRecv:
  477. sdp << "/sendrecv";
  478. break;
  479. case Direction::Inactive:
  480. sdp << "/inactive";
  481. break;
  482. default:
  483. // Ignore
  484. break;
  485. }
  486. sdp << ' ' << map.uri;
  487. if (!map.attributes.empty())
  488. sdp << ' ' << map.attributes;
  489. sdp << eol;
  490. }
  491. switch (mDirection) {
  492. case Direction::SendOnly:
  493. sdp << "a=sendonly" << eol;
  494. break;
  495. case Direction::RecvOnly:
  496. sdp << "a=recvonly" << eol;
  497. break;
  498. case Direction::SendRecv:
  499. sdp << "a=sendrecv" << eol;
  500. break;
  501. case Direction::Inactive:
  502. sdp << "a=inactive" << eol;
  503. break;
  504. default:
  505. // Ignore
  506. break;
  507. }
  508. for (const auto &attr : mAttributes)
  509. sdp << "a=" << attr << eol;
  510. return sdp.str();
  511. }
  512. void Description::Entry::parseSdpLine(string_view line) {
  513. if (match_prefix(line, "a=")) {
  514. string_view attr = line.substr(2);
  515. auto [key, value] = parse_pair(attr);
  516. if (key == "mid") {
  517. mMid = value;
  518. } else if (key == "extmap") {
  519. auto id = Description::Media::ExtMap::parseId(value);
  520. auto it = mExtMaps.find(id);
  521. if (it == mExtMaps.end())
  522. it = mExtMaps.insert(std::make_pair(id, Description::Media::ExtMap(value))).first;
  523. else
  524. it->second.setDescription(value);
  525. } else if (attr == "sendonly")
  526. mDirection = Direction::SendOnly;
  527. else if (attr == "recvonly")
  528. mDirection = Direction::RecvOnly;
  529. else if (key == "sendrecv")
  530. mDirection = Direction::SendRecv;
  531. else if (key == "inactive")
  532. mDirection = Direction::Inactive;
  533. else if (key == "bundle-only") {
  534. // always added
  535. } else
  536. mAttributes.emplace_back(attr);
  537. }
  538. }
  539. std::vector<string>::iterator Description::Entry::beginAttributes() { return mAttributes.begin(); }
  540. std::vector<string>::iterator Description::Entry::endAttributes() { return mAttributes.end(); }
  541. std::vector<string>::iterator
  542. Description::Entry::removeAttribute(std::vector<string>::iterator it) {
  543. return mAttributes.erase(it);
  544. }
  545. std::map<int, Description::Entry::ExtMap>::iterator Description::Entry::beginExtMaps() {
  546. return mExtMaps.begin();
  547. }
  548. std::map<int, Description::Entry::ExtMap>::iterator Description::Entry::endExtMaps() {
  549. return mExtMaps.end();
  550. }
  551. std::map<int, Description::Entry::ExtMap>::iterator
  552. Description::Entry::removeExtMap(std::map<int, Description::Entry::ExtMap>::iterator iterator) {
  553. return mExtMaps.erase(iterator);
  554. }
  555. Description::Entry::ExtMap::ExtMap(string_view description) { setDescription(description); }
  556. int Description::Entry::ExtMap::parseId(string_view description) {
  557. size_t p = description.find(' ');
  558. return to_integer<int>(description.substr(0, p));
  559. }
  560. void Description::Entry::ExtMap::setDescription(string_view description) {
  561. const size_t uriStart = description.find(' ');
  562. if (uriStart == string::npos)
  563. throw std::invalid_argument("Invalid description");
  564. const string_view idAndDirection = description.substr(0, uriStart);
  565. const size_t idSplit = idAndDirection.find('/');
  566. if (idSplit == string::npos) {
  567. this->id = to_integer<int>(idAndDirection);
  568. } else {
  569. this->id = to_integer<int>(idAndDirection.substr(0, idSplit));
  570. const string_view directionStr = idAndDirection.substr(idSplit + 1);
  571. if (directionStr == "sendonly")
  572. this->direction = Direction::SendOnly;
  573. else if (directionStr == "recvonly")
  574. this->direction = Direction::RecvOnly;
  575. else if (directionStr == "sendrecv")
  576. this->direction = Direction::SendRecv;
  577. else if (directionStr == "inactive")
  578. this->direction = Direction::Inactive;
  579. else
  580. throw std::invalid_argument("Invalid direction");
  581. }
  582. const string_view uriAndAttributes = description.substr(uriStart + 1);
  583. const size_t attributeSplit = uriAndAttributes.find(' ');
  584. if (attributeSplit == string::npos)
  585. this->uri = uriAndAttributes;
  586. else {
  587. this->uri = uriAndAttributes.substr(0, attributeSplit);
  588. this->attributes = uriAndAttributes.substr(attributeSplit + 1);
  589. }
  590. }
  591. void Description::Media::addSSRC(uint32_t ssrc, optional<string> name, optional<string> msid,
  592. optional<string> trackId) {
  593. if (name) {
  594. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " cname:" + *name);
  595. mCNameMap.emplace(ssrc, *name);
  596. } else {
  597. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc));
  598. }
  599. if (msid)
  600. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " msid:" + *msid + " " +
  601. trackId.value_or(*msid));
  602. mSsrcs.emplace_back(ssrc);
  603. }
  604. void Description::Media::removeSSRC(uint32_t ssrc) {
  605. string prefix = "ssrc:" + std::to_string(ssrc);
  606. mAttributes.erase(std::remove_if(mAttributes.begin(), mAttributes.end(),
  607. [&](const auto &a) { return match_prefix(a, prefix); }),
  608. mAttributes.end());
  609. mSsrcs.erase(std::remove(mSsrcs.begin(), mSsrcs.end(), ssrc), mSsrcs.end());
  610. }
  611. void Description::Media::replaceSSRC(uint32_t old, uint32_t ssrc, optional<string> name,
  612. optional<string> msid, optional<string> trackID) {
  613. removeSSRC(old);
  614. addSSRC(ssrc, std::move(name), std::move(msid), std::move(trackID));
  615. }
  616. bool Description::Media::hasSSRC(uint32_t ssrc) {
  617. return std::find(mSsrcs.begin(), mSsrcs.end(), ssrc) != mSsrcs.end();
  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. for (auto it = reciprocated.mExtMaps.begin(); it != reciprocated.mExtMaps.end(); ++it) {
  693. auto &map = it->second;
  694. switch (map.direction) {
  695. case Direction::RecvOnly:
  696. map.direction = Direction::SendOnly;
  697. break;
  698. case Direction::SendOnly:
  699. map.direction = Direction::RecvOnly;
  700. break;
  701. default:
  702. // We are good
  703. break;
  704. }
  705. }
  706. // Clear all ssrc attributes as they are individual
  707. auto it = reciprocated.mAttributes.begin();
  708. while (it != reciprocated.mAttributes.end()) {
  709. if (match_prefix(*it, "ssrc:"))
  710. it = reciprocated.mAttributes.erase(it);
  711. else
  712. ++it;
  713. }
  714. reciprocated.mSsrcs.clear();
  715. reciprocated.mCNameMap.clear();
  716. // Remove rtcp-rsize attribute as Reduced-Size RTCP is not supported (see RFC 5506)
  717. reciprocated.removeAttribute("rtcp-rsize");
  718. return reciprocated;
  719. }
  720. std::vector<uint32_t> Description::Media::getSSRCs() { return mSsrcs; }
  721. optional<string> Description::Media::getCNameForSsrc(uint32_t ssrc) {
  722. auto it = mCNameMap.find(ssrc);
  723. if (it != mCNameMap.end()) {
  724. return it->second;
  725. }
  726. return nullopt;
  727. }
  728. int Description::Media::bitrate() const { return mBas; }
  729. void Description::Media::setBitrate(int bitrate) { mBas = bitrate; }
  730. bool Description::Media::hasPayloadType(int payloadType) const {
  731. return mRtpMaps.find(payloadType) != mRtpMaps.end();
  732. }
  733. std::vector<int> Description::Media::payloadTypes() const {
  734. std::vector<int> result;
  735. result.reserve(mRtpMaps.size());
  736. for (auto it = mRtpMaps.begin(); it != mRtpMaps.end(); ++it)
  737. result.push_back(it->first);
  738. return result;
  739. }
  740. Description::Media::RtpMap *Description::Media::rtpMap(int payloadType) {
  741. auto it = mRtpMaps.find(payloadType);
  742. if (it == mRtpMaps.end())
  743. throw std::invalid_argument("rtpmap not found");
  744. return &it->second;
  745. }
  746. void Description::Media::addRtpMap(RtpMap map) {
  747. auto payloadType = map.payloadType;
  748. mRtpMaps.emplace(payloadType, std::move(map));
  749. }
  750. void Description::Media::removeRtpMap(int payloadType) {
  751. // Remove the actual format
  752. mRtpMaps.erase(payloadType);
  753. // Remove any other rtpmaps that depend on the format we just removed
  754. auto it = mRtpMaps.begin();
  755. while (it != mRtpMaps.end()) {
  756. const auto &fmtps = it->second.fmtps;
  757. if (std::find(fmtps.begin(), fmtps.end(), "apt=" + std::to_string(payloadType)) !=
  758. fmtps.end())
  759. it = mRtpMaps.erase(it);
  760. else
  761. ++it;
  762. }
  763. }
  764. void Description::Media::removeFormat(const string &format) {
  765. std::vector<int> payloadTypes;
  766. auto it = mRtpMaps.begin();
  767. while (it != mRtpMaps.end()) {
  768. if (it->second.format == format)
  769. payloadTypes.push_back(it->first);
  770. else
  771. ++it;
  772. }
  773. for (int pt : payloadTypes)
  774. removeRtpMap(pt);
  775. }
  776. void Description::Media::addRtxCodec(int payloadType, int origPayloadType, unsigned int clockRate) {
  777. RtpMap rtp(std::to_string(payloadType) + " RTX/" + std::to_string(clockRate));
  778. rtp.fmtps.emplace_back("apt=" + std::to_string(origPayloadType));
  779. addRtpMap(rtp);
  780. }
  781. string Description::Media::generateSdpLines(string_view eol) const {
  782. std::ostringstream sdp;
  783. if (mBas >= 0)
  784. sdp << "b=AS:" << mBas << eol;
  785. sdp << Entry::generateSdpLines(eol);
  786. sdp << "a=rtcp-mux" << eol;
  787. for (auto it = mRtpMaps.begin(); it != mRtpMaps.end(); ++it) {
  788. auto &map = it->second;
  789. // Create the a=rtpmap
  790. sdp << "a=rtpmap:" << map.payloadType << ' ' << map.format << '/' << map.clockRate;
  791. if (!map.encParams.empty())
  792. sdp << '/' << map.encParams;
  793. sdp << eol;
  794. for (const auto &val : map.rtcpFbs)
  795. if (val != "transport-cc")
  796. sdp << "a=rtcp-fb:" << map.payloadType << ' ' << val << eol;
  797. for (const auto &val : map.fmtps)
  798. sdp << "a=fmtp:" << map.payloadType << ' ' << val << eol;
  799. }
  800. return sdp.str();
  801. }
  802. void Description::Media::parseSdpLine(string_view line) {
  803. if (match_prefix(line, "a=")) {
  804. string_view attr = line.substr(2);
  805. auto [key, value] = parse_pair(attr);
  806. if (key == "rtpmap") {
  807. auto pt = Description::Media::RtpMap::parsePayloadType(value);
  808. auto it = mRtpMaps.find(pt);
  809. if (it == mRtpMaps.end())
  810. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(value))).first;
  811. else
  812. it->second.setDescription(value);
  813. } else if (key == "rtcp-fb") {
  814. size_t p = value.find(' ');
  815. int pt = to_integer<int>(value.substr(0, p));
  816. auto it = mRtpMaps.find(pt);
  817. if (it == mRtpMaps.end())
  818. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(pt))).first;
  819. it->second.rtcpFbs.emplace_back(value.substr(p + 1));
  820. } else if (key == "fmtp") {
  821. size_t p = value.find(' ');
  822. int pt = to_integer<int>(value.substr(0, p));
  823. auto it = mRtpMaps.find(pt);
  824. if (it == mRtpMaps.end())
  825. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(pt))).first;
  826. it->second.fmtps.emplace_back(value.substr(p + 1));
  827. } else if (key == "rtcp-mux") {
  828. // always added
  829. } else if (key == "ssrc") {
  830. auto ssrc = to_integer<uint32_t>(value);
  831. if (!hasSSRC(ssrc))
  832. mSsrcs.emplace_back(ssrc);
  833. auto cnamePos = value.find("cname:");
  834. if (cnamePos != string::npos) {
  835. auto cname = value.substr(cnamePos + 6);
  836. mCNameMap.emplace(ssrc, cname);
  837. }
  838. mAttributes.emplace_back(attr);
  839. } else {
  840. Entry::parseSdpLine(line);
  841. }
  842. } else if (match_prefix(line, "b=AS")) {
  843. mBas = to_integer<int>(line.substr(line.find(':') + 1));
  844. } else {
  845. Entry::parseSdpLine(line);
  846. }
  847. }
  848. std::map<int, Description::Media::RtpMap>::iterator Description::Media::beginMaps() {
  849. return mRtpMaps.begin();
  850. }
  851. std::map<int, Description::Media::RtpMap>::iterator Description::Media::endMaps() {
  852. return mRtpMaps.end();
  853. }
  854. std::map<int, Description::Media::RtpMap>::iterator
  855. Description::Media::removeMap(std::map<int, Description::Media::RtpMap>::iterator iterator) {
  856. return mRtpMaps.erase(iterator);
  857. }
  858. Description::Media::RtpMap::RtpMap(int payloadType) {
  859. this->payloadType = payloadType;
  860. this->clockRate = 0;
  861. }
  862. int Description::Media::RtpMap::parsePayloadType(string_view mline) {
  863. size_t p = mline.find(' ');
  864. return to_integer<int>(mline.substr(0, p));
  865. }
  866. Description::Media::RtpMap::RtpMap(string_view description) { setDescription(description); }
  867. void Description::Media::RtpMap::setDescription(string_view description) {
  868. size_t p = description.find(' ');
  869. if (p == string::npos)
  870. throw std::invalid_argument("Invalid format description");
  871. this->payloadType = to_integer<int>(description.substr(0, p));
  872. string_view line = description.substr(p + 1);
  873. size_t spl = line.find('/');
  874. if (spl == string::npos)
  875. throw std::invalid_argument("Invalid format description");
  876. this->format = line.substr(0, spl);
  877. line = line.substr(spl + 1);
  878. spl = line.find('/');
  879. if (spl == string::npos) {
  880. spl = line.find(' ');
  881. }
  882. if (spl == string::npos)
  883. this->clockRate = to_integer<int>(line);
  884. else {
  885. this->clockRate = to_integer<int>(line.substr(0, spl));
  886. this->encParams = line.substr(spl + 1);
  887. }
  888. }
  889. void Description::Media::RtpMap::addFeedback(string fb) {
  890. if (std::find(rtcpFbs.begin(), rtcpFbs.end(), fb) == rtcpFbs.end())
  891. fmtps.emplace_back(std::move(fb));
  892. }
  893. void Description::Media::RtpMap::removeFeedback(const string &str) {
  894. auto it = rtcpFbs.begin();
  895. while (it != rtcpFbs.end()) {
  896. if (it->find(str) != string::npos)
  897. it = rtcpFbs.erase(it);
  898. else
  899. it++;
  900. }
  901. }
  902. void Description::Media::RtpMap::addParameter(string p) {
  903. if (std::find(fmtps.begin(), fmtps.end(), p) == fmtps.end())
  904. fmtps.emplace_back(std::move(p));
  905. }
  906. void Description::Media::RtpMap::removeParameter(const string &str) {
  907. fmtps.erase(std::remove_if(fmtps.begin(), fmtps.end(),
  908. [&](const auto &p) { return p.find(str) != string::npos; }),
  909. fmtps.end());
  910. }
  911. Description::Audio::Audio(string mid, Direction dir)
  912. : Media("audio 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  913. void Description::Audio::addAudioCodec(int payloadType, string codec, optional<string> profile) {
  914. if (codec.find('/') == string::npos)
  915. codec += "/48000/2";
  916. RtpMap map(std::to_string(payloadType) + ' ' + codec);
  917. if (profile)
  918. map.fmtps.emplace_back(*profile);
  919. addRtpMap(map);
  920. }
  921. void Description::Audio::addOpusCodec(int payloadType, optional<string> profile) {
  922. addAudioCodec(payloadType, "OPUS", profile);
  923. }
  924. Description::Video::Video(string mid, Direction dir)
  925. : Media("video 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  926. void Description::Video::addVideoCodec(int payloadType, string codec, optional<string> profile) {
  927. if (codec.find('/') == string::npos)
  928. codec += "/90000";
  929. RtpMap map(std::to_string(payloadType) + ' ' + codec);
  930. map.addFeedback("nack");
  931. map.addFeedback("nack pli");
  932. // map.addFB("ccm fir");
  933. map.addFeedback("goog-remb");
  934. if (profile)
  935. map.fmtps.emplace_back(*profile);
  936. addRtpMap(map);
  937. /* TODO
  938. * TIL that Firefox does not properly support the negotiation of RTX! It works, but doesn't
  939. * negotiate the SSRC so we have no idea what SSRC is RTX going to be. Three solutions: One) we
  940. * don't negotitate it and (maybe) break RTX support with Edge. Two) we do negotiate it and
  941. * rebuild the original packet before we send it distribute it to each track. Three) we complain
  942. * to mozilla. This one probably won't do much.
  943. */
  944. // RTX Packets
  945. // Format rtx(std::to_string(payloadType+1) + " rtx/90000");
  946. // // TODO rtx-time is how long can a request be stashed for before needing to resend it.
  947. // Needs to be parameterized rtx.addAttribute("apt=" + std::to_string(payloadType) +
  948. // ";rtx-time=3000"); addFormat(rtx);
  949. }
  950. void Description::Video::addH264Codec(int pt, optional<string> profile) {
  951. addVideoCodec(pt, "H264", profile);
  952. }
  953. void Description::Video::addVP8Codec(int payloadType) {
  954. addVideoCodec(payloadType, "VP8", nullopt);
  955. }
  956. void Description::Video::addVP9Codec(int payloadType) {
  957. addVideoCodec(payloadType, "VP9", nullopt);
  958. }
  959. Description::Type Description::stringToType(const string &typeString) {
  960. using TypeMap_t = std::unordered_map<string, Type>;
  961. static const TypeMap_t TypeMap = {{"unspec", Type::Unspec},
  962. {"offer", Type::Offer},
  963. {"answer", Type::Answer},
  964. {"pranswer", Type::Pranswer},
  965. {"rollback", Type::Rollback}};
  966. auto it = TypeMap.find(typeString);
  967. return it != TypeMap.end() ? it->second : Type::Unspec;
  968. }
  969. string Description::typeToString(Type type) {
  970. switch (type) {
  971. case Type::Unspec:
  972. return "unspec";
  973. case Type::Offer:
  974. return "offer";
  975. case Type::Answer:
  976. return "answer";
  977. case Type::Pranswer:
  978. return "pranswer";
  979. case Type::Rollback:
  980. return "rollback";
  981. default:
  982. return "unknown";
  983. }
  984. }
  985. } // namespace rtc
  986. std::ostream &operator<<(std::ostream &out, const rtc::Description &description) {
  987. return out << std::string(description);
  988. }
  989. std::ostream &operator<<(std::ostream &out, rtc::Description::Type type) {
  990. return out << rtc::Description::typeToString(type);
  991. }
  992. std::ostream &operator<<(std::ostream &out, rtc::Description::Role role) {
  993. using Role = rtc::Description::Role;
  994. // Used for SDP generation, do not change
  995. switch (role) {
  996. case Role::Active:
  997. out << "active";
  998. break;
  999. case Role::Passive:
  1000. out << "passive";
  1001. break;
  1002. default:
  1003. out << "actpass";
  1004. break;
  1005. }
  1006. return out;
  1007. }