description.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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 <algorithm>
  21. #include <array>
  22. #include <cctype>
  23. #include <chrono>
  24. #include <iostream>
  25. #include <random>
  26. using std::shared_ptr;
  27. using std::size_t;
  28. using std::string;
  29. using std::string_view;
  30. using std::chrono::system_clock;
  31. namespace {
  32. inline bool match_prefix(string_view str, string_view prefix) {
  33. return str.size() >= prefix.size() &&
  34. std::mismatch(prefix.begin(), prefix.end(), str.begin()).first == prefix.end();
  35. }
  36. inline void trim_end(string &str) {
  37. str.erase(
  38. std::find_if(str.rbegin(), str.rend(), [](char c) { return !std::isspace(c); }).base(),
  39. str.end());
  40. }
  41. inline std::pair<string_view, string_view> parse_pair(string_view attr) {
  42. string_view key, value;
  43. if (size_t separator = attr.find(':'); separator != string::npos) {
  44. key = attr.substr(0, separator);
  45. value = attr.substr(separator + 1);
  46. } else {
  47. key = attr;
  48. }
  49. return std::make_pair(std::move(key), std::move(value));
  50. }
  51. template <typename T> T to_integer(string_view s) {
  52. return std::is_signed<T>::value ? T(std::stol(string(s))) : T(std::stoul(string(s)));
  53. }
  54. } // namespace
  55. namespace rtc {
  56. Description::Description(const string &sdp, const string &typeString)
  57. : Description(sdp, stringToType(typeString)) {}
  58. Description::Description(const string &sdp, Type type) : Description(sdp, type, Role::ActPass) {}
  59. Description::Description(const string &sdp, Type type, Role role)
  60. : mType(Type::Unspec), mRole(role) {
  61. hintType(type);
  62. auto seed = static_cast<unsigned int>(system_clock::now().time_since_epoch().count());
  63. std::default_random_engine generator(seed);
  64. std::uniform_int_distribution<uint32_t> uniform;
  65. mSessionId = std::to_string(uniform(generator));
  66. std::istringstream ss(sdp);
  67. std::shared_ptr<Entry> current;
  68. int index = -1;
  69. string line;
  70. while (std::getline(ss, line) || !line.empty()) {
  71. trim_end(line);
  72. // Media description line (aka m-line)
  73. if (match_prefix(line, "m=")) {
  74. ++index;
  75. string mline = line.substr(2);
  76. current = createEntry(std::move(mline), std::to_string(index), Direction::Unknown);
  77. // Attribute line
  78. } else if (match_prefix(line, "a=")) {
  79. string attr = line.substr(2);
  80. auto [key, value] = parse_pair(attr);
  81. if (key == "setup") {
  82. if (value == "active")
  83. mRole = Role::Active;
  84. else if (value == "passive")
  85. mRole = Role::Passive;
  86. else
  87. mRole = Role::ActPass;
  88. } else if (key == "fingerprint") {
  89. if (match_prefix(value, "sha-256 ")) {
  90. mFingerprint = value.substr(8);
  91. std::transform(mFingerprint->begin(), mFingerprint->end(),
  92. mFingerprint->begin(),
  93. [](char c) { return char(std::toupper(c)); });
  94. } else {
  95. PLOG_WARNING << "Unknown SDP fingerprint type: " << value;
  96. }
  97. } else if (key == "ice-ufrag") {
  98. mIceUfrag = value;
  99. } else if (key == "ice-pwd") {
  100. mIcePwd = value;
  101. } else if (key == "candidate") {
  102. addCandidate(Candidate(attr, bundleMid()));
  103. } else if (key == "end-of-candidates") {
  104. mEnded = true;
  105. } else if (current) {
  106. current->parseSdpLine(std::move(line));
  107. }
  108. } else if (current) {
  109. current->parseSdpLine(std::move(line));
  110. }
  111. };
  112. }
  113. Description::Type Description::type() const { return mType; }
  114. string Description::typeString() const { return typeToString(mType); }
  115. Description::Role Description::role() const { return mRole; }
  116. string Description::roleString() const { return roleToString(mRole); }
  117. string Description::bundleMid() const {
  118. // Get the mid of the first media
  119. return !mEntries.empty() ? mEntries[0]->mid() : "0";
  120. }
  121. std::optional<string> Description::fingerprint() const { return mFingerprint; }
  122. bool Description::ended() const { return mEnded; }
  123. void Description::hintType(Type type) {
  124. if (mType == Type::Unspec) {
  125. mType = type;
  126. if (mType == Type::Answer && mRole == Role::ActPass)
  127. mRole = Role::Passive; // ActPass is illegal for an answer, so default to passive
  128. }
  129. }
  130. void Description::setFingerprint(string fingerprint) {
  131. mFingerprint.emplace(std::move(fingerprint));
  132. }
  133. void Description::addCandidate(Candidate candidate) {
  134. mCandidates.emplace_back(std::move(candidate));
  135. }
  136. void Description::endCandidates() { mEnded = true; }
  137. std::vector<Candidate> Description::extractCandidates() {
  138. std::vector<Candidate> result;
  139. std::swap(mCandidates, result);
  140. mEnded = false;
  141. return result;
  142. }
  143. Description::operator string() const { return generateSdp("\r\n"); }
  144. string Description::generateSdp(string_view eol) const {
  145. std::ostringstream sdp;
  146. // Header
  147. sdp << "v=0" << eol;
  148. sdp << "o=- " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
  149. sdp << "s=-" << eol;
  150. sdp << "t=0 0" << eol;
  151. // Bundle
  152. // see Negotiating Media Multiplexing Using the Session Description Protocol
  153. // https://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-54
  154. sdp << "a=group:BUNDLE";
  155. for (const auto &entry : mEntries)
  156. sdp << ' ' << entry->mid();
  157. sdp << eol;
  158. // Lip-sync
  159. std::ostringstream lsGroup;
  160. for (const auto &entry : mEntries)
  161. if (entry != mApplication)
  162. lsGroup << ' ' << entry->mid();
  163. if (!lsGroup.str().empty())
  164. sdp << "a=group:LS" << lsGroup.str() << eol;
  165. // Session-level attributes
  166. sdp << "a=msid-semantic:WMS *" << eol;
  167. sdp << "a=setup:" << roleToString(mRole) << eol;
  168. sdp << "a=ice-ufrag:" << mIceUfrag << eol;
  169. sdp << "a=ice-pwd:" << mIcePwd << eol;
  170. if (!mEnded)
  171. sdp << "a=ice-options:trickle" << eol;
  172. if (mFingerprint)
  173. sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
  174. // Entries
  175. bool first = true;
  176. for (const auto &entry : mEntries) {
  177. sdp << entry->generateSdp(eol);
  178. if (std::exchange(first, false)) {
  179. // Candidates
  180. for (const auto &candidate : mCandidates)
  181. sdp << string(candidate) << eol;
  182. if (mEnded)
  183. sdp << "a=end-of-candidates" << eol;
  184. }
  185. }
  186. return sdp.str();
  187. }
  188. string Description::generateApplicationSdp(string_view eol) const {
  189. std::ostringstream sdp;
  190. // Header
  191. sdp << "v=0" << eol;
  192. sdp << "o=- " << mSessionId << " 0 IN IP4 127.0.0.1" << eol;
  193. sdp << "s=-" << eol;
  194. sdp << "t=0 0" << eol;
  195. // Application
  196. auto app = mApplication ? mApplication : std::make_shared<Application>();
  197. sdp << app->generateSdp(eol);
  198. // Session-level attributes
  199. sdp << "a=msid-semantic:WMS *" << eol;
  200. sdp << "a=setup:" << roleToString(mRole) << eol;
  201. sdp << "a=ice-ufrag:" << mIceUfrag << eol;
  202. sdp << "a=ice-pwd:" << mIcePwd << eol;
  203. if (!mEnded)
  204. sdp << "a=ice-options:trickle" << eol;
  205. if (mFingerprint)
  206. sdp << "a=fingerprint:sha-256 " << *mFingerprint << eol;
  207. // Candidates
  208. for (const auto &candidate : mCandidates)
  209. sdp << string(candidate) << eol;
  210. if (mEnded)
  211. sdp << "a=end-of-candidates" << eol;
  212. return sdp.str();
  213. }
  214. shared_ptr<Description::Entry> Description::createEntry(string mline, string mid, Direction dir) {
  215. string type = mline.substr(0, mline.find(' '));
  216. if (type == "application") {
  217. removeApplication();
  218. mApplication = std::make_shared<Application>(std::move(mid));
  219. mEntries.emplace_back(mApplication);
  220. return mApplication;
  221. } else {
  222. auto media = std::make_shared<Media>(std::move(mline), std::move(mid), dir);
  223. mEntries.emplace_back(media);
  224. return media;
  225. }
  226. }
  227. void Description::removeApplication() {
  228. if (!mApplication)
  229. return;
  230. auto it = std::find(mEntries.begin(), mEntries.end(), mApplication);
  231. if (it != mEntries.end())
  232. mEntries.erase(it);
  233. mApplication.reset();
  234. }
  235. bool Description::hasApplication() const { return mApplication != nullptr; }
  236. bool Description::hasAudioOrVideo() const {
  237. for (auto entry : mEntries)
  238. if (entry != mApplication)
  239. return true;
  240. return false;
  241. }
  242. int Description::addMedia(Media media) {
  243. mEntries.emplace_back(std::make_shared<Media>(std::move(media)));
  244. return int(mEntries.size()) - 1;
  245. }
  246. int Description::addMedia(Application application) {
  247. removeApplication();
  248. mApplication = std::make_shared<Application>(std::move(application));
  249. mEntries.emplace_back(mApplication);
  250. return int(mEntries.size()) - 1;
  251. }
  252. int Description::addApplication(string mid) { return addMedia(Application(std::move(mid))); }
  253. Description::Application *Description::application() { return mApplication.get(); }
  254. int Description::addVideo(string mid, Direction dir) {
  255. return addMedia(Video(std::move(mid), dir));
  256. }
  257. int Description::addAudio(string mid, Direction dir) {
  258. return addMedia(Audio(std::move(mid), dir));
  259. }
  260. std::variant<Description::Media *, Description::Application *> Description::media(int index) {
  261. if (index < 0 || index >= int(mEntries.size()))
  262. throw std::out_of_range("Media index out of range");
  263. const auto &entry = mEntries[index];
  264. if (entry == mApplication) {
  265. auto result = dynamic_cast<Application *>(entry.get());
  266. if (!result)
  267. throw std::logic_error("Bad type of application in description");
  268. return result;
  269. } else {
  270. auto result = dynamic_cast<Media *>(entry.get());
  271. if (!result)
  272. throw std::logic_error("Bad type of media in description");
  273. return result;
  274. }
  275. }
  276. std::variant<const Description::Media *, const Description::Application *>
  277. Description::media(int index) const {
  278. if (index < 0 || index >= int(mEntries.size()))
  279. throw std::out_of_range("Media index out of range");
  280. const auto &entry = mEntries[index];
  281. if (entry == mApplication) {
  282. auto result = dynamic_cast<Application *>(entry.get());
  283. if (!result)
  284. throw std::logic_error("Bad type of application in description");
  285. return result;
  286. } else {
  287. auto result = dynamic_cast<Media *>(entry.get());
  288. if (!result)
  289. throw std::logic_error("Bad type of media in description");
  290. return result;
  291. }
  292. }
  293. unsigned int Description::mediaCount() const { return mEntries.size(); }
  294. Description::Entry::Entry(const string &mline, string mid, Direction dir)
  295. : mMid(std::move(mid)), mDirection(dir) {
  296. unsigned int port;
  297. std::istringstream ss(mline);
  298. ss >> mType;
  299. ss >> port; // ignored
  300. ss >> mDescription;
  301. }
  302. void Description::Entry::setDirection(Direction dir) { mDirection = dir; }
  303. Description::Entry::operator string() const { return generateSdp("\r\n"); }
  304. string Description::Entry::generateSdp(string_view eol) const {
  305. std::ostringstream sdp;
  306. // Port 9 is the discard protocol
  307. sdp << "m=" << type() << ' ' << 9 << ' ' << description() << eol;
  308. sdp << "c=IN IP4 0.0.0.0" << eol;
  309. sdp << generateSdpLines(eol);
  310. return sdp.str();
  311. }
  312. string Description::Entry::generateSdpLines(string_view eol) const {
  313. std::ostringstream sdp;
  314. sdp << "a=bundle-only" << eol;
  315. sdp << "a=mid:" << mMid << eol;
  316. switch (mDirection) {
  317. case Direction::SendOnly:
  318. sdp << "a=sendonly" << eol;
  319. break;
  320. case Direction::RecvOnly:
  321. sdp << "a=recvonly" << eol;
  322. break;
  323. case Direction::SendRecv:
  324. sdp << "a=sendrecv" << eol;
  325. break;
  326. case Direction::Inactive:
  327. sdp << "a=inactive" << eol;
  328. break;
  329. default:
  330. // Ignore
  331. break;
  332. }
  333. for (const auto &attr : mAttributes)
  334. sdp << "a=" << attr << eol;
  335. return sdp.str();
  336. }
  337. void Description::Entry::parseSdpLine(string_view line) {
  338. if (match_prefix(line, "a=")) {
  339. string_view attr = line.substr(2);
  340. auto [key, value] = parse_pair(attr);
  341. if (key == "mid")
  342. mMid = value;
  343. else if (attr == "sendonly")
  344. mDirection = Direction::SendOnly;
  345. else if (attr == "recvonly")
  346. mDirection = Direction::RecvOnly;
  347. else if (key == "sendrecv")
  348. mDirection = Direction::SendRecv;
  349. else if (key == "inactive")
  350. mDirection = Direction::Inactive;
  351. else if (key == "bundle-only") {
  352. // always added
  353. } else
  354. mAttributes.emplace_back(line.substr(2));
  355. }
  356. }
  357. void Description::Media::addSSRC(uint32_t ssrc, std::string name) {
  358. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " cname:" + name);
  359. }
  360. void Description::Media::replaceSSRC(uint32_t oldSSRC, uint32_t ssrc, std::string name) {
  361. auto it = mAttributes.begin();
  362. while (it != mAttributes.end()) {
  363. if (it->find("ssrc:" + std::to_string(oldSSRC)) == 0) {
  364. it = mAttributes.erase(it);
  365. }else
  366. it++;
  367. }
  368. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc) + " cname:" + name);
  369. }
  370. void Description::Media::addSSRC(uint32_t ssrc) {
  371. mAttributes.emplace_back("ssrc:" + std::to_string(ssrc));
  372. }
  373. bool Description::Media::hasSSRC(uint32_t ssrc) {
  374. for (auto &val : mAttributes) {
  375. if (val.find("ssrc:" + std::to_string(ssrc)) != std::string ::npos)
  376. return true;
  377. }
  378. return false;
  379. }
  380. Description::Application::Application(string mid)
  381. : Entry("application 9 UDP/DTLS/SCTP", std::move(mid), Direction::SendRecv) {}
  382. string Description::Application::description() const {
  383. return Entry::description() + " webrtc-datachannel";
  384. }
  385. Description::Application Description::Application::reciprocate() const {
  386. Application reciprocated(*this);
  387. reciprocated.mMaxMessageSize.reset();
  388. return reciprocated;
  389. }
  390. string Description::Application::generateSdpLines(string_view eol) const {
  391. std::ostringstream sdp;
  392. sdp << Entry::generateSdpLines(eol);
  393. if (mSctpPort)
  394. sdp << "a=sctp-port:" << *mSctpPort << eol;
  395. if (mMaxMessageSize)
  396. sdp << "a=max-message-size:" << *mMaxMessageSize << eol;
  397. return sdp.str();
  398. }
  399. void Description::Application::parseSdpLine(string_view line) {
  400. if (match_prefix(line, "a=")) {
  401. string_view attr = line.substr(2);
  402. auto [key, value] = parse_pair(attr);
  403. if (key == "sctp-port") {
  404. mSctpPort = to_integer<uint16_t>(value);
  405. } else if (key == "max-message-size") {
  406. mMaxMessageSize = to_integer<size_t>(value);
  407. } else {
  408. Entry::parseSdpLine(line);
  409. }
  410. } else {
  411. Entry::parseSdpLine(line);
  412. }
  413. }
  414. Description::Media::Media(const string &sdp) : Entry(sdp, "", Direction::Unknown) {
  415. std::istringstream ss(sdp);
  416. string line;
  417. while (std::getline(ss, line) || !line.empty()) {
  418. trim_end(line);
  419. parseSdpLine(line);
  420. }
  421. if (mid().empty())
  422. throw std::invalid_argument("Missing mid in media SDP");
  423. }
  424. Description::Media::Media(const string &mline, string mid, Direction dir)
  425. : Entry(mline, std::move(mid), dir) {
  426. }
  427. string Description::Media::description() const {
  428. std::ostringstream desc;
  429. desc << Entry::description();
  430. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it)
  431. desc << ' ' << it->first;
  432. return desc.str();
  433. }
  434. Description::Media Description::Media::reciprocate() const {
  435. Media reciprocated(*this);
  436. // Invert direction
  437. switch (direction()) {
  438. case Direction::RecvOnly:
  439. reciprocated.setDirection(Direction::SendOnly);
  440. break;
  441. case Direction::SendOnly:
  442. reciprocated.setDirection(Direction::RecvOnly);
  443. break;
  444. default:
  445. // We are good
  446. break;
  447. }
  448. return reciprocated;
  449. }
  450. Description::Media::RTPMap &Description::Media::getFormat(int fmt) {
  451. auto it = mRtpMap.find(fmt);
  452. if (it != mRtpMap.end())
  453. return it->second;
  454. throw std::invalid_argument("m-line index is out of bounds");
  455. }
  456. Description::Media::RTPMap &Description::Media::getFormat(const string &fmt) {
  457. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it)
  458. if (it->second.format == fmt)
  459. return it->second;
  460. throw std::invalid_argument("format was not found");
  461. }
  462. void Description::Media::removeFormat(const string &fmt) {
  463. auto it = mRtpMap.begin();
  464. std::vector<int> remed;
  465. // Remove the actual formats
  466. while (it != mRtpMap.end()) {
  467. if (it->second.format == fmt) {
  468. remed.emplace_back(it->first);
  469. it = mRtpMap.erase(it);
  470. } else {
  471. it++;
  472. }
  473. }
  474. // Remove any other rtpmaps that depend on the formats we just removed
  475. it = mRtpMap.begin();
  476. while (it != mRtpMap.end()) {
  477. auto it2 = it->second.fmtps.begin();
  478. bool rem = false;
  479. while (it2 != it->second.fmtps.end()) {
  480. if (it2->find("apt=") == 0) {
  481. for (auto remid : remed) {
  482. if (it2->find(std::to_string(remid)) != string::npos) {
  483. std::cout << *it2 << ' ' << remid << std::endl;
  484. it = mRtpMap.erase(it);
  485. rem = true;
  486. break;
  487. }
  488. }
  489. break;
  490. }
  491. it2++;
  492. }
  493. if (!rem)
  494. it++;
  495. }
  496. }
  497. void Description::Video::addVideoCodec(int payloadType, const string &codec) {
  498. RTPMap map(std::to_string(payloadType) + ' ' + codec + "/90000");
  499. map.addFB("nack");
  500. map.addFB("nack pli");
  501. map.addFB("goog-remb");
  502. if (codec == "H264") {
  503. // Use Constrained Baseline profile Level 4.2 (necessary for Firefox)
  504. // https://developer.mozilla.org/en-US/docs/Web/Media/Formats/WebRTC_codecs#Supported_video_codecs
  505. // TODO: Should be 42E0 but 42C0 appears to be more compatible. Investigate this.
  506. map.fmtps.emplace_back("profile-level-id=4de01f;packetization-mode=1;level-asymmetry-allowed=1");
  507. // Because certain Android devices don't like me, let us just negotiate some random
  508. {
  509. RTPMap map(std::to_string(payloadType+1) + ' ' + codec + "/90000");
  510. map.addFB("nack");
  511. map.addFB("nack pli");
  512. map.addFB("goog-remb");
  513. addRTPMap(map);
  514. }
  515. }
  516. addRTPMap(map);
  517. // // RTX Packets
  518. /* TODO
  519. * TIL that Firefox does not properly support the negotiation of RTX! It works, but doesn't negotiate the SSRC so
  520. * we have no idea what SSRC is RTX going to be. Three solutions:
  521. * One) we don't negotitate it and (maybe) break RTX support with Edge.
  522. * Two) we do negotiate it and rebuild the original packet before we send it distribute it to each track.
  523. * Three) we complain to mozilla. This one probably won't do much.
  524. */
  525. // RTPMap rtx(std::to_string(payloadType+1) + " rtx/90000");
  526. // // TODO rtx-time is how long can a request be stashed for before needing to resend it. Needs to be parameterized
  527. // rtx.addAttribute("apt=" + std::to_string(payloadType) + ";rtx-time=3000");
  528. // addRTPMap(rtx);
  529. }
  530. void Description::Audio::addAudioCodec(int payloadType, const string &codec) {
  531. // TODO This 48000/2 should be parameterized
  532. RTPMap map(std::to_string(payloadType) + ' ' + codec + "/48000/2");
  533. map.fmtps.emplace_back("maxaveragebitrate=510000; stereo=1; sprop-stereo=1; useinbandfec=1");
  534. addRTPMap(map);
  535. }
  536. void Description::Video::addH264Codec(int pt) { addVideoCodec(pt, "H264"); }
  537. void Description::Video::addVP8Codec(int payloadType) { addVideoCodec(payloadType, "VP8"); }
  538. void Description::Video::addVP9Codec(int payloadType) { addVideoCodec(payloadType, "VP9"); }
  539. void Description::Media::setBitrate(int bitrate) { mBas = bitrate; }
  540. int Description::Media::getBitrate() const { return mBas; }
  541. bool Description::Media::hasPayloadType(int payloadType) const {
  542. return mRtpMap.find(payloadType) != mRtpMap.end();
  543. }
  544. string Description::Media::generateSdpLines(string_view eol) const {
  545. std::ostringstream sdp;
  546. if (mBas >= 0)
  547. sdp << "b=AS:" << mBas << eol;
  548. sdp << Entry::generateSdpLines(eol);
  549. sdp << "a=rtcp-mux" << eol;
  550. for (auto it = mRtpMap.begin(); it != mRtpMap.end(); ++it) {
  551. auto &map = it->second;
  552. // Create the a=rtpmap
  553. sdp << "a=rtpmap:" << map.pt << ' ' << map.format << '/' << map.clockRate;
  554. if (!map.encParams.empty())
  555. sdp << '/' << map.encParams;
  556. sdp << eol;
  557. for (const auto &val : map.rtcpFbs)
  558. sdp << "a=rtcp-fb:" << map.pt << ' ' << val << eol;
  559. for (const auto &val : map.fmtps)
  560. sdp << "a=fmtp:" << map.pt << ' ' << val << eol;
  561. }
  562. return sdp.str();
  563. }
  564. void Description::Media::parseSdpLine(string_view line) {
  565. if (match_prefix(line, "a=")) {
  566. string_view attr = line.substr(2);
  567. auto [key, value] = parse_pair(attr);
  568. if (key == "rtpmap") {
  569. Description::Media::RTPMap map(value);
  570. int pt = map.pt;
  571. mRtpMap.emplace(pt, std::move(map));
  572. } else if (key == "rtcp-fb") {
  573. size_t p = value.find(' ');
  574. int pt = to_integer<int>(value.substr(0, p));
  575. auto it = mRtpMap.find(pt);
  576. if (it == mRtpMap.end()) {
  577. PLOG_WARNING << "rtcp-fb applied before the corresponding rtpmap, ignoring";
  578. } else {
  579. it->second.rtcpFbs.emplace_back(value.substr(p + 1));
  580. }
  581. } else if (key == "fmtp") {
  582. size_t p = value.find(' ');
  583. int pt = to_integer<int>(value.substr(0, p));
  584. auto it = mRtpMap.find(pt);
  585. if (it == mRtpMap.end()) {
  586. PLOG_WARNING << "fmtp applied before the corresponding rtpmap, ignoring";
  587. } else {
  588. it->second.fmtps.emplace_back(value.substr(p + 1));
  589. }
  590. } else if (key == "rtcp-mux") {
  591. // always added
  592. } else {
  593. Entry::parseSdpLine(line);
  594. }
  595. } else if (match_prefix(line, "b=AS")) {
  596. mBas = to_integer<int>(line.substr(line.find(':') + 1));
  597. } else {
  598. Entry::parseSdpLine(line);
  599. }
  600. }
  601. void Description::Media::addRTPMap(const Description::Media::RTPMap& map) {
  602. mRtpMap.emplace(map.pt, map);
  603. }
  604. std::vector<uint32_t> Description::Media::getSSRCs() {
  605. std::vector<uint32_t> vec;
  606. for (auto &val : mAttributes) {
  607. PLOG_DEBUG << val;
  608. if (val.find("ssrc:") == 0) {
  609. vec.emplace_back(std::stoul((std::string)val.substr(5, val.find(" "))));
  610. }
  611. }
  612. return vec;
  613. }
  614. Description::Media::RTPMap::RTPMap(string_view mline) {
  615. size_t p = mline.find(' ');
  616. this->pt = to_integer<int>(mline.substr(0, p));
  617. string_view line = mline.substr(p + 1);
  618. size_t spl = line.find('/');
  619. this->format = line.substr(0, spl);
  620. line = line.substr(spl + 1);
  621. spl = line.find('/');
  622. if (spl == string::npos) {
  623. spl = line.find(' ');
  624. }
  625. if (spl == string::npos)
  626. this->clockRate = to_integer<int>(line);
  627. else {
  628. this->clockRate = to_integer<int>(line.substr(0, spl));
  629. this->encParams = line.substr(spl+1);
  630. }
  631. }
  632. void Description::Media::RTPMap::removeFB(const string &str) {
  633. auto it = rtcpFbs.begin();
  634. while (it != rtcpFbs.end()) {
  635. if (it->find(str) != std::string::npos) {
  636. it = rtcpFbs.erase(it);
  637. } else
  638. it++;
  639. }
  640. }
  641. void Description::Media::RTPMap::addFB(const string &str) { rtcpFbs.emplace_back(str); }
  642. Description::Audio::Audio(string mid, Direction dir)
  643. : Media("audio 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  644. void Description::Audio::addOpusCodec(int payloadType) {
  645. addAudioCodec(payloadType, "OPUS");
  646. }
  647. Description::Video::Video(string mid, Direction dir)
  648. : Media("video 9 UDP/TLS/RTP/SAVPF", std::move(mid), dir) {}
  649. Description::Type Description::stringToType(const string &typeString) {
  650. if (typeString == "offer")
  651. return Type::Offer;
  652. else if (typeString == "answer")
  653. return Type::Answer;
  654. else
  655. return Type::Unspec;
  656. }
  657. string Description::typeToString(Type type) {
  658. switch (type) {
  659. case Type::Offer:
  660. return "offer";
  661. case Type::Answer:
  662. return "answer";
  663. default:
  664. return "";
  665. }
  666. }
  667. string Description::roleToString(Role role) {
  668. switch (role) {
  669. case Role::Active:
  670. return "active";
  671. case Role::Passive:
  672. return "passive";
  673. default:
  674. return "actpass";
  675. }
  676. }
  677. } // namespace rtc
  678. std::ostream &operator<<(std::ostream &out, const rtc::Description &description) {
  679. return out << std::string(description);
  680. }