rtp.hpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  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)htonl(((uint64_t)(x)&0xFFFFFFFF) << 32) | (uint64_t)htonl((uint64_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;
  246. public:
  247. inline std::string text() const { return std::string(&_text, _length); }
  248. inline void setText(std::string text) {
  249. _length = text.length();
  250. memcpy(&_text, text.data(), _length);
  251. }
  252. inline uint8_t length() { return _length; }
  253. [[nodiscard]] static unsigned int size(uint8_t textLength) { return textLength + 2; }
  254. };
  255. struct RTCP_SDES_CHUNK {
  256. private:
  257. SSRC _ssrc;
  258. RTCP_SDES_ITEM _items;
  259. public:
  260. inline SSRC ssrc() const { return ntohl(_ssrc); }
  261. inline void setSSRC(SSRC ssrc) { _ssrc = htonl(ssrc); }
  262. /// Get item at given index
  263. /// @note All items with index < `num` must be valid, otherwise this function has undefined
  264. /// behaviour (use `safelyCountChunkSize` to check if chunk is valid)
  265. /// @param num Index of item to return
  266. inline RTCP_SDES_ITEM *getItem(int num) {
  267. auto base = &_items;
  268. while (num-- > 0) {
  269. auto itemSize = RTCP_SDES_ITEM::size(base->length());
  270. base = reinterpret_cast<RTCP_SDES_ITEM *>(reinterpret_cast<uint8_t *>(base) + itemSize);
  271. }
  272. return reinterpret_cast<RTCP_SDES_ITEM *>(base);
  273. }
  274. long safelyCountChunkSize(unsigned int maxChunkSize) {
  275. if (maxChunkSize < RTCP_SDES_CHUNK::size({})) {
  276. // chunk is truncated
  277. return -1;
  278. } else {
  279. unsigned int size = sizeof(SSRC);
  280. unsigned int i = 0;
  281. // We can always access first 4 bytes of first item (in case of no items there will be 4
  282. // null bytes)
  283. auto item = getItem(i);
  284. std::vector<uint8_t> textsLength{};
  285. while (item->type != 0) {
  286. if (size + RTCP_SDES_ITEM::size(0) > maxChunkSize) {
  287. // item is too short
  288. return -1;
  289. }
  290. auto itemLength = item->length();
  291. if (size + RTCP_SDES_ITEM::size(itemLength) >= maxChunkSize) {
  292. // item is too large (it can't be equal to chunk size because after item there
  293. // must be 1-4 null bytes as padding)
  294. return -1;
  295. }
  296. textsLength.push_back(itemLength);
  297. // safely to access next item
  298. item = getItem(++i);
  299. }
  300. auto realSize = RTCP_SDES_CHUNK::size(textsLength);
  301. if (realSize > maxChunkSize) {
  302. // Chunk is too large
  303. return -1;
  304. }
  305. return realSize;
  306. }
  307. }
  308. [[nodiscard]] static unsigned int size(const std::vector<uint8_t> textLengths) {
  309. unsigned int itemsSize = 0;
  310. for (auto length : textLengths) {
  311. itemsSize += RTCP_SDES_ITEM::size(length);
  312. }
  313. auto nullTerminatedItemsSize = itemsSize + 1;
  314. auto words = uint8_t(std::ceil(double(nullTerminatedItemsSize) / 4)) + 1;
  315. return words * 4;
  316. }
  317. /// Get size of chunk
  318. /// @note All items must be valid, otherwise this function has undefined behaviour (use
  319. /// `safelyCountChunkSize` to check if chunk is valid)
  320. [[nodiscard]] unsigned int getSize() {
  321. std::vector<uint8_t> textLengths{};
  322. unsigned int i = 0;
  323. auto item = getItem(i);
  324. while (item->type != 0) {
  325. textLengths.push_back(item->length());
  326. item = getItem(++i);
  327. }
  328. return size(textLengths);
  329. }
  330. };
  331. struct RTCP_SDES {
  332. RTCP_HEADER header;
  333. private:
  334. RTCP_SDES_CHUNK _chunks;
  335. public:
  336. inline void preparePacket(uint8_t chunkCount) {
  337. unsigned int chunkSize = 0;
  338. for (uint8_t i = 0; i < chunkCount; i++) {
  339. auto chunk = getChunk(i);
  340. chunkSize += chunk->getSize();
  341. }
  342. uint16_t length = (sizeof(header) + chunkSize) / 4 - 1;
  343. header.prepareHeader(202, chunkCount, length);
  344. }
  345. bool isValid() {
  346. auto chunksSize = header.lengthInBytes() - sizeof(header);
  347. if (chunksSize == 0) {
  348. return true;
  349. } else {
  350. // there is at least one chunk
  351. unsigned int i = 0;
  352. unsigned int size = 0;
  353. while (size < chunksSize) {
  354. if (chunksSize < size + RTCP_SDES_CHUNK::size({})) {
  355. // chunk is truncated
  356. return false;
  357. }
  358. auto chunk = getChunk(i++);
  359. auto chunkSize = chunk->safelyCountChunkSize(chunksSize - size);
  360. if (chunkSize < 0) {
  361. // chunk is invalid
  362. return false;
  363. }
  364. size += chunkSize;
  365. }
  366. return size == chunksSize;
  367. }
  368. }
  369. /// Returns number of chunks in this packet
  370. /// @note Returns 0 if packet is invalid
  371. inline unsigned int chunksCount() {
  372. if (!isValid()) {
  373. return 0;
  374. }
  375. uint16_t chunksSize = 4 * (header.length() + 1) - sizeof(header);
  376. unsigned int size = 0;
  377. unsigned int i = 0;
  378. while (size < chunksSize) {
  379. size += getChunk(i++)->getSize();
  380. }
  381. return i;
  382. }
  383. /// Get chunk at given index
  384. /// @note All chunks (and their items) with index < `num` must be valid, otherwise this function
  385. /// has undefined behaviour (use `isValid` to check if chunk is valid)
  386. /// @param num Index of chunk to return
  387. inline RTCP_SDES_CHUNK *getChunk(int num) {
  388. auto base = &_chunks;
  389. while (num-- > 0) {
  390. auto chunkSize = base->getSize();
  391. base =
  392. reinterpret_cast<RTCP_SDES_CHUNK *>(reinterpret_cast<uint8_t *>(base) + chunkSize);
  393. }
  394. return reinterpret_cast<RTCP_SDES_CHUNK *>(base);
  395. }
  396. [[nodiscard]] static unsigned int size(const std::vector<std::vector<uint8_t>> lengths) {
  397. unsigned int chunks_size = 0;
  398. for (auto length : lengths) {
  399. chunks_size += RTCP_SDES_CHUNK::size(length);
  400. }
  401. return 4 + chunks_size;
  402. }
  403. };
  404. struct RTCP_RR {
  405. RTCP_HEADER header;
  406. SSRC _senderSSRC;
  407. private:
  408. RTCP_ReportBlock _reportBlocks;
  409. public:
  410. [[nodiscard]] inline RTCP_ReportBlock *getReportBlock(int num) { return &_reportBlocks + num; }
  411. [[nodiscard]] inline const RTCP_ReportBlock *getReportBlock(int num) const {
  412. return &_reportBlocks + num;
  413. }
  414. inline SSRC senderSSRC() const { return ntohl(_senderSSRC); }
  415. inline void setSenderSSRC(SSRC ssrc) { this->_senderSSRC = htonl(ssrc); }
  416. [[nodiscard]] inline size_t getSize() const {
  417. // "length" in packet is one less than the number of 32 bit words in the packet.
  418. return sizeof(uint32_t) * (1 + size_t(header.length()));
  419. }
  420. inline void preparePacket(SSRC senderSSRC, uint8_t reportCount) {
  421. // "length" in packet is one less than the number of 32 bit words in the packet.
  422. size_t length = (sizeWithReportBlocks(reportCount) / 4) - 1;
  423. header.prepareHeader(201, reportCount, uint16_t(length));
  424. this->_senderSSRC = htonl(senderSSRC);
  425. }
  426. inline static size_t sizeWithReportBlocks(uint8_t reportCount) {
  427. return sizeof(header) + 4 + size_t(reportCount) * sizeof(RTCP_ReportBlock);
  428. }
  429. inline bool isSenderReport() { return header.payloadType() == 200; }
  430. inline bool isReceiverReport() { return header.payloadType() == 201; }
  431. inline void log() const {
  432. header.log();
  433. PLOG_VERBOSE << "RTCP RR: "
  434. << " SSRC=" << ntohl(_senderSSRC);
  435. for (unsigned i = 0; i < unsigned(header.reportCount()); i++) {
  436. getReportBlock(i)->log();
  437. }
  438. }
  439. };
  440. struct RTCP_REMB {
  441. RTCP_FB_HEADER header;
  442. /*! \brief Unique identifier ('R' 'E' 'M' 'B') */
  443. char id[4];
  444. /*! \brief Num SSRC, Br Exp, Br Mantissa (bit mask) */
  445. uint32_t bitrate;
  446. SSRC ssrc[1];
  447. [[nodiscard]] unsigned int getSize() const {
  448. // "length" in packet is one less than the number of 32 bit words in the packet.
  449. return sizeof(uint32_t) * (1 + header.header.length());
  450. }
  451. void preparePacket(SSRC senderSSRC, unsigned int numSSRC, unsigned int in_bitrate) {
  452. // Report Count becomes the format here.
  453. header.header.prepareHeader(206, 15, 0);
  454. // Always zero.
  455. header.setMediaSourceSSRC(0);
  456. header.setPacketSenderSSRC(senderSSRC);
  457. id[0] = 'R';
  458. id[1] = 'E';
  459. id[2] = 'M';
  460. id[3] = 'B';
  461. setBitrate(numSSRC, in_bitrate);
  462. }
  463. void setBitrate(unsigned int numSSRC, unsigned int in_bitrate) {
  464. unsigned int exp = 0;
  465. while (in_bitrate > pow(2, 18) - 1) {
  466. exp++;
  467. in_bitrate /= 2;
  468. }
  469. // "length" in packet is one less than the number of 32 bit words in the packet.
  470. header.header.setLength(
  471. uint16_t((offsetof(RTCP_REMB, ssrc) / sizeof(uint32_t)) - 1 + numSSRC));
  472. this->bitrate = htonl((numSSRC << (32u - 8u)) | (exp << (32u - 8u - 6u)) | in_bitrate);
  473. }
  474. void setSsrc(int iterator, SSRC newSssrc) { ssrc[iterator] = htonl(newSssrc); }
  475. size_t static inline sizeWithSSRCs(int count) {
  476. return sizeof(RTCP_REMB) + (count - 1) * sizeof(SSRC);
  477. }
  478. };
  479. struct RTCP_PLI {
  480. RTCP_FB_HEADER header;
  481. void preparePacket(SSRC messageSSRC) {
  482. header.header.prepareHeader(206, 1, 2);
  483. header.setPacketSenderSSRC(messageSSRC);
  484. header.setMediaSourceSSRC(messageSSRC);
  485. }
  486. void print() { header.log(); }
  487. [[nodiscard]] static unsigned int size() { return sizeof(RTCP_FB_HEADER); }
  488. };
  489. struct RTCP_FIR_PART {
  490. uint32_t ssrc;
  491. uint8_t seqNo;
  492. uint8_t dummy1;
  493. uint16_t dummy2;
  494. };
  495. struct RTCP_FIR {
  496. RTCP_FB_HEADER header;
  497. RTCP_FIR_PART parts[1];
  498. void preparePacket(SSRC messageSSRC, uint8_t seqNo) {
  499. header.header.prepareHeader(206, 4, 2 + 2 * 1);
  500. header.setPacketSenderSSRC(messageSSRC);
  501. header.setMediaSourceSSRC(messageSSRC);
  502. parts[0].ssrc = htonl(messageSSRC);
  503. parts[0].seqNo = seqNo;
  504. }
  505. void print() { header.log(); }
  506. [[nodiscard]] static unsigned int size() {
  507. return sizeof(RTCP_FB_HEADER) + sizeof(RTCP_FIR_PART);
  508. }
  509. };
  510. struct RTCP_NACK_PART {
  511. uint16_t _pid;
  512. uint16_t _blp;
  513. uint16_t getPID() { return ntohs(_pid); }
  514. uint16_t getBLP() { return ntohs(_blp); }
  515. void setPID(uint16_t pid) { _pid = htons(pid); }
  516. void setBLP(uint16_t blp) { _blp = htons(blp); }
  517. std::vector<uint16_t> getSequenceNumbers() {
  518. std::vector<uint16_t> result{};
  519. result.reserve(17);
  520. auto pid = getPID();
  521. result.push_back(pid);
  522. auto bitmask = getBLP();
  523. auto i = pid + 1;
  524. while (bitmask > 0) {
  525. if (bitmask & 0x1) {
  526. result.push_back(i);
  527. }
  528. i += 1;
  529. bitmask >>= 1;
  530. }
  531. return result;
  532. }
  533. };
  534. class RTCP_NACK {
  535. public:
  536. RTCP_FB_HEADER header;
  537. RTCP_NACK_PART parts[1];
  538. public:
  539. void preparePacket(SSRC ssrc, unsigned int discreteSeqNoCount) {
  540. header.header.prepareHeader(205, 1, 2 + uint16_t(discreteSeqNoCount));
  541. header.setMediaSourceSSRC(ssrc);
  542. header.setPacketSenderSSRC(ssrc);
  543. }
  544. /**
  545. * Add a packet to the list of missing packets.
  546. * @param fciCount The number of FCI fields that are present in this packet.
  547. * Let the number start at zero and let this function grow the number.
  548. * @param fciPID The seq no of the active FCI. It will be initialized automatically, and will
  549. * change automatically.
  550. * @param missingPacket The seq no of the missing packet. This will be added to the queue.
  551. * @return true if the packet has grown, false otherwise.
  552. */
  553. bool addMissingPacket(unsigned int *fciCount, uint16_t *fciPID, uint16_t missingPacket) {
  554. if (*fciCount == 0 || missingPacket < *fciPID || missingPacket > (*fciPID + 16)) {
  555. parts[*fciCount].setPID(missingPacket);
  556. parts[*fciCount].setBLP(0);
  557. *fciPID = missingPacket;
  558. (*fciCount)++;
  559. return true;
  560. } else {
  561. // TODO SPEEED!
  562. auto blp = parts[(*fciCount) - 1].getBLP();
  563. auto newBit = 1u << (unsigned int)(missingPacket - (1 + *fciPID));
  564. parts[(*fciCount) - 1].setBLP(blp | newBit);
  565. return false;
  566. }
  567. }
  568. [[nodiscard]] static unsigned int getSize(unsigned int discreteSeqNoCount) {
  569. return offsetof(RTCP_NACK, parts) + sizeof(RTCP_NACK_PART) * discreteSeqNoCount;
  570. }
  571. [[nodiscard]] unsigned int getSeqNoCount() { return header.header.length() - 2; }
  572. };
  573. class RTP_RTX {
  574. private:
  575. RTP header;
  576. public:
  577. size_t copyTo(RTP *dest, size_t totalSize, uint8_t originalPayloadType) {
  578. memmove((char *)dest, (char *)this, header.getSize());
  579. dest->setSeqNumber(getOriginalSeqNo());
  580. dest->setPayloadType(originalPayloadType);
  581. memmove(dest->getBody(), getBody(), getBodySize(totalSize));
  582. return totalSize;
  583. }
  584. [[nodiscard]] uint16_t getOriginalSeqNo() const {
  585. return ntohs(*(uint16_t *)(header.getBody()));
  586. }
  587. [[nodiscard]] char *getBody() { return header.getBody() + sizeof(uint16_t); }
  588. [[nodiscard]] const char *getBody() const { return header.getBody() + sizeof(uint16_t); }
  589. [[nodiscard]] size_t getBodySize(size_t totalSize) {
  590. return totalSize - (getBody() - reinterpret_cast<char *>(this));
  591. }
  592. [[nodiscard]] RTP &getHeader() { return header; }
  593. size_t normalizePacket(size_t totalSize, SSRC originalSSRC, uint8_t originalPayloadType) {
  594. header.setSeqNumber(getOriginalSeqNo());
  595. header.setSsrc(originalSSRC);
  596. header.setPayloadType(originalPayloadType);
  597. // TODO, the -12 is the size of the header (which is variable!)
  598. memmove(header.getBody(), header.getBody() + sizeof(uint16_t),
  599. totalSize - 12 - sizeof(uint16_t));
  600. return totalSize - sizeof(uint16_t);
  601. }
  602. };
  603. #pragma pack(pop)
  604. }; // namespace rtc
  605. #endif