description.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. for (auto it = mExtMap.begin(); it != mExtMap.end(); ++it) {
  406. auto &map = it->second;
  407. sdp << "a=extmap:" << map.id;
  408. switch (map.direction) {
  409. case Direction::SendOnly:
  410. sdp << "/sendonly";
  411. break;
  412. case Direction::RecvOnly:
  413. sdp << "/recvonly";
  414. break;
  415. case Direction::SendRecv:
  416. sdp << "/sendrecv";
  417. break;
  418. case Direction::Inactive:
  419. sdp << "/inactive";
  420. break;
  421. default:
  422. // Ignore
  423. break;
  424. }
  425. sdp << ' ' << map.uri;
  426. if (!map.attributes.empty())
  427. sdp << ' ' << map.attributes;
  428. sdp << eol;
  429. }
  430. switch (mDirection) {
  431. case Direction::SendOnly:
  432. sdp << "a=sendonly" << eol;
  433. break;
  434. case Direction::RecvOnly:
  435. sdp << "a=recvonly" << eol;
  436. break;
  437. case Direction::SendRecv:
  438. sdp << "a=sendrecv" << eol;
  439. break;
  440. case Direction::Inactive:
  441. sdp << "a=inactive" << eol;
  442. break;
  443. default:
  444. // Ignore
  445. break;
  446. }
  447. for (const auto &attr : mAttributes) {
  448. if (attr.find("extmap") == string::npos && attr.find("rtcp-rsize") == string::npos)
  449. sdp << "a=" << attr << eol;
  450. }
  451. return sdp.str();
  452. }
  453. void Description::Entry::parseSdpLine(string_view line) {
  454. if (match_prefix(line, "a=")) {
  455. string_view attr = line.substr(2);
  456. auto [key, value] = parse_pair(attr);
  457. if (key == "mid")
  458. mMid = value;
  459. else if (key == "extmap") {
  460. auto id = Description::Media::ExtMap::parseId(value);
  461. auto it = mExtMap.find(id);
  462. if (it == mExtMap.end()) {
  463. it = mExtMap.insert(std::make_pair(id, Description::Media::ExtMap(value))).first;
  464. } else {
  465. it->second.setDescription(value);
  466. }
  467. } else if (attr == "sendonly")
  468. mDirection = Direction::SendOnly;
  469. else if (attr == "recvonly")
  470. mDirection = Direction::RecvOnly;
  471. else if (key == "sendrecv")
  472. mDirection = Direction::SendRecv;
  473. else if (key == "inactive")
  474. mDirection = Direction::Inactive;
  475. else if (key == "bundle-only") {
  476. // always added
  477. } else
  478. mAttributes.emplace_back(line.substr(2));
  479. }
  480. }
  481. std::vector<string>::iterator Description::Entry::beginAttributes() { return mAttributes.begin(); }
  482. std::vector<string>::iterator Description::Entry::endAttributes() { return mAttributes.end(); }
  483. std::vector<string>::iterator
  484. Description::Entry::removeAttribute(std::vector<string>::iterator it) {
  485. return mAttributes.erase(it);
  486. }
  487. void Description::Entry::addExtMap(const Description::Entry::ExtMap &map) {
  488. mExtMap.emplace(map.id, map);
  489. }
  490. std::map<int, Description::Entry::ExtMap>::iterator Description::Entry::beginExtMaps() {
  491. return mExtMap.begin();
  492. }
  493. std::map<int, Description::Entry::ExtMap>::iterator Description::Entry::endExtMaps() {
  494. return mExtMap.end();
  495. }
  496. std::map<int, Description::Entry::ExtMap>::iterator
  497. Description::Entry::removeExtMap(std::map<int, Description::Entry::ExtMap>::iterator iterator) {
  498. return mExtMap.erase(iterator);
  499. }
  500. Description::Entry::ExtMap::ExtMap(string_view description) { setDescription(description); }
  501. int Description::Entry::ExtMap::parseId(string_view view) {
  502. size_t p = view.find(' ');
  503. return to_integer<int>(view.substr(0, p));
  504. }
  505. void Description::Entry::ExtMap::setDescription(string_view description) {
  506. const size_t uriStart = description.find(' ');
  507. if (uriStart == string::npos)
  508. throw std::invalid_argument("Invalid description");
  509. const string_view idAndDirection = description.substr(0, uriStart);
  510. const size_t idSplit = idAndDirection.find('/');
  511. if (idSplit == string::npos) {
  512. this->id = to_integer<int>(idAndDirection);
  513. } else {
  514. this->id = to_integer<int>(idAndDirection.substr(0, idSplit));
  515. const string_view directionStr = idAndDirection.substr(idSplit + 1);
  516. if (directionStr == "sendonly")
  517. this->direction = Direction::SendOnly;
  518. else if (directionStr == "recvonly")
  519. this->direction = Direction::RecvOnly;
  520. else if (directionStr == "sendrecv")
  521. this->direction = Direction::SendRecv;
  522. else if (directionStr == "inactive")
  523. this->direction = Direction::Inactive;
  524. else
  525. throw std::invalid_argument("Invalid direction");
  526. }
  527. const string_view uriAndAttributes = description.substr(uriStart + 1);
  528. const size_t attributeSplit = uriAndAttributes.find(' ');
  529. if (attributeSplit == string::npos)
  530. this->uri = uriAndAttributes;
  531. else {
  532. this->uri = uriAndAttributes.substr(0, attributeSplit);
  533. this->attributes = uriAndAttributes.substr(attributeSplit + 1);
  534. }
  535. }
  536. void Description::Media::addSSRC(uint32_t ssrc, optional<string> name, optional<string> msid,
  537. optional<string> trackID) {
  538. if (name) {
  539. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " cname:" + *name);
  540. mCNameMap.emplace(ssrc, *name);
  541. } else {
  542. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc));
  543. }
  544. if (msid)
  545. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " msid:" + *msid + " " +
  546. trackID.value_or(*msid));
  547. mSsrcs.emplace_back(ssrc);
  548. }
  549. void Description::Media::removeSSRC(uint32_t oldSSRC) {
  550. auto it = mAttributes.begin();
  551. while (it != mAttributes.end()) {
  552. if (match_prefix(*it, "ssrc:" + std::to_string(oldSSRC)))
  553. it = mAttributes.erase(it);
  554. else
  555. ++it;
  556. }
  557. auto jt = mSsrcs.begin();
  558. while (jt != mSsrcs.end()) {
  559. if (*jt == oldSSRC)
  560. jt = mSsrcs.erase(jt);
  561. else
  562. ++jt;
  563. }
  564. }
  565. void Description::Media::replaceSSRC(uint32_t oldSSRC, uint32_t ssrc, optional<string> name,
  566. optional<string> msid, optional<string> trackID) {
  567. removeSSRC(oldSSRC);
  568. addSSRC(ssrc, std::move(name), std::move(msid), std::move(trackID));
  569. }
  570. bool Description::Media::hasSSRC(uint32_t ssrc) {
  571. return std::find(mSsrcs.begin(), mSsrcs.end(), ssrc) != mSsrcs.end();
  572. }
  573. Description::Application::Application(string mid)
  574. : Entry("application 9 UDP/DTLS/SCTP", std::move(mid), Direction::SendRecv) {}
  575. string Description::Application::description() const {
  576. return Entry::description() + " webrtc-datachannel";
  577. }
  578. Description::Application Description::Application::reciprocate() const {
  579. Application reciprocated(*this);
  580. reciprocated.mMaxMessageSize.reset();
  581. return reciprocated;
  582. }
  583. string Description::Application::generateSdpLines(string_view eol) const {
  584. std::ostringstream sdp;
  585. sdp << Entry::generateSdpLines(eol);
  586. if (mSctpPort)
  587. sdp << "a=sctp-port:" << *mSctpPort << eol;
  588. if (mMaxMessageSize)
  589. sdp << "a=max-message-size:" << *mMaxMessageSize << eol;
  590. return sdp.str();
  591. }
  592. void Description::Application::parseSdpLine(string_view line) {
  593. if (match_prefix(line, "a=")) {
  594. string_view attr = line.substr(2);
  595. auto [key, value] = parse_pair(attr);
  596. if (key == "sctp-port") {
  597. mSctpPort = to_integer<uint16_t>(value);
  598. } else if (key == "max-message-size") {
  599. mMaxMessageSize = to_integer<size_t>(value);
  600. } else {
  601. Entry::parseSdpLine(line);
  602. }
  603. } else {
  604. Entry::parseSdpLine(line);
  605. }
  606. }
  607. Description::Media::Media(const string &sdp) : Entry(sdp, "", Direction::Unknown) {
  608. std::istringstream ss(sdp);
  609. while (ss) {
  610. string line;
  611. std::getline(ss, line);
  612. trim_end(line);
  613. if (line.empty())
  614. continue;
  615. parseSdpLine(line);
  616. }
  617. if (mid().empty())
  618. throw std::invalid_argument("Missing mid in media SDP");
  619. }
  620. Description::Media::Media(const string &mline, string mid, Direction dir)
  621. : Entry(mline, std::move(mid), dir) {}
  622. string Description::Media::description() const {
  623. std::ostringstream desc;
  624. desc << Entry::description();
  625. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it)
  626. desc << ' ' << it->first;
  627. return desc.str();
  628. }
  629. Description::Media Description::Media::reciprocate() const {
  630. Media reciprocated(*this);
  631. // Invert direction
  632. switch (reciprocated.direction()) {
  633. case Direction::RecvOnly:
  634. reciprocated.setDirection(Direction::SendOnly);
  635. break;
  636. case Direction::SendOnly:
  637. reciprocated.setDirection(Direction::RecvOnly);
  638. break;
  639. default:
  640. // We are good
  641. break;
  642. }
  643. // Invert directions of extmap
  644. for (auto it = reciprocated.mExtMap.begin(); it != reciprocated.mExtMap.end(); ++it) {
  645. auto &map = it->second;
  646. switch (map.direction) {
  647. case Direction::RecvOnly:
  648. map.direction = Direction::SendOnly;
  649. break;
  650. case Direction::SendOnly:
  651. map.direction = Direction::RecvOnly;
  652. break;
  653. default:
  654. // We are good
  655. break;
  656. }
  657. }
  658. // Clear all ssrc attributes as they are individual
  659. auto it = reciprocated.mAttributes.begin();
  660. while (it != reciprocated.mAttributes.end()) {
  661. if (match_prefix(*it, "ssrc:"))
  662. it = reciprocated.mAttributes.erase(it);
  663. else
  664. ++it;
  665. }
  666. reciprocated.mSsrcs.clear();
  667. reciprocated.mCNameMap.clear();
  668. return reciprocated;
  669. }
  670. Description::Media::RTPMap &Description::Media::getFormat(int fmt) {
  671. auto it = mRtpMap.find(fmt);
  672. if (it != mRtpMap.end())
  673. return it->second;
  674. throw std::invalid_argument("m-line index is out of bounds");
  675. }
  676. Description::Media::RTPMap &Description::Media::getFormat(const string &fmt) {
  677. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it)
  678. if (it->second.format == fmt)
  679. return it->second;
  680. throw std::invalid_argument("format was not found");
  681. }
  682. void Description::Media::removeFormat(const string &fmt) {
  683. auto it = mRtpMap.begin();
  684. std::vector<int> remed;
  685. // Remove the actual formats
  686. while (it != mRtpMap.end()) {
  687. if (it->second.format == fmt) {
  688. remed.emplace_back(it->first);
  689. it = mRtpMap.erase(it);
  690. } else {
  691. it++;
  692. }
  693. }
  694. // Remove any other rtpmaps that depend on the formats we just removed
  695. it = mRtpMap.begin();
  696. while (it != mRtpMap.end()) {
  697. auto it2 = it->second.fmtps.begin();
  698. bool rem = false;
  699. while (it2 != it->second.fmtps.end()) {
  700. if (it2->find("apt=") == 0) {
  701. for (auto remid : remed) {
  702. if (it2->find(std::to_string(remid)) != string::npos) {
  703. std::cout << *it2 << ' ' << remid << std::endl;
  704. it = mRtpMap.erase(it);
  705. rem = true;
  706. break;
  707. }
  708. }
  709. break;
  710. }
  711. it2++;
  712. }
  713. if (!rem)
  714. it++;
  715. }
  716. }
  717. void Description::Video::addVideoCodec(int payloadType, string codec, optional<string> profile) {
  718. RTPMap map(std::to_string(payloadType) + ' ' + codec + "/90000");
  719. map.addFB("nack");
  720. map.addFB("nack pli");
  721. // map.addFB("ccm fir");
  722. map.addFB("goog-remb");
  723. if (profile)
  724. map.fmtps.emplace_back(*profile);
  725. addRTPMap(map);
  726. /* TODO
  727. * TIL that Firefox does not properly support the negotiation of RTX! It works, but doesn't
  728. * negotiate the SSRC so we have no idea what SSRC is RTX going to be. Three solutions: One) we
  729. * don't negotitate it and (maybe) break RTX support with Edge. Two) we do negotiate it and
  730. * rebuild the original packet before we send it distribute it to each track. Three) we complain
  731. * to mozilla. This one probably won't do much.
  732. */
  733. // RTX Packets
  734. // RTPMap rtx(std::to_string(payloadType+1) + " rtx/90000");
  735. // // TODO rtx-time is how long can a request be stashed for before needing to resend it.
  736. // Needs to be parameterized rtx.addAttribute("apt=" + std::to_string(payloadType) +
  737. // ";rtx-time=3000"); addRTPMap(rtx);
  738. }
  739. void Description::Audio::addAudioCodec(int payloadType, string codec, optional<string> profile) {
  740. // TODO This 48000/2 should be parameterized
  741. RTPMap map(std::to_string(payloadType) + ' ' + codec + "/48000/2");
  742. if (profile)
  743. map.fmtps.emplace_back(*profile);
  744. addRTPMap(map);
  745. }
  746. void Description::Media::addRTXCodec(unsigned int payloadType, unsigned int originalPayloadType,
  747. unsigned int clockRate) {
  748. RTPMap map(std::to_string(payloadType) + " RTX/" + std::to_string(clockRate));
  749. map.fmtps.emplace_back("apt=" + std::to_string(originalPayloadType));
  750. addRTPMap(map);
  751. }
  752. void Description::Video::addH264Codec(int pt, optional<string> profile) {
  753. addVideoCodec(pt, "H264", profile);
  754. }
  755. void Description::Video::addVP8Codec(int payloadType) {
  756. addVideoCodec(payloadType, "VP8", nullopt);
  757. }
  758. void Description::Video::addVP9Codec(int payloadType) {
  759. addVideoCodec(payloadType, "VP9", nullopt);
  760. }
  761. void Description::Media::setBitrate(int bitrate) { mBas = bitrate; }
  762. int Description::Media::getBitrate() const { return mBas; }
  763. bool Description::Media::hasPayloadType(int payloadType) const {
  764. return mRtpMap.find(payloadType) != mRtpMap.end();
  765. }
  766. string Description::Media::generateSdpLines(string_view eol) const {
  767. std::ostringstream sdp;
  768. if (mBas >= 0)
  769. sdp << "b=AS:" << mBas << eol;
  770. sdp << Entry::generateSdpLines(eol);
  771. sdp << "a=rtcp-mux" << eol;
  772. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it) {
  773. auto &map = it->second;
  774. // Create the a=rtpmap
  775. sdp << "a=rtpmap:" << map.pt << ' ' << map.format << '/' << map.clockRate;
  776. if (!map.encParams.empty())
  777. sdp << '/' << map.encParams;
  778. sdp << eol;
  779. for (const auto &val : map.rtcpFbs) {
  780. if (val != "transport-cc")
  781. sdp << "a=rtcp-fb:" << map.pt << ' ' << val << eol;
  782. }
  783. for (const auto &val : map.fmtps)
  784. sdp << "a=fmtp:" << map.pt << ' ' << val << eol;
  785. }
  786. return sdp.str();
  787. }
  788. void Description::Media::parseSdpLine(string_view line) {
  789. if (match_prefix(line, "a=")) {
  790. string_view attr = line.substr(2);
  791. auto [key, value] = parse_pair(attr);
  792. if (key == "rtpmap") {
  793. auto pt = Description::Media::RTPMap::parsePT(value);
  794. auto it = mRtpMap.find(pt);
  795. if (it == mRtpMap.end()) {
  796. it = mRtpMap.insert(std::make_pair(pt, Description::Media::RTPMap(value))).first;
  797. } else {
  798. it->second.setMLine(value);
  799. }
  800. } else if (key == "rtcp-fb") {
  801. size_t p = value.find(' ');
  802. int pt = to_integer<int>(value.substr(0, p));
  803. auto it = mRtpMap.find(pt);
  804. if (it == mRtpMap.end()) {
  805. it = mRtpMap.insert(std::make_pair(pt, Description::Media::RTPMap())).first;
  806. }
  807. it->second.rtcpFbs.emplace_back(value.substr(p + 1));
  808. } else if (key == "fmtp") {
  809. size_t p = value.find(' ');
  810. int pt = to_integer<int>(value.substr(0, p));
  811. auto it = mRtpMap.find(pt);
  812. if (it == mRtpMap.end())
  813. it = mRtpMap.insert(std::make_pair(pt, Description::Media::RTPMap())).first;
  814. it->second.fmtps.emplace_back(value.substr(p + 1));
  815. } else if (key == "rtcp-mux") {
  816. // always added
  817. } else if (key == "ssrc") {
  818. auto ssrc = to_integer<uint32_t>(value);
  819. if (!hasSSRC(ssrc)) {
  820. mSsrcs.emplace_back(ssrc);
  821. }
  822. auto cnamePos = value.find("cname:");
  823. if (cnamePos != string::npos) {
  824. auto cname = value.substr(cnamePos + 6);
  825. mCNameMap.emplace(ssrc, cname);
  826. }
  827. mAttributes.emplace_back(attr);
  828. } else {
  829. Entry::parseSdpLine(line);
  830. }
  831. } else if (match_prefix(line, "b=AS")) {
  832. mBas = to_integer<int>(line.substr(line.find(':') + 1));
  833. } else {
  834. Entry::parseSdpLine(line);
  835. }
  836. }
  837. void Description::Media::addRTPMap(const Description::Media::RTPMap &map) {
  838. mRtpMap.emplace(map.pt, map);
  839. }
  840. std::vector<uint32_t> Description::Media::getSSRCs() { return mSsrcs; }
  841. optional<string> Description::Media::getCNameForSsrc(uint32_t ssrc) {
  842. auto it = mCNameMap.find(ssrc);
  843. if (it != mCNameMap.end()) {
  844. return it->second;
  845. }
  846. return nullopt;
  847. }
  848. std::map<int, Description::Media::RTPMap>::iterator Description::Media::beginMaps() {
  849. return mRtpMap.begin();
  850. }
  851. std::map<int, Description::Media::RTPMap>::iterator Description::Media::endMaps() {
  852. return mRtpMap.end();
  853. }
  854. std::map<int, Description::Media::RTPMap>::iterator
  855. Description::Media::removeMap(std::map<int, Description::Media::RTPMap>::iterator iterator) {
  856. return mRtpMap.erase(iterator);
  857. }
  858. Description::Media::RTPMap::RTPMap(string_view mline) { setMLine(mline); }
  859. void Description::Media::RTPMap::removeFB(const string &str) {
  860. auto it = rtcpFbs.begin();
  861. while (it != rtcpFbs.end()) {
  862. if (it->find(str) != string::npos) {
  863. it = rtcpFbs.erase(it);
  864. } else
  865. it++;
  866. }
  867. }
  868. void Description::Media::RTPMap::addFB(const string &str) { rtcpFbs.emplace_back(str); }
  869. int Description::Media::RTPMap::parsePT(string_view view) {
  870. size_t p = view.find(' ');
  871. return to_integer<int>(view.substr(0, p));
  872. }
  873. void Description::Media::RTPMap::setMLine(string_view mline) {
  874. size_t p = mline.find(' ');
  875. if (p == string::npos)
  876. throw std::invalid_argument("Invalid m-line");
  877. this->pt = to_integer<int>(mline.substr(0, p));
  878. string_view line = mline.substr(p + 1);
  879. size_t spl = line.find('/');
  880. if (spl == string::npos)
  881. throw std::invalid_argument("Invalid m-line");
  882. this->format = line.substr(0, spl);
  883. line = line.substr(spl + 1);
  884. spl = line.find('/');
  885. if (spl == string::npos) {
  886. spl = line.find(' ');
  887. }
  888. if (spl == string::npos)
  889. this->clockRate = to_integer<int>(line);
  890. else {
  891. this->clockRate = to_integer<int>(line.substr(0, spl));
  892. this->encParams = line.substr(spl + 1);
  893. }
  894. }
  895. Description::Audio::Audio(string mid, Direction dir)
  896. : Media("audio 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  897. void Description::Audio::addOpusCodec(int payloadType, optional<string> profile) {
  898. addAudioCodec(payloadType, "OPUS", profile);
  899. }
  900. Description::Video::Video(string mid, Direction dir)
  901. : Media("video 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  902. Description::Type Description::stringToType(const string &typeString) {
  903. using TypeMap_t = std::unordered_map<string, Type>;
  904. static const TypeMap_t TypeMap = {{"unspec", Type::Unspec},
  905. {"offer", Type::Offer},
  906. {"answer", Type::Answer},
  907. {"pranswer", Type::Pranswer},
  908. {"rollback", Type::Rollback}};
  909. auto it = TypeMap.find(typeString);
  910. return it != TypeMap.end() ? it->second : Type::Unspec;
  911. }
  912. string Description::typeToString(Type type) {
  913. switch (type) {
  914. case Type::Unspec:
  915. return "unspec";
  916. case Type::Offer:
  917. return "offer";
  918. case Type::Answer:
  919. return "answer";
  920. case Type::Pranswer:
  921. return "pranswer";
  922. case Type::Rollback:
  923. return "rollback";
  924. default:
  925. return "unknown";
  926. }
  927. }
  928. } // namespace rtc
  929. std::ostream &operator<<(std::ostream &out, const rtc::Description &description) {
  930. return out << std::string(description);
  931. }
  932. std::ostream &operator<<(std::ostream &out, rtc::Description::Type type) {
  933. return out << rtc::Description::typeToString(type);
  934. }
  935. std::ostream &operator<<(std::ostream &out, rtc::Description::Role role) {
  936. using Role = rtc::Description::Role;
  937. // Used for SDP generation, do not change
  938. switch (role) {
  939. case Role::Active:
  940. out << "active";
  941. break;
  942. case Role::Passive:
  943. out << "passive";
  944. break;
  945. default:
  946. out << "actpass";
  947. break;
  948. }
  949. return out;
  950. }