description.cpp 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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 <algorithm>
  22. #include <array>
  23. #include <cctype>
  24. #include <chrono>
  25. #include <iostream>
  26. #include <random>
  27. #include <sstream>
  28. #include <unordered_map>
  29. using std::chrono::system_clock;
  30. namespace {
  31. using std::string;
  32. using std::string_view;
  33. inline bool match_prefix(string_view str, string_view prefix) {
  34. return str.size() >= prefix.size() &&
  35. std::mismatch(prefix.begin(), prefix.end(), str.begin()).first == prefix.end();
  36. }
  37. inline void trim_begin(string &str) {
  38. str.erase(str.begin(),
  39. std::find_if(str.begin(), str.end(), [](char c) { return !std::isspace(c); }));
  40. }
  41. inline void trim_end(string &str) {
  42. str.erase(
  43. std::find_if(str.rbegin(), str.rend(), [](char c) { return !std::isspace(c); }).base(),
  44. str.end());
  45. }
  46. inline std::pair<string_view, string_view> parse_pair(string_view attr) {
  47. string_view key, value;
  48. if (size_t separator = attr.find(':'); separator != string::npos) {
  49. key = attr.substr(0, separator);
  50. value = attr.substr(separator + 1);
  51. } else {
  52. key = attr;
  53. }
  54. return std::make_pair(std::move(key), std::move(value));
  55. }
  56. template <typename T> T to_integer(string_view s) {
  57. const string str(s);
  58. try {
  59. return std::is_signed<T>::value ? T(std::stol(str)) : T(std::stoul(str));
  60. } catch (...) {
  61. throw std::invalid_argument("Invalid integer \"" + str + "\" in description");
  62. }
  63. }
  64. inline bool is_sha256_fingerprint(string_view f) {
  65. if (f.size() != 32 * 3 - 1)
  66. return false;
  67. for (size_t i = 0; i < f.size(); ++i) {
  68. if (i % 3 == 2) {
  69. if (f[i] != ':')
  70. return false;
  71. } else {
  72. if (!std::isxdigit(f[i]))
  73. return false;
  74. }
  75. }
  76. return true;
  77. }
  78. } // namespace
  79. namespace rtc {
  80. Description::Description(const string &sdp, Type type, Role role)
  81. : mType(Type::Unspec), mRole(role) {
  82. hintType(type);
  83. int index = -1;
  84. shared_ptr<Entry> current;
  85. std::istringstream ss(sdp);
  86. while (ss) {
  87. string line;
  88. std::getline(ss, line);
  89. trim_end(line);
  90. if (line.empty())
  91. continue;
  92. if (match_prefix(line, "m=")) { // Media description line (aka m-line)
  93. current = createEntry(line.substr(2), std::to_string(++index), Direction::Unknown);
  94. } else if (match_prefix(line, "o=")) { // Origin line
  95. std::istringstream origin(line.substr(2));
  96. origin >> mUsername >> mSessionId;
  97. } else if (match_prefix(line, "a=")) { // Attribute line
  98. string attr = line.substr(2);
  99. auto [key, value] = parse_pair(attr);
  100. if (key == "setup") {
  101. if (value == "active")
  102. mRole = Role::Active;
  103. else if (value == "passive")
  104. mRole = Role::Passive;
  105. else
  106. mRole = Role::ActPass;
  107. } else if (key == "fingerprint") {
  108. if (match_prefix(value, "sha-256 ")) {
  109. string fingerprint{value.substr(8)};
  110. trim_begin(fingerprint);
  111. setFingerprint(std::move(fingerprint));
  112. } else {
  113. PLOG_WARNING << "Unknown SDP fingerprint format: " << value;
  114. }
  115. } else if (key == "ice-ufrag") {
  116. mIceUfrag = value;
  117. } else if (key == "ice-pwd") {
  118. mIcePwd = value;
  119. } else if (key == "candidate") {
  120. addCandidate(Candidate(attr, bundleMid()));
  121. } else if (key == "end-of-candidates") {
  122. mEnded = true;
  123. } else if (current) {
  124. current->parseSdpLine(std::move(line));
  125. }
  126. } else if (current) {
  127. current->parseSdpLine(std::move(line));
  128. }
  129. }
  130. if (mUsername.empty())
  131. mUsername = "rtc";
  132. if (mSessionId.empty()) {
  133. auto seed = static_cast<unsigned int>(system_clock::now().time_since_epoch().count());
  134. std::default_random_engine generator(seed);
  135. std::uniform_int_distribution<uint32_t> uniform;
  136. mSessionId = std::to_string(uniform(generator));
  137. }
  138. }
  139. Description::Description(const string &sdp, string typeString)
  140. : Description(sdp, !typeString.empty() ? stringToType(typeString) : Type::Unspec,
  141. Role::ActPass) {}
  142. Description::Type Description::type() const { return mType; }
  143. string Description::typeString() const { return typeToString(mType); }
  144. Description::Role Description::role() const { return mRole; }
  145. string Description::bundleMid() const {
  146. // Get the mid of the first media
  147. return !mEntries.empty() ? mEntries[0]->mid() : "0";
  148. }
  149. optional<string> Description::iceUfrag() const { return mIceUfrag; }
  150. optional<string> Description::icePwd() const { return mIcePwd; }
  151. optional<string> Description::fingerprint() const { return mFingerprint; }
  152. bool Description::ended() const { return mEnded; }
  153. void Description::hintType(Type type) {
  154. if (mType == Type::Unspec) {
  155. mType = type;
  156. if (mType == Type::Answer && mRole == Role::ActPass)
  157. mRole = Role::Passive; // ActPass is illegal for an answer, so default to passive
  158. }
  159. }
  160. void Description::setFingerprint(string fingerprint) {
  161. if (!is_sha256_fingerprint(fingerprint))
  162. throw std::invalid_argument("Invalid SHA256 fingerprint \"" + fingerprint + "\"");
  163. std::transform(fingerprint.begin(), fingerprint.end(), fingerprint.begin(),
  164. [](char c) { return char(std::toupper(c)); });
  165. mFingerprint.emplace(std::move(fingerprint));
  166. }
  167. bool Description::hasCandidate(const Candidate &candidate) const {
  168. for (const Candidate &other : mCandidates)
  169. if (candidate == other)
  170. return true;
  171. return false;
  172. }
  173. void Description::addCandidate(Candidate candidate) {
  174. candidate.hintMid(bundleMid());
  175. for (const Candidate &other : mCandidates)
  176. if (candidate == other)
  177. return;
  178. mCandidates.emplace_back(std::move(candidate));
  179. }
  180. void Description::addCandidates(std::vector<Candidate> candidates) {
  181. for (Candidate candidate : candidates)
  182. addCandidate(std::move(candidate));
  183. }
  184. void Description::endCandidates() { mEnded = true; }
  185. std::vector<Candidate> Description::extractCandidates() {
  186. std::vector<Candidate> result;
  187. std::swap(mCandidates, result);
  188. mEnded = false;
  189. return result;
  190. }
  191. Description::operator string() const { return generateSdp("\r\n"); }
  192. string Description::generateSdp(string_view eol) const {
  193. std::ostringstream sdp;
  194. // Header
  195. sdp << "v=0" << eol;
  196. sdp << "o=" << mUsername << " " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
  197. sdp << "s=-" << eol;
  198. sdp << "t=0 0" << eol;
  199. // Bundle (RFC8843 Negotiating Media Multiplexing Using the Session Description Protocol)
  200. // https://tools.ietf.org/html/rfc8843
  201. sdp << "a=group:BUNDLE";
  202. for (const auto &entry : mEntries)
  203. sdp << ' ' << entry->mid();
  204. sdp << eol;
  205. // Lip-sync
  206. std::ostringstream lsGroup;
  207. for (const auto &entry : mEntries)
  208. if (entry != mApplication)
  209. lsGroup << ' ' << entry->mid();
  210. if (!lsGroup.str().empty())
  211. sdp << "a=group:LS" << lsGroup.str() << eol;
  212. // Session-level attributes
  213. sdp << "a=msid-semantic:WMS *" << eol;
  214. sdp << "a=setup:" << mRole << eol;
  215. if (mIceUfrag)
  216. sdp << "a=ice-ufrag:" << *mIceUfrag << eol;
  217. if (mIcePwd)
  218. sdp << "a=ice-pwd:" << *mIcePwd << eol;
  219. if (!mEnded)
  220. sdp << "a=ice-options:trickle" << eol;
  221. if (mFingerprint)
  222. sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
  223. auto cand = defaultCandidate();
  224. const string addr = cand && cand->isResolved()
  225. ? (string(cand->family() == Candidate::Family::Ipv6 ? "IP6" : "IP4") +
  226. " " + *cand->address())
  227. : "IP4 0.0.0.0";
  228. const string port = std::to_string(
  229. cand && cand->isResolved() ? *cand->port() : 9); // Port 9 is the discard protocol
  230. // Entries
  231. bool first = true;
  232. for (const auto &entry : mEntries) {
  233. sdp << entry->generateSdp(eol, addr, port);
  234. if (std::exchange(first, false)) {
  235. // Candidates
  236. for (const auto &candidate : mCandidates)
  237. sdp << string(candidate) << eol;
  238. if (mEnded)
  239. sdp << "a=end-of-candidates" << eol;
  240. }
  241. }
  242. return sdp.str();
  243. }
  244. string Description::generateApplicationSdp(string_view eol) const {
  245. std::ostringstream sdp;
  246. // Header
  247. sdp << "v=0" << eol;
  248. sdp << "o=" << mUsername << " " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
  249. sdp << "s=-" << eol;
  250. sdp << "t=0 0" << eol;
  251. auto cand = defaultCandidate();
  252. const string addr = cand && cand->isResolved()
  253. ? (string(cand->family() == Candidate::Family::Ipv6 ? "IP6" : "IP4") +
  254. " " + *cand->address())
  255. : "IP4 0.0.0.0";
  256. const string port = std::to_string(
  257. cand && cand->isResolved() ? *cand->port() : 9); // Port 9 is the discard protocol
  258. // Application
  259. auto app = mApplication ? mApplication : std::make_shared<Application>();
  260. sdp << app->generateSdp(eol, addr, port);
  261. // Session-level attributes
  262. sdp << "a=msid-semantic:WMS *" << eol;
  263. sdp << "a=setup:" << mRole << eol;
  264. if (mIceUfrag)
  265. sdp << "a=ice-ufrag:" << *mIceUfrag << eol;
  266. if (mIcePwd)
  267. sdp << "a=ice-pwd:" << *mIcePwd << eol;
  268. if (!mEnded)
  269. sdp << "a=ice-options:trickle" << eol;
  270. if (mFingerprint)
  271. sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
  272. // Candidates
  273. for (const auto &candidate : mCandidates)
  274. sdp << string(candidate) << eol;
  275. if (mEnded)
  276. sdp << "a=end-of-candidates" << eol;
  277. return sdp.str();
  278. }
  279. optional<Candidate> Description::defaultCandidate() const {
  280. // Return the first host candidate with highest priority, favoring IPv4
  281. optional<Candidate> result;
  282. for (const auto &c : mCandidates) {
  283. if (c.type() == Candidate::Type::Host) {
  284. if (!result ||
  285. (result->family() == Candidate::Family::Ipv6 &&
  286. c.family() == Candidate::Family::Ipv4) ||
  287. (result->family() == c.family() && result->priority() < c.priority()))
  288. result.emplace(c);
  289. }
  290. }
  291. return result;
  292. }
  293. shared_ptr<Description::Entry> Description::createEntry(string mline, string mid, Direction dir) {
  294. string type = mline.substr(0, mline.find(' '));
  295. if (type == "application") {
  296. removeApplication();
  297. mApplication = std::make_shared<Application>(std::move(mid));
  298. mEntries.emplace_back(mApplication);
  299. return mApplication;
  300. } else {
  301. auto media = std::make_shared<Media>(std::move(mline), std::move(mid), dir);
  302. mEntries.emplace_back(media);
  303. return media;
  304. }
  305. }
  306. void Description::removeApplication() {
  307. if (!mApplication)
  308. return;
  309. auto it = std::find(mEntries.begin(), mEntries.end(), mApplication);
  310. if (it != mEntries.end())
  311. mEntries.erase(it);
  312. mApplication.reset();
  313. }
  314. bool Description::hasApplication() const { return mApplication != nullptr; }
  315. bool Description::hasAudioOrVideo() const {
  316. for (auto entry : mEntries)
  317. if (entry != mApplication)
  318. return true;
  319. return false;
  320. }
  321. bool Description::hasMid(string_view mid) const {
  322. for (const auto &entry : mEntries)
  323. if (entry->mid() == mid)
  324. return true;
  325. return false;
  326. }
  327. int Description::addMedia(Media media) {
  328. mEntries.emplace_back(std::make_shared<Media>(std::move(media)));
  329. return int(mEntries.size()) - 1;
  330. }
  331. int Description::addMedia(Application application) {
  332. removeApplication();
  333. mApplication = std::make_shared<Application>(std::move(application));
  334. mEntries.emplace_back(mApplication);
  335. return int(mEntries.size()) - 1;
  336. }
  337. int Description::addApplication(string mid) { return addMedia(Application(std::move(mid))); }
  338. const Description::Application *Description::application() const { return mApplication.get(); }
  339. Description::Application *Description::application() { return mApplication.get(); }
  340. int Description::addVideo(string mid, Direction dir) {
  341. return addMedia(Video(std::move(mid), dir));
  342. }
  343. int Description::addAudio(string mid, Direction dir) {
  344. return addMedia(Audio(std::move(mid), dir));
  345. }
  346. void Description::clearMedia() {
  347. mEntries.clear();
  348. mApplication.reset();
  349. }
  350. variant<Description::Media *, Description::Application *> Description::media(unsigned int index) {
  351. if (index >= mEntries.size())
  352. throw std::out_of_range("Media index out of range");
  353. const auto &entry = mEntries[index];
  354. if (entry == mApplication) {
  355. auto result = dynamic_cast<Application *>(entry.get());
  356. if (!result)
  357. throw std::logic_error("Bad type of application in description");
  358. return result;
  359. } else {
  360. auto result = dynamic_cast<Media *>(entry.get());
  361. if (!result)
  362. throw std::logic_error("Bad type of media in description");
  363. return result;
  364. }
  365. }
  366. variant<const Description::Media *, const Description::Application *>
  367. Description::media(unsigned int index) const {
  368. if (index >= mEntries.size())
  369. throw std::out_of_range("Media index out of range");
  370. const auto &entry = mEntries[index];
  371. if (entry == mApplication) {
  372. auto result = dynamic_cast<Application *>(entry.get());
  373. if (!result)
  374. throw std::logic_error("Bad type of application in description");
  375. return result;
  376. } else {
  377. auto result = dynamic_cast<Media *>(entry.get());
  378. if (!result)
  379. throw std::logic_error("Bad type of media in description");
  380. return result;
  381. }
  382. }
  383. unsigned int Description::mediaCount() const { return unsigned(mEntries.size()); }
  384. Description::Entry::Entry(const string &mline, string mid, Direction dir)
  385. : mMid(std::move(mid)), mDirection(dir) {
  386. unsigned int port;
  387. std::istringstream ss(mline);
  388. ss >> mType;
  389. ss >> port; // ignored
  390. ss >> mDescription;
  391. }
  392. void Description::Entry::setDirection(Direction dir) { mDirection = dir; }
  393. Description::Entry::operator string() const { return generateSdp("\r\n", "IP4 0.0.0.0", "9"); }
  394. string Description::Entry::generateSdp(string_view eol, string_view addr, string_view port) const {
  395. std::ostringstream sdp;
  396. sdp << "m=" << type() << ' ' << port << ' ' << description() << eol;
  397. sdp << "c=IN " << addr << eol;
  398. sdp << generateSdpLines(eol);
  399. return sdp.str();
  400. }
  401. string Description::Entry::generateSdpLines(string_view eol) const {
  402. std::ostringstream sdp;
  403. sdp << "a=bundle-only" << eol;
  404. sdp << "a=mid:" << mMid << eol;
  405. switch (mDirection) {
  406. case Direction::SendOnly:
  407. sdp << "a=sendonly" << eol;
  408. break;
  409. case Direction::RecvOnly:
  410. sdp << "a=recvonly" << eol;
  411. break;
  412. case Direction::SendRecv:
  413. sdp << "a=sendrecv" << eol;
  414. break;
  415. case Direction::Inactive:
  416. sdp << "a=inactive" << eol;
  417. break;
  418. default:
  419. // Ignore
  420. break;
  421. }
  422. for (const auto &attr : mAttributes) {
  423. if (attr.find("extmap") == string::npos && attr.find("rtcp-rsize") == string::npos)
  424. sdp << "a=" << attr << eol;
  425. }
  426. return sdp.str();
  427. }
  428. void Description::Entry::parseSdpLine(string_view line) {
  429. if (match_prefix(line, "a=")) {
  430. string_view attr = line.substr(2);
  431. auto [key, value] = parse_pair(attr);
  432. if (key == "mid")
  433. mMid = value;
  434. else if (attr == "sendonly")
  435. mDirection = Direction::SendOnly;
  436. else if (attr == "recvonly")
  437. mDirection = Direction::RecvOnly;
  438. else if (key == "sendrecv")
  439. mDirection = Direction::SendRecv;
  440. else if (key == "inactive")
  441. mDirection = Direction::Inactive;
  442. else if (key == "bundle-only") {
  443. // always added
  444. } else
  445. mAttributes.emplace_back(line.substr(2));
  446. }
  447. }
  448. std::vector<string>::iterator Description::Entry::beginAttributes() { return mAttributes.begin(); }
  449. std::vector<string>::iterator Description::Entry::endAttributes() { return mAttributes.end(); }
  450. std::vector<string>::iterator
  451. Description::Entry::removeAttribute(std::vector<string>::iterator it) {
  452. return mAttributes.erase(it);
  453. }
  454. void Description::Media::addSSRC(uint32_t ssrc, optional<string> name, optional<string> msid,
  455. optional<string> trackID) {
  456. if (name)
  457. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " cname:" + *name);
  458. else
  459. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc));
  460. if (msid)
  461. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " msid:" + *msid + " " +
  462. trackID.value_or(*msid));
  463. mSsrcs.emplace_back(ssrc);
  464. }
  465. void Description::Media::replaceSSRC(uint32_t oldSSRC, uint32_t ssrc, optional<string> name,
  466. optional<string> msid, optional<string> trackID) {
  467. auto it = mAttributes.begin();
  468. while (it != mAttributes.end()) {
  469. if (it->find("ssrc:" + std::to_string(oldSSRC)) == 0) {
  470. it = mAttributes.erase(it);
  471. } else
  472. it++;
  473. }
  474. addSSRC(ssrc, std::move(name), std::move(msid), std::move(trackID));
  475. }
  476. void Description::Media::removeSSRC(uint32_t oldSSRC) {
  477. auto it = mAttributes.begin();
  478. while (it != mAttributes.end()) {
  479. if (it->find("ssrc:" + std::to_string(oldSSRC)) == 0) {
  480. it = mAttributes.erase(it);
  481. } else
  482. it++;
  483. }
  484. }
  485. bool Description::Media::hasSSRC(uint32_t ssrc) {
  486. return std::find(mSsrcs.begin(), mSsrcs.end(), ssrc) != mSsrcs.end();
  487. }
  488. Description::Application::Application(string mid)
  489. : Entry("application 9 UDP/DTLS/SCTP", std::move(mid), Direction::SendRecv) {}
  490. string Description::Application::description() const {
  491. return Entry::description() + " webrtc-datachannel";
  492. }
  493. Description::Application Description::Application::reciprocate() const {
  494. Application reciprocated(*this);
  495. reciprocated.mMaxMessageSize.reset();
  496. return reciprocated;
  497. }
  498. string Description::Application::generateSdpLines(string_view eol) const {
  499. std::ostringstream sdp;
  500. sdp << Entry::generateSdpLines(eol);
  501. if (mSctpPort)
  502. sdp << "a=sctp-port:" << *mSctpPort << eol;
  503. if (mMaxMessageSize)
  504. sdp << "a=max-message-size:" << *mMaxMessageSize << eol;
  505. return sdp.str();
  506. }
  507. void Description::Application::parseSdpLine(string_view line) {
  508. if (match_prefix(line, "a=")) {
  509. string_view attr = line.substr(2);
  510. auto [key, value] = parse_pair(attr);
  511. if (key == "sctp-port") {
  512. mSctpPort = to_integer<uint16_t>(value);
  513. } else if (key == "max-message-size") {
  514. mMaxMessageSize = to_integer<size_t>(value);
  515. } else {
  516. Entry::parseSdpLine(line);
  517. }
  518. } else {
  519. Entry::parseSdpLine(line);
  520. }
  521. }
  522. Description::Media::Media(const string &sdp) : Entry(sdp, "", Direction::Unknown) {
  523. std::istringstream ss(sdp);
  524. while (ss) {
  525. string line;
  526. std::getline(ss, line);
  527. trim_end(line);
  528. if (line.empty())
  529. continue;
  530. parseSdpLine(line);
  531. }
  532. if (mid().empty())
  533. throw std::invalid_argument("Missing mid in media SDP");
  534. }
  535. Description::Media::Media(const string &mline, string mid, Direction dir)
  536. : Entry(mline, std::move(mid), dir) {}
  537. string Description::Media::description() const {
  538. std::ostringstream desc;
  539. desc << Entry::description();
  540. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it)
  541. desc << ' ' << it->first;
  542. return desc.str();
  543. }
  544. Description::Media Description::Media::reciprocate() const {
  545. Media reciprocated(*this);
  546. // Invert direction
  547. switch (direction()) {
  548. case Direction::RecvOnly:
  549. reciprocated.setDirection(Direction::SendOnly);
  550. break;
  551. case Direction::SendOnly:
  552. reciprocated.setDirection(Direction::RecvOnly);
  553. break;
  554. default:
  555. // We are good
  556. break;
  557. }
  558. return reciprocated;
  559. }
  560. Description::Media::RTPMap &Description::Media::getFormat(int fmt) {
  561. auto it = mRtpMap.find(fmt);
  562. if (it != mRtpMap.end())
  563. return it->second;
  564. throw std::invalid_argument("m-line index is out of bounds");
  565. }
  566. Description::Media::RTPMap &Description::Media::getFormat(const string &fmt) {
  567. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it)
  568. if (it->second.format == fmt)
  569. return it->second;
  570. throw std::invalid_argument("format was not found");
  571. }
  572. void Description::Media::removeFormat(const string &fmt) {
  573. auto it = mRtpMap.begin();
  574. std::vector<int> remed;
  575. // Remove the actual formats
  576. while (it != mRtpMap.end()) {
  577. if (it->second.format == fmt) {
  578. remed.emplace_back(it->first);
  579. it = mRtpMap.erase(it);
  580. } else {
  581. it++;
  582. }
  583. }
  584. // Remove any other rtpmaps that depend on the formats we just removed
  585. it = mRtpMap.begin();
  586. while (it != mRtpMap.end()) {
  587. auto it2 = it->second.fmtps.begin();
  588. bool rem = false;
  589. while (it2 != it->second.fmtps.end()) {
  590. if (it2->find("apt=") == 0) {
  591. for (auto remid : remed) {
  592. if (it2->find(std::to_string(remid)) != string::npos) {
  593. std::cout << *it2 << ' ' << remid << std::endl;
  594. it = mRtpMap.erase(it);
  595. rem = true;
  596. break;
  597. }
  598. }
  599. break;
  600. }
  601. it2++;
  602. }
  603. if (!rem)
  604. it++;
  605. }
  606. }
  607. void Description::Video::addVideoCodec(int payloadType, string codec, optional<string> profile) {
  608. RTPMap map(std::to_string(payloadType) + ' ' + codec + "/90000");
  609. map.addFB("nack");
  610. map.addFB("nack pli");
  611. // map.addFB("ccm fir");
  612. map.addFB("goog-remb");
  613. if (profile)
  614. map.fmtps.emplace_back(*profile);
  615. addRTPMap(map);
  616. /* TODO
  617. * TIL that Firefox does not properly support the negotiation of RTX! It works, but doesn't
  618. * negotiate the SSRC so we have no idea what SSRC is RTX going to be. Three solutions: One) we
  619. * don't negotitate it and (maybe) break RTX support with Edge. Two) we do negotiate it and
  620. * rebuild the original packet before we send it distribute it to each track. Three) we complain
  621. * to mozilla. This one probably won't do much.
  622. */
  623. // RTX Packets
  624. // RTPMap rtx(std::to_string(payloadType+1) + " rtx/90000");
  625. // // TODO rtx-time is how long can a request be stashed for before needing to resend it.
  626. // Needs to be parameterized rtx.addAttribute("apt=" + std::to_string(payloadType) +
  627. // ";rtx-time=3000"); addRTPMap(rtx);
  628. }
  629. void Description::Audio::addAudioCodec(int payloadType, string codec, optional<string> profile) {
  630. // TODO This 48000/2 should be parameterized
  631. RTPMap map(std::to_string(payloadType) + ' ' + codec + "/48000/2");
  632. if (profile)
  633. map.fmtps.emplace_back(*profile);
  634. addRTPMap(map);
  635. }
  636. void Description::Media::addRTXCodec(unsigned int payloadType, unsigned int originalPayloadType,
  637. unsigned int clockRate) {
  638. RTPMap map(std::to_string(payloadType) + " RTX/" + std::to_string(clockRate));
  639. map.fmtps.emplace_back("apt=" + std::to_string(originalPayloadType));
  640. addRTPMap(map);
  641. }
  642. void Description::Video::addH264Codec(int pt, optional<string> profile) {
  643. addVideoCodec(pt, "H264", profile);
  644. }
  645. void Description::Video::addVP8Codec(int payloadType) {
  646. addVideoCodec(payloadType, "VP8", nullopt);
  647. }
  648. void Description::Video::addVP9Codec(int payloadType) {
  649. addVideoCodec(payloadType, "VP9", nullopt);
  650. }
  651. void Description::Media::setBitrate(int bitrate) { mBas = bitrate; }
  652. int Description::Media::getBitrate() const { return mBas; }
  653. bool Description::Media::hasPayloadType(int payloadType) const {
  654. return mRtpMap.find(payloadType) != mRtpMap.end();
  655. }
  656. string Description::Media::generateSdpLines(string_view eol) const {
  657. std::ostringstream sdp;
  658. if (mBas >= 0)
  659. sdp << "b=AS:" << mBas << eol;
  660. sdp << Entry::generateSdpLines(eol);
  661. sdp << "a=rtcp-mux" << eol;
  662. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it) {
  663. auto &map = it->second;
  664. // Create the a=rtpmap
  665. sdp << "a=rtpmap:" << map.pt << ' ' << map.format << '/' << map.clockRate;
  666. if (!map.encParams.empty())
  667. sdp << '/' << map.encParams;
  668. sdp << eol;
  669. for (const auto &val : map.rtcpFbs) {
  670. if (val != "transport-cc")
  671. sdp << "a=rtcp-fb:" << map.pt << ' ' << val << eol;
  672. }
  673. for (const auto &val : map.fmtps)
  674. sdp << "a=fmtp:" << map.pt << ' ' << val << eol;
  675. }
  676. return sdp.str();
  677. }
  678. void Description::Media::parseSdpLine(string_view line) {
  679. if (match_prefix(line, "a=")) {
  680. string_view attr = line.substr(2);
  681. auto [key, value] = parse_pair(attr);
  682. if (key == "rtpmap") {
  683. auto pt = Description::Media::RTPMap::parsePT(value);
  684. auto it = mRtpMap.find(pt);
  685. if (it == mRtpMap.end()) {
  686. it = mRtpMap.insert(std::make_pair(pt, Description::Media::RTPMap(value))).first;
  687. } else {
  688. it->second.setMLine(value);
  689. }
  690. } else if (key == "rtcp-fb") {
  691. size_t p = value.find(' ');
  692. int pt = to_integer<int>(value.substr(0, p));
  693. auto it = mRtpMap.find(pt);
  694. if (it == mRtpMap.end()) {
  695. it = mRtpMap.insert(std::make_pair(pt, Description::Media::RTPMap())).first;
  696. }
  697. it->second.rtcpFbs.emplace_back(value.substr(p + 1));
  698. } else if (key == "fmtp") {
  699. size_t p = value.find(' ');
  700. int pt = to_integer<int>(value.substr(0, p));
  701. auto it = mRtpMap.find(pt);
  702. if (it == mRtpMap.end())
  703. it = mRtpMap.insert(std::make_pair(pt, Description::Media::RTPMap())).first;
  704. it->second.fmtps.emplace_back(value.substr(p + 1));
  705. } else if (key == "rtcp-mux") {
  706. // always added
  707. } else if (key == "ssrc") {
  708. auto ssrc = to_integer<uint32_t>(value);
  709. if (!hasSSRC(ssrc)) {
  710. mSsrcs.emplace_back(ssrc);
  711. }
  712. mAttributes.emplace_back(attr);
  713. } else {
  714. Entry::parseSdpLine(line);
  715. }
  716. } else if (match_prefix(line, "b=AS")) {
  717. mBas = to_integer<int>(line.substr(line.find(':') + 1));
  718. } else {
  719. Entry::parseSdpLine(line);
  720. }
  721. }
  722. void Description::Media::addRTPMap(const Description::Media::RTPMap &map) {
  723. mRtpMap.emplace(map.pt, map);
  724. }
  725. std::vector<uint32_t> Description::Media::getSSRCs() { return mSsrcs; }
  726. std::optional<std::string> Description::Media::getCNameForSsrc(uint32_t ssrc) {
  727. for (auto &val : mAttributes) {
  728. if (val.find("ssrc:") == 0 && val.find("cname:") != std::string::npos) {
  729. return val.substr(val.find("cname:") + 6);
  730. }
  731. }
  732. return std::nullopt;
  733. }
  734. std::map<int, Description::Media::RTPMap>::iterator Description::Media::beginMaps() {
  735. return mRtpMap.begin();
  736. }
  737. std::map<int, Description::Media::RTPMap>::iterator Description::Media::endMaps() {
  738. return mRtpMap.end();
  739. }
  740. std::map<int, Description::Media::RTPMap>::iterator
  741. Description::Media::removeMap(std::map<int, Description::Media::RTPMap>::iterator iterator) {
  742. return mRtpMap.erase(iterator);
  743. }
  744. Description::Media::RTPMap::RTPMap(string_view mline) { setMLine(mline); }
  745. void Description::Media::RTPMap::removeFB(const string &str) {
  746. auto it = rtcpFbs.begin();
  747. while (it != rtcpFbs.end()) {
  748. if (it->find(str) != string::npos) {
  749. it = rtcpFbs.erase(it);
  750. } else
  751. it++;
  752. }
  753. }
  754. void Description::Media::RTPMap::addFB(const string &str) { rtcpFbs.emplace_back(str); }
  755. int Description::Media::RTPMap::parsePT(string_view view) {
  756. size_t p = view.find(' ');
  757. return to_integer<int>(view.substr(0, p));
  758. }
  759. void Description::Media::RTPMap::setMLine(string_view mline) {
  760. size_t p = mline.find(' ');
  761. this->pt = to_integer<int>(mline.substr(0, p));
  762. string_view line = mline.substr(p + 1);
  763. size_t spl = line.find('/');
  764. this->format = line.substr(0, spl);
  765. line = line.substr(spl + 1);
  766. spl = line.find('/');
  767. if (spl == string::npos) {
  768. spl = line.find(' ');
  769. }
  770. if (spl == string::npos)
  771. this->clockRate = to_integer<int>(line);
  772. else {
  773. this->clockRate = to_integer<int>(line.substr(0, spl));
  774. this->encParams = line.substr(spl + 1);
  775. }
  776. }
  777. Description::Audio::Audio(string mid, Direction dir)
  778. : Media("audio 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  779. void Description::Audio::addOpusCodec(int payloadType, optional<string> profile) {
  780. addAudioCodec(payloadType, "OPUS", profile);
  781. }
  782. Description::Video::Video(string mid, Direction dir)
  783. : Media("video 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  784. Description::Type Description::stringToType(const string &typeString) {
  785. using TypeMap_t = std::unordered_map<string, Type>;
  786. static const TypeMap_t TypeMap = {{"unspec", Type::Unspec},
  787. {"offer", Type::Offer},
  788. {"answer", Type::Answer},
  789. {"pranswer", Type::Pranswer},
  790. {"rollback", Type::Rollback}};
  791. auto it = TypeMap.find(typeString);
  792. return it != TypeMap.end() ? it->second : Type::Unspec;
  793. }
  794. string Description::typeToString(Type type) {
  795. switch (type) {
  796. case Type::Unspec:
  797. return "unspec";
  798. case Type::Offer:
  799. return "offer";
  800. case Type::Answer:
  801. return "answer";
  802. case Type::Pranswer:
  803. return "pranswer";
  804. case Type::Rollback:
  805. return "rollback";
  806. default:
  807. return "unknown";
  808. }
  809. }
  810. } // namespace rtc
  811. std::ostream &operator<<(std::ostream &out, const rtc::Description &description) {
  812. return out << std::string(description);
  813. }
  814. std::ostream &operator<<(std::ostream &out, rtc::Description::Type type) {
  815. return out << rtc::Description::typeToString(type);
  816. }
  817. std::ostream &operator<<(std::ostream &out, rtc::Description::Role role) {
  818. using Role = rtc::Description::Role;
  819. // Used for SDP generation, do not change
  820. switch (role) {
  821. case Role::Active:
  822. out << "active";
  823. break;
  824. case Role::Passive:
  825. out << "passive";
  826. break;
  827. default:
  828. out << "actpass";
  829. break;
  830. }
  831. return out;
  832. }