description.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  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. for (const auto &it : mRtpMaps) {
  767. if( it.second.format == format)
  768. payloadTypes.push_back(it.first);
  769. }
  770. for (int pt : payloadTypes)
  771. removeRtpMap(pt);
  772. }
  773. void Description::Media::addRtxCodec(int payloadType, int origPayloadType, unsigned int clockRate) {
  774. RtpMap rtp(std::to_string(payloadType) + " RTX/" + std::to_string(clockRate));
  775. rtp.fmtps.emplace_back("apt=" + std::to_string(origPayloadType));
  776. addRtpMap(rtp);
  777. }
  778. string Description::Media::generateSdpLines(string_view eol) const {
  779. std::ostringstream sdp;
  780. if (mBas >= 0)
  781. sdp << "b=AS:" << mBas << eol;
  782. sdp << Entry::generateSdpLines(eol);
  783. sdp << "a=rtcp-mux" << eol;
  784. for (auto it = mRtpMaps.begin(); it != mRtpMaps.end(); ++it) {
  785. auto &map = it->second;
  786. // Create the a=rtpmap
  787. sdp << "a=rtpmap:" << map.payloadType << ' ' << map.format << '/' << map.clockRate;
  788. if (!map.encParams.empty())
  789. sdp << '/' << map.encParams;
  790. sdp << eol;
  791. for (const auto &val : map.rtcpFbs)
  792. if (val != "transport-cc")
  793. sdp << "a=rtcp-fb:" << map.payloadType << ' ' << val << eol;
  794. for (const auto &val : map.fmtps)
  795. sdp << "a=fmtp:" << map.payloadType << ' ' << val << eol;
  796. }
  797. return sdp.str();
  798. }
  799. void Description::Media::parseSdpLine(string_view line) {
  800. if (match_prefix(line, "a=")) {
  801. string_view attr = line.substr(2);
  802. auto [key, value] = parse_pair(attr);
  803. if (key == "rtpmap") {
  804. auto pt = Description::Media::RtpMap::parsePayloadType(value);
  805. auto it = mRtpMaps.find(pt);
  806. if (it == mRtpMaps.end())
  807. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(value))).first;
  808. else
  809. it->second.setDescription(value);
  810. } else if (key == "rtcp-fb") {
  811. size_t p = value.find(' ');
  812. int pt = to_integer<int>(value.substr(0, p));
  813. auto it = mRtpMaps.find(pt);
  814. if (it == mRtpMaps.end())
  815. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(pt))).first;
  816. it->second.rtcpFbs.emplace_back(value.substr(p + 1));
  817. } else if (key == "fmtp") {
  818. size_t p = value.find(' ');
  819. int pt = to_integer<int>(value.substr(0, p));
  820. auto it = mRtpMaps.find(pt);
  821. if (it == mRtpMaps.end())
  822. it = mRtpMaps.insert(std::make_pair(pt, Description::Media::RtpMap(pt))).first;
  823. it->second.fmtps.emplace_back(value.substr(p + 1));
  824. } else if (key == "rtcp-mux") {
  825. // always added
  826. } else if (key == "ssrc") {
  827. auto ssrc = to_integer<uint32_t>(value);
  828. if (!hasSSRC(ssrc))
  829. mSsrcs.emplace_back(ssrc);
  830. auto cnamePos = value.find("cname:");
  831. if (cnamePos != string::npos) {
  832. auto cname = value.substr(cnamePos + 6);
  833. mCNameMap.emplace(ssrc, cname);
  834. }
  835. mAttributes.emplace_back(attr);
  836. } else {
  837. Entry::parseSdpLine(line);
  838. }
  839. } else if (match_prefix(line, "b=AS")) {
  840. mBas = to_integer<int>(line.substr(line.find(':') + 1));
  841. } else {
  842. Entry::parseSdpLine(line);
  843. }
  844. }
  845. std::map<int, Description::Media::RtpMap>::iterator Description::Media::beginMaps() {
  846. return mRtpMaps.begin();
  847. }
  848. std::map<int, Description::Media::RtpMap>::iterator Description::Media::endMaps() {
  849. return mRtpMaps.end();
  850. }
  851. std::map<int, Description::Media::RtpMap>::iterator
  852. Description::Media::removeMap(std::map<int, Description::Media::RtpMap>::iterator iterator) {
  853. return mRtpMaps.erase(iterator);
  854. }
  855. Description::Media::RtpMap::RtpMap(int payloadType) {
  856. this->payloadType = payloadType;
  857. this->clockRate = 0;
  858. }
  859. int Description::Media::RtpMap::parsePayloadType(string_view mline) {
  860. size_t p = mline.find(' ');
  861. return to_integer<int>(mline.substr(0, p));
  862. }
  863. Description::Media::RtpMap::RtpMap(string_view description) { setDescription(description); }
  864. void Description::Media::RtpMap::setDescription(string_view description) {
  865. size_t p = description.find(' ');
  866. if (p == string::npos)
  867. throw std::invalid_argument("Invalid format description");
  868. this->payloadType = to_integer<int>(description.substr(0, p));
  869. string_view line = description.substr(p + 1);
  870. size_t spl = line.find('/');
  871. if (spl == string::npos)
  872. throw std::invalid_argument("Invalid format description");
  873. this->format = line.substr(0, spl);
  874. line = line.substr(spl + 1);
  875. spl = line.find('/');
  876. if (spl == string::npos) {
  877. spl = line.find(' ');
  878. }
  879. if (spl == string::npos)
  880. this->clockRate = to_integer<int>(line);
  881. else {
  882. this->clockRate = to_integer<int>(line.substr(0, spl));
  883. this->encParams = line.substr(spl + 1);
  884. }
  885. }
  886. void Description::Media::RtpMap::addFeedback(string fb) {
  887. if (std::find(rtcpFbs.begin(), rtcpFbs.end(), fb) == rtcpFbs.end())
  888. fmtps.emplace_back(std::move(fb));
  889. }
  890. void Description::Media::RtpMap::removeFeedback(const string &str) {
  891. auto it = rtcpFbs.begin();
  892. while (it != rtcpFbs.end()) {
  893. if (it->find(str) != string::npos)
  894. it = rtcpFbs.erase(it);
  895. else
  896. it++;
  897. }
  898. }
  899. void Description::Media::RtpMap::addParameter(string p) {
  900. if (std::find(fmtps.begin(), fmtps.end(), p) == fmtps.end())
  901. fmtps.emplace_back(std::move(p));
  902. }
  903. void Description::Media::RtpMap::removeParameter(const string &str) {
  904. fmtps.erase(std::remove_if(fmtps.begin(), fmtps.end(),
  905. [&](const auto &p) { return p.find(str) != string::npos; }),
  906. fmtps.end());
  907. }
  908. Description::Audio::Audio(string mid, Direction dir)
  909. : Media("audio 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  910. void Description::Audio::addAudioCodec(int payloadType, string codec, optional<string> profile) {
  911. if (codec.find('/') == string::npos)
  912. codec += "/48000/2";
  913. RtpMap map(std::to_string(payloadType) + ' ' + codec);
  914. if (profile)
  915. map.fmtps.emplace_back(*profile);
  916. addRtpMap(map);
  917. }
  918. void Description::Audio::addOpusCodec(int payloadType, optional<string> profile) {
  919. addAudioCodec(payloadType, "OPUS", profile);
  920. }
  921. Description::Video::Video(string mid, Direction dir)
  922. : Media("video 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  923. void Description::Video::addVideoCodec(int payloadType, string codec, optional<string> profile) {
  924. if (codec.find('/') == string::npos)
  925. codec += "/90000";
  926. RtpMap map(std::to_string(payloadType) + ' ' + codec);
  927. map.addFeedback("nack");
  928. map.addFeedback("nack pli");
  929. // map.addFB("ccm fir");
  930. map.addFeedback("goog-remb");
  931. if (profile)
  932. map.fmtps.emplace_back(*profile);
  933. addRtpMap(map);
  934. /* TODO
  935. * TIL that Firefox does not properly support the negotiation of RTX! It works, but doesn't
  936. * negotiate the SSRC so we have no idea what SSRC is RTX going to be. Three solutions: One) we
  937. * don't negotitate it and (maybe) break RTX support with Edge. Two) we do negotiate it and
  938. * rebuild the original packet before we send it distribute it to each track. Three) we complain
  939. * to mozilla. This one probably won't do much.
  940. */
  941. // RTX Packets
  942. // Format rtx(std::to_string(payloadType+1) + " rtx/90000");
  943. // // TODO rtx-time is how long can a request be stashed for before needing to resend it.
  944. // Needs to be parameterized rtx.addAttribute("apt=" + std::to_string(payloadType) +
  945. // ";rtx-time=3000"); addFormat(rtx);
  946. }
  947. void Description::Video::addH264Codec(int pt, optional<string> profile) {
  948. addVideoCodec(pt, "H264", profile);
  949. }
  950. void Description::Video::addVP8Codec(int payloadType) {
  951. addVideoCodec(payloadType, "VP8", nullopt);
  952. }
  953. void Description::Video::addVP9Codec(int payloadType) {
  954. addVideoCodec(payloadType, "VP9", nullopt);
  955. }
  956. Description::Type Description::stringToType(const string &typeString) {
  957. using TypeMap_t = std::unordered_map<string, Type>;
  958. static const TypeMap_t TypeMap = {{"unspec", Type::Unspec},
  959. {"offer", Type::Offer},
  960. {"answer", Type::Answer},
  961. {"pranswer", Type::Pranswer},
  962. {"rollback", Type::Rollback}};
  963. auto it = TypeMap.find(typeString);
  964. return it != TypeMap.end() ? it->second : Type::Unspec;
  965. }
  966. string Description::typeToString(Type type) {
  967. switch (type) {
  968. case Type::Unspec:
  969. return "unspec";
  970. case Type::Offer:
  971. return "offer";
  972. case Type::Answer:
  973. return "answer";
  974. case Type::Pranswer:
  975. return "pranswer";
  976. case Type::Rollback:
  977. return "rollback";
  978. default:
  979. return "unknown";
  980. }
  981. }
  982. } // namespace rtc
  983. std::ostream &operator<<(std::ostream &out, const rtc::Description &description) {
  984. return out << std::string(description);
  985. }
  986. std::ostream &operator<<(std::ostream &out, rtc::Description::Type type) {
  987. return out << rtc::Description::typeToString(type);
  988. }
  989. std::ostream &operator<<(std::ostream &out, rtc::Description::Role role) {
  990. using Role = rtc::Description::Role;
  991. // Used for SDP generation, do not change
  992. switch (role) {
  993. case Role::Active:
  994. out << "active";
  995. break;
  996. case Role::Passive:
  997. out << "passive";
  998. break;
  999. default:
  1000. out << "actpass";
  1001. break;
  1002. }
  1003. return out;
  1004. }