rtp.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. /**
  2. * Copyright (c) 2020 Staz Modrzynski
  3. * Copyright (c) 2020 Paul-Louis Ageneau
  4. * Copyright (c) 2020 Filip Klembara (in2core)
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 2.1 of the License, or (at your option) any later version.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #ifndef RTC_RTP_HPP
  21. #define RTC_RTP_HPP
  22. #include "log.hpp"
  23. #include <cmath>
  24. #ifdef _WIN32
  25. #include <winsock2.h>
  26. #else
  27. #include <arpa/inet.h>
  28. #endif
  29. #ifndef htonll
  30. #define htonll(x) \
  31. ((uint64_t)(((uint64_t)htonl((uint32_t)(x))) << 32) | (uint64_t)htonl((uint32_t)((x) >> 32)))
  32. #endif
  33. #ifndef ntohll
  34. #define ntohll(x) htonll(x)
  35. #endif
  36. namespace rtc {
  37. typedef uint32_t SSRC;
  38. #pragma pack(push, 1)
  39. struct RTP {
  40. private:
  41. uint8_t _first;
  42. uint8_t _payloadType;
  43. uint16_t _seqNumber;
  44. uint32_t _timestamp;
  45. SSRC _ssrc;
  46. public:
  47. SSRC csrc[16];
  48. inline uint8_t version() const { return _first >> 6; }
  49. inline bool padding() const { return (_first >> 5) & 0x01; }
  50. inline bool extension() const { return (_first >> 4) & 0x01; }
  51. inline uint8_t csrcCount() const { return _first & 0x0F; }
  52. inline uint8_t marker() const { return _payloadType & 0b10000000; }
  53. inline uint8_t payloadType() const { return _payloadType & 0b01111111; }
  54. inline uint16_t seqNumber() const { return ntohs(_seqNumber); }
  55. inline uint32_t timestamp() const { return ntohl(_timestamp); }
  56. inline uint32_t ssrc() const { return ntohl(_ssrc); }
  57. inline size_t getSize() const {
  58. return reinterpret_cast<const char *>(&csrc) - reinterpret_cast<const char *>(this) +
  59. sizeof(SSRC) * csrcCount();
  60. }
  61. [[nodiscard]] char *getBody() {
  62. return reinterpret_cast<char *>(&csrc) + sizeof(SSRC) * csrcCount();
  63. }
  64. [[nodiscard]] const char *getBody() const {
  65. return reinterpret_cast<const char *>(&csrc) + sizeof(SSRC) * csrcCount();
  66. }
  67. inline void preparePacket() { _first |= (1 << 7); }
  68. inline void setSeqNumber(uint16_t newSeqNo) { _seqNumber = htons(newSeqNo); }
  69. inline void setPayloadType(uint8_t newPayloadType) {
  70. _payloadType = (_payloadType & 0b10000000u) | (0b01111111u & newPayloadType);
  71. }
  72. inline void setSsrc(uint32_t in_ssrc) { _ssrc = htonl(in_ssrc); }
  73. inline void setMarker(bool marker) { _payloadType = (_payloadType & 0x7F) | (marker << 7); };
  74. void setTimestamp(uint32_t i) { _timestamp = htonl(i); }
  75. void log() {
  76. PLOG_VERBOSE << "RTP V: " << (int)version() << " P: " << (padding() ? "P" : " ")
  77. << " X: " << (extension() ? "X" : " ") << " CC: " << (int)csrcCount()
  78. << " M: " << (marker() ? "M" : " ") << " PT: " << (int)payloadType()
  79. << " SEQNO: " << seqNumber() << " TS: " << timestamp();
  80. }
  81. };
  82. struct RTCP_ReportBlock {
  83. SSRC ssrc;
  84. private:
  85. uint32_t _fractionLostAndPacketsLost; // fraction lost is 8-bit, packets lost is 24-bit
  86. uint16_t _seqNoCycles;
  87. uint16_t _highestSeqNo;
  88. uint32_t _jitter;
  89. uint32_t _lastReport;
  90. uint32_t _delaySinceLastReport;
  91. public:
  92. inline void preparePacket(SSRC in_ssrc, [[maybe_unused]] unsigned int packetsLost,
  93. [[maybe_unused]] unsigned int totalPackets, uint16_t highestSeqNo,
  94. uint16_t seqNoCycles, uint32_t jitter, uint64_t lastSR_NTP,
  95. uint64_t lastSR_DELAY) {
  96. setSeqNo(highestSeqNo, seqNoCycles);
  97. setJitter(jitter);
  98. setSSRC(in_ssrc);
  99. // Middle 32 bits of NTP Timestamp
  100. // this->lastReport = lastSR_NTP >> 16u;
  101. setNTPOfSR(uint64_t(lastSR_NTP));
  102. setDelaySinceSR(uint32_t(lastSR_DELAY));
  103. // The delay, expressed in units of 1/65536 seconds
  104. // this->delaySinceLastReport = lastSR_DELAY;
  105. }
  106. inline void setSSRC(SSRC in_ssrc) { this->ssrc = htonl(in_ssrc); }
  107. [[nodiscard]] inline SSRC getSSRC() const { return ntohl(ssrc); }
  108. inline void setPacketsLost([[maybe_unused]] unsigned int packetsLost,
  109. [[maybe_unused]] unsigned int totalPackets) {
  110. // TODO Implement loss percentages.
  111. _fractionLostAndPacketsLost = 0;
  112. }
  113. [[nodiscard]] inline unsigned int getLossPercentage() const {
  114. // TODO Implement loss percentages.
  115. return 0;
  116. }
  117. [[nodiscard]] inline unsigned int getPacketLostCount() const {
  118. // TODO Implement total packets lost.
  119. return 0;
  120. }
  121. inline uint16_t seqNoCycles() const { return ntohs(_seqNoCycles); }
  122. inline uint16_t highestSeqNo() const { return ntohs(_highestSeqNo); }
  123. inline uint32_t jitter() const { return ntohl(_jitter); }
  124. inline void setSeqNo(uint16_t highestSeqNo, uint16_t seqNoCycles) {
  125. _highestSeqNo = htons(highestSeqNo);
  126. _seqNoCycles = htons(seqNoCycles);
  127. }
  128. inline void setJitter(uint32_t jitter) { _jitter = htonl(jitter); }
  129. inline void setNTPOfSR(uint64_t ntp) { _lastReport = htonll(ntp >> 16u); }
  130. [[nodiscard]] inline uint32_t getNTPOfSR() const { return ntohl(_lastReport) << 16u; }
  131. inline void setDelaySinceSR(uint32_t sr) {
  132. // The delay, expressed in units of 1/65536 seconds
  133. _delaySinceLastReport = htonl(sr);
  134. }
  135. [[nodiscard]] inline uint32_t getDelaySinceSR() const { return ntohl(_delaySinceLastReport); }
  136. inline void log() const {
  137. PLOG_VERBOSE << "RTCP report block: "
  138. << "ssrc="
  139. << ntohl(ssrc)
  140. // TODO: Implement these reports
  141. // << ", fractionLost=" << fractionLost
  142. // << ", packetsLost=" << packetsLost
  143. << ", highestSeqNo=" << highestSeqNo() << ", seqNoCycles=" << seqNoCycles()
  144. << ", jitter=" << jitter() << ", lastSR=" << getNTPOfSR()
  145. << ", lastSRDelay=" << getDelaySinceSR();
  146. }
  147. };
  148. struct RTCP_HEADER {
  149. private:
  150. uint8_t _first;
  151. uint8_t _payloadType;
  152. uint16_t _length;
  153. public:
  154. inline uint8_t version() const { return _first >> 6; }
  155. inline bool padding() const { return (_first >> 5) & 0x01; }
  156. inline uint8_t reportCount() const { return _first & 0x0F; }
  157. inline uint8_t payloadType() const { return _payloadType; }
  158. inline uint16_t length() const { return ntohs(_length); }
  159. inline size_t lengthInBytes() const { return (1 + length()) * 4; }
  160. inline void setPayloadType(uint8_t type) { _payloadType = type; }
  161. inline void setReportCount(uint8_t count) {
  162. _first = (_first & 0b11100000u) | (count & 0b00011111u);
  163. }
  164. inline void setLength(uint16_t length) { _length = htons(length); }
  165. inline void prepareHeader(uint8_t payloadType, uint8_t reportCount, uint16_t length) {
  166. _first = 0b10000000; // version 2, no padding
  167. setReportCount(reportCount);
  168. setPayloadType(payloadType);
  169. setLength(length);
  170. }
  171. inline void log() const {
  172. PLOG_VERBOSE << "RTCP header: "
  173. << "version=" << unsigned(version()) << ", padding=" << padding()
  174. << ", reportCount=" << unsigned(reportCount())
  175. << ", payloadType=" << unsigned(payloadType()) << ", length=" << length();
  176. }
  177. };
  178. struct RTCP_FB_HEADER {
  179. RTCP_HEADER header;
  180. SSRC packetSender;
  181. SSRC mediaSource;
  182. [[nodiscard]] SSRC getPacketSenderSSRC() const { return ntohl(packetSender); }
  183. [[nodiscard]] SSRC getMediaSourceSSRC() const { return ntohl(mediaSource); }
  184. void setPacketSenderSSRC(SSRC ssrc) { this->packetSender = htonl(ssrc); }
  185. void setMediaSourceSSRC(SSRC ssrc) { this->mediaSource = htonl(ssrc); }
  186. void log() {
  187. header.log();
  188. PLOG_VERBOSE << "FB: "
  189. << " packet sender: " << getPacketSenderSSRC()
  190. << " media source: " << getMediaSourceSSRC();
  191. }
  192. };
  193. struct RTCP_SR {
  194. RTCP_HEADER header;
  195. SSRC _senderSSRC;
  196. private:
  197. uint64_t _ntpTimestamp;
  198. uint32_t _rtpTimestamp;
  199. uint32_t _packetCount;
  200. uint32_t _octetCount;
  201. RTCP_ReportBlock _reportBlocks;
  202. public:
  203. inline void preparePacket(SSRC senderSSRC, uint8_t reportCount) {
  204. unsigned int length =
  205. ((sizeof(header) + 24 + reportCount * sizeof(RTCP_ReportBlock)) / 4) - 1;
  206. header.prepareHeader(200, reportCount, uint16_t(length));
  207. this->_senderSSRC = htonl(senderSSRC);
  208. }
  209. [[nodiscard]] inline RTCP_ReportBlock *getReportBlock(int num) { return &_reportBlocks + num; }
  210. [[nodiscard]] inline const RTCP_ReportBlock *getReportBlock(int num) const {
  211. return &_reportBlocks + num;
  212. }
  213. [[nodiscard]] static unsigned int size(unsigned int reportCount) {
  214. return sizeof(RTCP_HEADER) + 24 + reportCount * sizeof(RTCP_ReportBlock);
  215. }
  216. [[nodiscard]] inline size_t getSize() const {
  217. // "length" in packet is one less than the number of 32 bit words in the packet.
  218. return sizeof(uint32_t) * (1 + size_t(header.length()));
  219. }
  220. inline uint64_t ntpTimestamp() const { return ntohll(_ntpTimestamp); }
  221. inline uint32_t rtpTimestamp() const { return ntohl(_rtpTimestamp); }
  222. inline uint32_t packetCount() const { return ntohl(_packetCount); }
  223. inline uint32_t octetCount() const { return ntohl(_octetCount); }
  224. inline uint32_t senderSSRC() const { return ntohl(_senderSSRC); }
  225. inline void setNtpTimestamp(uint64_t ts) { _ntpTimestamp = htonll(ts); }
  226. inline void setRtpTimestamp(uint32_t ts) { _rtpTimestamp = htonl(ts); }
  227. inline void setOctetCount(uint32_t ts) { _octetCount = htonl(ts); }
  228. inline void setPacketCount(uint32_t ts) { _packetCount = htonl(ts); }
  229. inline void log() const {
  230. header.log();
  231. PLOG_VERBOSE << "RTCP SR: "
  232. << " SSRC=" << senderSSRC() << ", NTP_TS=" << ntpTimestamp()
  233. << ", RTP_TS=" << rtpTimestamp() << ", packetCount=" << packetCount()
  234. << ", octetCount=" << octetCount();
  235. for (unsigned i = 0; i < unsigned(header.reportCount()); i++) {
  236. getReportBlock(i)->log();
  237. }
  238. }
  239. };
  240. struct RTCP_SDES_ITEM {
  241. public:
  242. uint8_t type;
  243. private:
  244. uint8_t _length;
  245. char _text[1];
  246. public:
  247. inline std::string text() const { return std::string(_text, _length); }
  248. inline void setText(std::string text) {
  249. if(text.size() > 0xFF)
  250. throw std::invalid_argument("text is too long");
  251. _length = uint8_t(text.size());
  252. memcpy(_text, text.data(), text.size());
  253. }
  254. inline uint8_t length() { return _length; }
  255. [[nodiscard]] static unsigned int size(uint8_t textLength) { return textLength + 2; }
  256. };
  257. struct RTCP_SDES_CHUNK {
  258. private:
  259. SSRC _ssrc;
  260. RTCP_SDES_ITEM _items;
  261. public:
  262. inline SSRC ssrc() const { return ntohl(_ssrc); }
  263. inline void setSSRC(SSRC ssrc) { _ssrc = htonl(ssrc); }
  264. /// Get item at given index
  265. /// @note All items with index < `num` must be valid, otherwise this function has undefined
  266. /// behaviour (use `safelyCountChunkSize` to check if chunk is valid)
  267. /// @param num Index of item to return
  268. inline RTCP_SDES_ITEM *getItem(int num) {
  269. auto base = &_items;
  270. while (num-- > 0) {
  271. auto itemSize = RTCP_SDES_ITEM::size(base->length());
  272. base = reinterpret_cast<RTCP_SDES_ITEM *>(reinterpret_cast<uint8_t *>(base) + itemSize);
  273. }
  274. return reinterpret_cast<RTCP_SDES_ITEM *>(base);
  275. }
  276. long safelyCountChunkSize(size_t maxChunkSize) {
  277. if (maxChunkSize < RTCP_SDES_CHUNK::size({})) {
  278. // chunk is truncated
  279. return -1;
  280. } else {
  281. size_t size = sizeof(SSRC);
  282. unsigned int i = 0;
  283. // We can always access first 4 bytes of first item (in case of no items there will be 4
  284. // null bytes)
  285. auto item = getItem(i);
  286. std::vector<uint8_t> textsLength{};
  287. while (item->type != 0) {
  288. if (size + RTCP_SDES_ITEM::size(0) > maxChunkSize) {
  289. // item is too short
  290. return -1;
  291. }
  292. auto itemLength = item->length();
  293. if (size + RTCP_SDES_ITEM::size(itemLength) >= maxChunkSize) {
  294. // item is too large (it can't be equal to chunk size because after item there
  295. // must be 1-4 null bytes as padding)
  296. return -1;
  297. }
  298. textsLength.push_back(itemLength);
  299. // safely to access next item
  300. item = getItem(++i);
  301. }
  302. auto realSize = RTCP_SDES_CHUNK::size(textsLength);
  303. if (realSize > maxChunkSize) {
  304. // Chunk is too large
  305. return -1;
  306. }
  307. return realSize;
  308. }
  309. }
  310. [[nodiscard]] static unsigned int size(const std::vector<uint8_t> textLengths) {
  311. unsigned int itemsSize = 0;
  312. for (auto length : textLengths) {
  313. itemsSize += RTCP_SDES_ITEM::size(length);
  314. }
  315. auto nullTerminatedItemsSize = itemsSize + 1;
  316. auto words = uint8_t(std::ceil(double(nullTerminatedItemsSize) / 4)) + 1;
  317. return words * 4;
  318. }
  319. /// Get size of chunk
  320. /// @note All items must be valid, otherwise this function has undefined behaviour (use
  321. /// `safelyCountChunkSize` to check if chunk is valid)
  322. [[nodiscard]] unsigned int getSize() {
  323. std::vector<uint8_t> textLengths{};
  324. unsigned int i = 0;
  325. auto item = getItem(i);
  326. while (item->type != 0) {
  327. textLengths.push_back(item->length());
  328. item = getItem(++i);
  329. }
  330. return size(textLengths);
  331. }
  332. };
  333. struct RTCP_SDES {
  334. RTCP_HEADER header;
  335. private:
  336. RTCP_SDES_CHUNK _chunks;
  337. public:
  338. inline void preparePacket(uint8_t chunkCount) {
  339. unsigned int chunkSize = 0;
  340. for (uint8_t i = 0; i < chunkCount; i++) {
  341. auto chunk = getChunk(i);
  342. chunkSize += chunk->getSize();
  343. }
  344. uint16_t length = uint16_t((sizeof(header) + chunkSize) / 4 - 1);
  345. header.prepareHeader(202, chunkCount, length);
  346. }
  347. bool isValid() {
  348. auto chunksSize = header.lengthInBytes() - sizeof(header);
  349. if (chunksSize == 0) {
  350. return true;
  351. } else {
  352. // there is at least one chunk
  353. unsigned int i = 0;
  354. unsigned int size = 0;
  355. while (size < chunksSize) {
  356. if (chunksSize < size + RTCP_SDES_CHUNK::size({})) {
  357. // chunk is truncated
  358. return false;
  359. }
  360. auto chunk = getChunk(i++);
  361. auto chunkSize = chunk->safelyCountChunkSize(chunksSize - size);
  362. if (chunkSize < 0) {
  363. // chunk is invalid
  364. return false;
  365. }
  366. size += chunkSize;
  367. }
  368. return size == chunksSize;
  369. }
  370. }
  371. /// Returns number of chunks in this packet
  372. /// @note Returns 0 if packet is invalid
  373. inline unsigned int chunksCount() {
  374. if (!isValid()) {
  375. return 0;
  376. }
  377. uint16_t chunksSize = 4 * (header.length() + 1) - sizeof(header);
  378. unsigned int size = 0;
  379. unsigned int i = 0;
  380. while (size < chunksSize) {
  381. size += getChunk(i++)->getSize();
  382. }
  383. return i;
  384. }
  385. /// Get chunk at given index
  386. /// @note All chunks (and their items) with index < `num` must be valid, otherwise this function
  387. /// has undefined behaviour (use `isValid` to check if chunk is valid)
  388. /// @param num Index of chunk to return
  389. inline RTCP_SDES_CHUNK *getChunk(int num) {
  390. auto base = &_chunks;
  391. while (num-- > 0) {
  392. auto chunkSize = base->getSize();
  393. base =
  394. reinterpret_cast<RTCP_SDES_CHUNK *>(reinterpret_cast<uint8_t *>(base) + chunkSize);
  395. }
  396. return reinterpret_cast<RTCP_SDES_CHUNK *>(base);
  397. }
  398. [[nodiscard]] static unsigned int size(const std::vector<std::vector<uint8_t>> lengths) {
  399. unsigned int chunks_size = 0;
  400. for (auto length : lengths) {
  401. chunks_size += RTCP_SDES_CHUNK::size(length);
  402. }
  403. return 4 + chunks_size;
  404. }
  405. };
  406. struct RTCP_RR {
  407. RTCP_HEADER header;
  408. SSRC _senderSSRC;
  409. private:
  410. RTCP_ReportBlock _reportBlocks;
  411. public:
  412. [[nodiscard]] inline RTCP_ReportBlock *getReportBlock(int num) { return &_reportBlocks + num; }
  413. [[nodiscard]] inline const RTCP_ReportBlock *getReportBlock(int num) const {
  414. return &_reportBlocks + num;
  415. }
  416. inline SSRC senderSSRC() const { return ntohl(_senderSSRC); }
  417. inline void setSenderSSRC(SSRC ssrc) { this->_senderSSRC = htonl(ssrc); }
  418. [[nodiscard]] inline size_t getSize() const {
  419. // "length" in packet is one less than the number of 32 bit words in the packet.
  420. return sizeof(uint32_t) * (1 + size_t(header.length()));
  421. }
  422. inline void preparePacket(SSRC senderSSRC, uint8_t reportCount) {
  423. // "length" in packet is one less than the number of 32 bit words in the packet.
  424. size_t length = (sizeWithReportBlocks(reportCount) / 4) - 1;
  425. header.prepareHeader(201, reportCount, uint16_t(length));
  426. this->_senderSSRC = htonl(senderSSRC);
  427. }
  428. inline static size_t sizeWithReportBlocks(uint8_t reportCount) {
  429. return sizeof(header) + 4 + size_t(reportCount) * sizeof(RTCP_ReportBlock);
  430. }
  431. inline bool isSenderReport() { return header.payloadType() == 200; }
  432. inline bool isReceiverReport() { return header.payloadType() == 201; }
  433. inline void log() const {
  434. header.log();
  435. PLOG_VERBOSE << "RTCP RR: "
  436. << " SSRC=" << ntohl(_senderSSRC);
  437. for (unsigned i = 0; i < unsigned(header.reportCount()); i++) {
  438. getReportBlock(i)->log();
  439. }
  440. }
  441. };
  442. struct RTCP_REMB {
  443. RTCP_FB_HEADER header;
  444. /*! \brief Unique identifier ('R' 'E' 'M' 'B') */
  445. char id[4];
  446. /*! \brief Num SSRC, Br Exp, Br Mantissa (bit mask) */
  447. uint32_t bitrate;
  448. SSRC ssrc[1];
  449. [[nodiscard]] unsigned int getSize() const {
  450. // "length" in packet is one less than the number of 32 bit words in the packet.
  451. return sizeof(uint32_t) * (1 + header.header.length());
  452. }
  453. void preparePacket(SSRC senderSSRC, unsigned int numSSRC, unsigned int in_bitrate) {
  454. // Report Count becomes the format here.
  455. header.header.prepareHeader(206, 15, 0);
  456. // Always zero.
  457. header.setMediaSourceSSRC(0);
  458. header.setPacketSenderSSRC(senderSSRC);
  459. id[0] = 'R';
  460. id[1] = 'E';
  461. id[2] = 'M';
  462. id[3] = 'B';
  463. setBitrate(numSSRC, in_bitrate);
  464. }
  465. void setBitrate(unsigned int numSSRC, unsigned int in_bitrate) {
  466. unsigned int exp = 0;
  467. while (in_bitrate > pow(2, 18) - 1) {
  468. exp++;
  469. in_bitrate /= 2;
  470. }
  471. // "length" in packet is one less than the number of 32 bit words in the packet.
  472. header.header.setLength(
  473. uint16_t((offsetof(RTCP_REMB, ssrc) / sizeof(uint32_t)) - 1 + numSSRC));
  474. this->bitrate = htonl((numSSRC << (32u - 8u)) | (exp << (32u - 8u - 6u)) | in_bitrate);
  475. }
  476. void setSsrc(int iterator, SSRC newSssrc) { ssrc[iterator] = htonl(newSssrc); }
  477. size_t static inline sizeWithSSRCs(int count) {
  478. return sizeof(RTCP_REMB) + (count - 1) * sizeof(SSRC);
  479. }
  480. };
  481. struct RTCP_PLI {
  482. RTCP_FB_HEADER header;
  483. void preparePacket(SSRC messageSSRC) {
  484. header.header.prepareHeader(206, 1, 2);
  485. header.setPacketSenderSSRC(messageSSRC);
  486. header.setMediaSourceSSRC(messageSSRC);
  487. }
  488. void print() { header.log(); }
  489. [[nodiscard]] static unsigned int size() { return sizeof(RTCP_FB_HEADER); }
  490. };
  491. struct RTCP_FIR_PART {
  492. uint32_t ssrc;
  493. uint8_t seqNo;
  494. uint8_t dummy1;
  495. uint16_t dummy2;
  496. };
  497. struct RTCP_FIR {
  498. RTCP_FB_HEADER header;
  499. RTCP_FIR_PART parts[1];
  500. void preparePacket(SSRC messageSSRC, uint8_t seqNo) {
  501. header.header.prepareHeader(206, 4, 2 + 2 * 1);
  502. header.setPacketSenderSSRC(messageSSRC);
  503. header.setMediaSourceSSRC(messageSSRC);
  504. parts[0].ssrc = htonl(messageSSRC);
  505. parts[0].seqNo = seqNo;
  506. }
  507. void print() { header.log(); }
  508. [[nodiscard]] static unsigned int size() {
  509. return sizeof(RTCP_FB_HEADER) + sizeof(RTCP_FIR_PART);
  510. }
  511. };
  512. struct RTCP_NACK_PART {
  513. uint16_t _pid;
  514. uint16_t _blp;
  515. uint16_t getPID() { return ntohs(_pid); }
  516. uint16_t getBLP() { return ntohs(_blp); }
  517. void setPID(uint16_t pid) { _pid = htons(pid); }
  518. void setBLP(uint16_t blp) { _blp = htons(blp); }
  519. std::vector<uint16_t> getSequenceNumbers() {
  520. std::vector<uint16_t> result{};
  521. result.reserve(17);
  522. uint16_t pid = getPID();
  523. result.push_back(pid);
  524. uint16_t bitmask = getBLP();
  525. uint16_t i = pid + 1;
  526. while (bitmask > 0) {
  527. if (bitmask & 0x1) {
  528. result.push_back(i);
  529. }
  530. i += 1;
  531. bitmask >>= 1;
  532. }
  533. return result;
  534. }
  535. };
  536. class RTCP_NACK {
  537. public:
  538. RTCP_FB_HEADER header;
  539. RTCP_NACK_PART parts[1];
  540. public:
  541. void preparePacket(SSRC ssrc, unsigned int discreteSeqNoCount) {
  542. header.header.prepareHeader(205, 1, 2 + uint16_t(discreteSeqNoCount));
  543. header.setMediaSourceSSRC(ssrc);
  544. header.setPacketSenderSSRC(ssrc);
  545. }
  546. /**
  547. * Add a packet to the list of missing packets.
  548. * @param fciCount The number of FCI fields that are present in this packet.
  549. * Let the number start at zero and let this function grow the number.
  550. * @param fciPID The seq no of the active FCI. It will be initialized automatically, and will
  551. * change automatically.
  552. * @param missingPacket The seq no of the missing packet. This will be added to the queue.
  553. * @return true if the packet has grown, false otherwise.
  554. */
  555. bool addMissingPacket(unsigned int *fciCount, uint16_t *fciPID, uint16_t missingPacket) {
  556. if (*fciCount == 0 || missingPacket < *fciPID || missingPacket > (*fciPID + 16)) {
  557. parts[*fciCount].setPID(missingPacket);
  558. parts[*fciCount].setBLP(0);
  559. *fciPID = missingPacket;
  560. (*fciCount)++;
  561. return true;
  562. } else {
  563. // TODO SPEED!
  564. uint16_t blp = parts[(*fciCount) - 1].getBLP();
  565. uint16_t newBit = uint16_t(1u << (missingPacket - (1 + *fciPID)));
  566. parts[(*fciCount) - 1].setBLP(blp | newBit);
  567. return false;
  568. }
  569. }
  570. [[nodiscard]] static unsigned int getSize(unsigned int discreteSeqNoCount) {
  571. return offsetof(RTCP_NACK, parts) + sizeof(RTCP_NACK_PART) * discreteSeqNoCount;
  572. }
  573. [[nodiscard]] unsigned int getSeqNoCount() { return header.header.length() - 2; }
  574. };
  575. class RTP_RTX {
  576. private:
  577. RTP header;
  578. public:
  579. size_t copyTo(RTP *dest, size_t totalSize, uint8_t originalPayloadType) {
  580. memmove((char *)dest, (char *)this, header.getSize());
  581. dest->setSeqNumber(getOriginalSeqNo());
  582. dest->setPayloadType(originalPayloadType);
  583. memmove(dest->getBody(), getBody(), getBodySize(totalSize));
  584. return totalSize;
  585. }
  586. [[nodiscard]] uint16_t getOriginalSeqNo() const {
  587. return ntohs(*(uint16_t *)(header.getBody()));
  588. }
  589. [[nodiscard]] char *getBody() { return header.getBody() + sizeof(uint16_t); }
  590. [[nodiscard]] const char *getBody() const { return header.getBody() + sizeof(uint16_t); }
  591. [[nodiscard]] size_t getBodySize(size_t totalSize) {
  592. return totalSize - (getBody() - reinterpret_cast<char *>(this));
  593. }
  594. [[nodiscard]] size_t getSize() const{
  595. return header.getSize() + sizeof(uint16_t);
  596. }
  597. [[nodiscard]] RTP &getHeader() { return header; }
  598. /*
  599. * Returns the new size of the packet
  600. */
  601. size_t normalizePacket(size_t totalSize, SSRC originalSSRC, uint8_t originalPayloadType) {
  602. header.setSeqNumber(getOriginalSeqNo());
  603. header.setSsrc(originalSSRC);
  604. header.setPayloadType(originalPayloadType);
  605. // TODO, the -12 is the size of the header (which is variable!)
  606. memmove(header.getBody(), getBody(), totalSize - getSize());
  607. return totalSize - 2;
  608. }
  609. };
  610. #pragma pack(pop)
  611. }; // namespace rtc
  612. #endif