rtp.hpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /**
  2. * Copyright (c) 2020 Staz Modrzynski
  3. * Copyright (c) 2020 Paul-Louis Ageneau
  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. #ifndef RTC_RTP_HPP
  20. #define RTC_RTP_HPP
  21. #include "log.hpp"
  22. #include <cmath>
  23. #ifdef _WIN32
  24. #include <winsock2.h>
  25. #else
  26. #include <arpa/inet.h>
  27. #endif
  28. #ifndef htonll
  29. #define htonll(x) \
  30. ((uint64_t)htonl(((uint64_t)(x)&0xFFFFFFFF) << 32) | (uint64_t)htonl((uint64_t)(x) >> 32))
  31. #endif
  32. #ifndef ntohll
  33. #define ntohll(x) htonll(x)
  34. #endif
  35. namespace rtc {
  36. typedef uint32_t SSRC;
  37. #pragma pack(push, 1)
  38. struct RTP {
  39. private:
  40. uint8_t _first;
  41. uint8_t _payloadType;
  42. uint16_t _seqNumber;
  43. uint32_t _timestamp;
  44. SSRC _ssrc;
  45. public:
  46. SSRC csrc[16];
  47. inline uint8_t version() const { return _first >> 6; }
  48. inline bool padding() const { return (_first >> 5) & 0x01; }
  49. inline bool extension() const { return (_first >> 4) & 0x01; }
  50. inline uint8_t csrcCount() const { return _first & 0x0F; }
  51. inline uint8_t marker() const { return _payloadType & 0b10000000; }
  52. inline uint8_t payloadType() const { return _payloadType & 0b01111111; }
  53. inline uint16_t seqNumber() const { return ntohs(_seqNumber); }
  54. inline uint32_t timestamp() const { return ntohl(_timestamp); }
  55. inline uint32_t ssrc() const { return ntohl(_ssrc); }
  56. inline size_t getSize() const {
  57. return reinterpret_cast<const char *>(&csrc) - reinterpret_cast<const char *>(this) +
  58. sizeof(SSRC) * csrcCount();
  59. }
  60. [[nodiscard]] char *getBody() {
  61. return reinterpret_cast<char *>(&csrc) + sizeof(SSRC) * csrcCount();
  62. }
  63. [[nodiscard]] const char *getBody() const {
  64. return reinterpret_cast<const char *>(&csrc) + sizeof(SSRC) * csrcCount();
  65. }
  66. inline void setSeqNumber(uint16_t newSeqNo) { _seqNumber = htons(newSeqNo); }
  67. inline void setPayloadType(uint8_t newPayloadType) {
  68. _payloadType = (_payloadType & 0b10000000u) | (0b01111111u & newPayloadType);
  69. }
  70. inline void setSsrc(uint32_t in_ssrc) { _ssrc = htonl(in_ssrc); }
  71. void setTimestamp(uint32_t i) { _timestamp = htonl(i); }
  72. void log() {
  73. PLOG_VERBOSE << "RTP V: " << (int)version() << " P: " << (padding() ? "P" : " ")
  74. << " X: " << (extension() ? "X" : " ") << " CC: " << (int)csrcCount()
  75. << " M: " << (marker() ? "M" : " ") << " PT: " << (int)payloadType()
  76. << " SEQNO: " << seqNumber() << " TS: " << timestamp();
  77. }
  78. };
  79. struct RTCP_ReportBlock {
  80. SSRC ssrc;
  81. private:
  82. uint32_t _fractionLostAndPacketsLost; // fraction lost is 8-bit, packets lost is 24-bit
  83. uint16_t _seqNoCycles;
  84. uint16_t _highestSeqNo;
  85. uint32_t _jitter;
  86. uint32_t _lastReport;
  87. uint32_t _delaySinceLastReport;
  88. public:
  89. inline void preparePacket(SSRC in_ssrc, [[maybe_unused]] unsigned int packetsLost,
  90. [[maybe_unused]] unsigned int totalPackets, uint16_t highestSeqNo,
  91. uint16_t seqNoCycles, uint32_t jitter, uint64_t lastSR_NTP,
  92. uint64_t lastSR_DELAY) {
  93. setSeqNo(highestSeqNo, seqNoCycles);
  94. setJitter(jitter);
  95. setSSRC(in_ssrc);
  96. // Middle 32 bits of NTP Timestamp
  97. // this->lastReport = lastSR_NTP >> 16u;
  98. setNTPOfSR(uint64_t(lastSR_NTP));
  99. setDelaySinceSR(uint32_t(lastSR_DELAY));
  100. // The delay, expressed in units of 1/65536 seconds
  101. // this->delaySinceLastReport = lastSR_DELAY;
  102. }
  103. inline void setSSRC(SSRC in_ssrc) { this->ssrc = htonl(in_ssrc); }
  104. [[nodiscard]] inline SSRC getSSRC() const { return ntohl(ssrc); }
  105. inline void setPacketsLost([[maybe_unused]] unsigned int packetsLost,
  106. [[maybe_unused]] unsigned int totalPackets) {
  107. // TODO Implement loss percentages.
  108. _fractionLostAndPacketsLost = 0;
  109. }
  110. [[nodiscard]] inline unsigned int getLossPercentage() const {
  111. // TODO Implement loss percentages.
  112. return 0;
  113. }
  114. [[nodiscard]] inline unsigned int getPacketLostCount() const {
  115. // TODO Implement total packets lost.
  116. return 0;
  117. }
  118. inline uint16_t seqNoCycles() const { return ntohs(_seqNoCycles); }
  119. inline uint16_t highestSeqNo() const { return ntohs(_highestSeqNo); }
  120. inline uint32_t jitter() const { return ntohl(_jitter); }
  121. inline void setSeqNo(uint16_t highestSeqNo, uint16_t seqNoCycles) {
  122. _highestSeqNo = htons(highestSeqNo);
  123. _seqNoCycles = htons(seqNoCycles);
  124. }
  125. inline void setJitter(uint32_t jitter) { _jitter = htonl(jitter); }
  126. inline void setNTPOfSR(uint64_t ntp) { _lastReport = htonll(ntp >> 16u); }
  127. [[nodiscard]] inline uint32_t getNTPOfSR() const { return ntohl(_lastReport) << 16u; }
  128. inline void setDelaySinceSR(uint32_t sr) {
  129. // The delay, expressed in units of 1/65536 seconds
  130. _delaySinceLastReport = htonl(sr);
  131. }
  132. [[nodiscard]] inline uint32_t getDelaySinceSR() const { return ntohl(_delaySinceLastReport); }
  133. inline void log() const {
  134. PLOG_VERBOSE << "RTCP report block: "
  135. << "ssrc="
  136. << ntohl(ssrc)
  137. // TODO: Implement these reports
  138. // << ", fractionLost=" << fractionLost
  139. // << ", packetsLost=" << packetsLost
  140. << ", highestSeqNo=" << highestSeqNo() << ", seqNoCycles=" << seqNoCycles()
  141. << ", jitter=" << jitter() << ", lastSR=" << getNTPOfSR()
  142. << ", lastSRDelay=" << getDelaySinceSR();
  143. }
  144. };
  145. struct RTCP_HEADER {
  146. private:
  147. uint8_t _first;
  148. uint8_t _payloadType;
  149. uint16_t _length;
  150. public:
  151. inline uint8_t version() const { return _first >> 6; }
  152. inline bool padding() const { return (_first >> 5) & 0x01; }
  153. inline uint8_t reportCount() const { return _first & 0x0F; }
  154. inline uint8_t payloadType() const { return _payloadType; }
  155. inline uint16_t length() const { return ntohs(_length); }
  156. inline size_t lengthInBytes() const { return (1 + length()) * 4; }
  157. inline void setPayloadType(uint8_t type) { _payloadType = type; }
  158. inline void setReportCount(uint8_t count) {
  159. _first = (_first & 0b11100000u) | (count & 0b00011111u);
  160. }
  161. inline void setLength(uint16_t length) { _length = htons(length); }
  162. inline void prepareHeader(uint8_t payloadType, uint8_t reportCount, uint16_t length) {
  163. _first = 0b10000000; // version 2, no padding
  164. setReportCount(reportCount);
  165. setPayloadType(payloadType);
  166. setLength(length);
  167. }
  168. inline void log() const {
  169. PLOG_VERBOSE << "RTCP header: "
  170. << "version=" << unsigned(version()) << ", padding=" << padding()
  171. << ", reportCount=" << unsigned(reportCount())
  172. << ", payloadType=" << unsigned(payloadType()) << ", length=" << length();
  173. }
  174. };
  175. struct RTCP_FB_HEADER {
  176. RTCP_HEADER header;
  177. SSRC packetSender;
  178. SSRC mediaSource;
  179. [[nodiscard]] SSRC getPacketSenderSSRC() const { return ntohl(packetSender); }
  180. [[nodiscard]] SSRC getMediaSourceSSRC() const { return ntohl(mediaSource); }
  181. void setPacketSenderSSRC(SSRC ssrc) { this->packetSender = htonl(ssrc); }
  182. void setMediaSourceSSRC(SSRC ssrc) { this->mediaSource = htonl(ssrc); }
  183. void log() {
  184. header.log();
  185. PLOG_VERBOSE << "FB: "
  186. << " packet sender: " << getPacketSenderSSRC()
  187. << " media source: " << getMediaSourceSSRC();
  188. }
  189. };
  190. struct RTCP_SR {
  191. RTCP_HEADER header;
  192. SSRC _senderSSRC;
  193. private:
  194. uint64_t _ntpTimestamp;
  195. uint32_t _rtpTimestamp;
  196. uint32_t _packetCount;
  197. uint32_t _octetCount;
  198. RTCP_ReportBlock _reportBlocks;
  199. public:
  200. inline void preparePacket(SSRC senderSSRC, uint8_t reportCount) {
  201. unsigned int length =
  202. ((sizeof(header) + 24 + reportCount * sizeof(RTCP_ReportBlock)) / 4) - 1;
  203. header.prepareHeader(200, reportCount, uint16_t(length));
  204. this->_senderSSRC = htonl(senderSSRC);
  205. }
  206. [[nodiscard]] inline RTCP_ReportBlock *getReportBlock(int num) { return &_reportBlocks + num; }
  207. [[nodiscard]] inline const RTCP_ReportBlock *getReportBlock(int num) const {
  208. return &_reportBlocks + num;
  209. }
  210. [[nodiscard]] inline size_t getSize() const {
  211. // "length" in packet is one less than the number of 32 bit words in the packet.
  212. return sizeof(uint32_t) * (1 + size_t(header.length()));
  213. }
  214. inline uint64_t ntpTimestamp() const { return ntohll(_ntpTimestamp); }
  215. inline uint32_t rtpTimestamp() const { return ntohl(_rtpTimestamp); }
  216. inline uint32_t packetCount() const { return ntohl(_packetCount); }
  217. inline uint32_t octetCount() const { return ntohl(_octetCount); }
  218. inline uint32_t senderSSRC() const { return ntohl(_senderSSRC); }
  219. inline void setNtpTimestamp(uint32_t ts) { _ntpTimestamp = htonll(ts); }
  220. inline void setRtpTimestamp(uint32_t ts) { _rtpTimestamp = htonl(ts); }
  221. inline void log() const {
  222. header.log();
  223. PLOG_VERBOSE << "RTCP SR: "
  224. << " SSRC=" << senderSSRC() << ", NTP_TS=" << ntpTimestamp()
  225. << ", RTP_TS=" << rtpTimestamp() << ", packetCount=" << packetCount()
  226. << ", octetCount=" << octetCount();
  227. for (unsigned i = 0; i < unsigned(header.reportCount()); i++) {
  228. getReportBlock(i)->log();
  229. }
  230. }
  231. };
  232. struct RTCP_RR {
  233. RTCP_HEADER header;
  234. SSRC _senderSSRC;
  235. private:
  236. RTCP_ReportBlock _reportBlocks;
  237. public:
  238. [[nodiscard]] inline RTCP_ReportBlock *getReportBlock(int num) { return &_reportBlocks + num; }
  239. [[nodiscard]] inline const RTCP_ReportBlock *getReportBlock(int num) const {
  240. return &_reportBlocks + num;
  241. }
  242. inline SSRC senderSSRC() const { return ntohl(_senderSSRC); }
  243. inline void setSenderSSRC(SSRC ssrc) { this->_senderSSRC = htonl(ssrc); }
  244. [[nodiscard]] inline size_t getSize() const {
  245. // "length" in packet is one less than the number of 32 bit words in the packet.
  246. return sizeof(uint32_t) * (1 + size_t(header.length()));
  247. }
  248. inline void preparePacket(SSRC senderSSRC, uint8_t reportCount) {
  249. // "length" in packet is one less than the number of 32 bit words in the packet.
  250. size_t length = (sizeWithReportBlocks(reportCount) / 4) - 1;
  251. header.prepareHeader(201, reportCount, uint16_t(length));
  252. this->_senderSSRC = htonl(senderSSRC);
  253. }
  254. inline static size_t sizeWithReportBlocks(uint8_t reportCount) {
  255. return sizeof(header) + 4 + size_t(reportCount) * sizeof(RTCP_ReportBlock);
  256. }
  257. inline bool isSenderReport() { return header.payloadType() == 200; }
  258. inline bool isReceiverReport() { return header.payloadType() == 201; }
  259. inline void log() const {
  260. header.log();
  261. PLOG_VERBOSE << "RTCP RR: "
  262. << " SSRC=" << ntohl(_senderSSRC);
  263. for (unsigned i = 0; i < unsigned(header.reportCount()); i++) {
  264. getReportBlock(i)->log();
  265. }
  266. }
  267. };
  268. struct RTCP_REMB {
  269. RTCP_FB_HEADER header;
  270. /*! \brief Unique identifier ('R' 'E' 'M' 'B') */
  271. char id[4];
  272. /*! \brief Num SSRC, Br Exp, Br Mantissa (bit mask) */
  273. uint32_t bitrate;
  274. SSRC ssrc[1];
  275. [[nodiscard]] unsigned int getSize() const {
  276. // "length" in packet is one less than the number of 32 bit words in the packet.
  277. return sizeof(uint32_t) * (1 + header.header.length());
  278. }
  279. void preparePacket(SSRC senderSSRC, unsigned int numSSRC, unsigned int in_bitrate) {
  280. // Report Count becomes the format here.
  281. header.header.prepareHeader(206, 15, 0);
  282. // Always zero.
  283. header.setMediaSourceSSRC(0);
  284. header.setPacketSenderSSRC(senderSSRC);
  285. id[0] = 'R';
  286. id[1] = 'E';
  287. id[2] = 'M';
  288. id[3] = 'B';
  289. setBitrate(numSSRC, in_bitrate);
  290. }
  291. void setBitrate(unsigned int numSSRC, unsigned int in_bitrate) {
  292. unsigned int exp = 0;
  293. while (in_bitrate > pow(2, 18) - 1) {
  294. exp++;
  295. in_bitrate /= 2;
  296. }
  297. // "length" in packet is one less than the number of 32 bit words in the packet.
  298. header.header.setLength(
  299. uint16_t((offsetof(RTCP_REMB, ssrc) / sizeof(uint32_t)) - 1 + numSSRC));
  300. this->bitrate = htonl((numSSRC << (32u - 8u)) | (exp << (32u - 8u - 6u)) | in_bitrate);
  301. }
  302. void setSsrc(int iterator, SSRC newSssrc) { ssrc[iterator] = htonl(newSssrc); }
  303. size_t static inline sizeWithSSRCs(int count) {
  304. return sizeof(RTCP_REMB) + (count - 1) * sizeof(SSRC);
  305. }
  306. };
  307. struct RTCP_PLI {
  308. RTCP_FB_HEADER header;
  309. void preparePacket(SSRC messageSSRC) {
  310. header.header.prepareHeader(206, 1, 2);
  311. header.setPacketSenderSSRC(messageSSRC);
  312. header.setMediaSourceSSRC(messageSSRC);
  313. }
  314. void print() { header.log(); }
  315. [[nodiscard]] static unsigned int size() { return sizeof(RTCP_FB_HEADER); }
  316. };
  317. struct RTCP_FIR_PART {
  318. uint32_t ssrc;
  319. uint8_t seqNo;
  320. uint8_t dummy1;
  321. uint16_t dummy2;
  322. };
  323. struct RTCP_FIR {
  324. RTCP_FB_HEADER header;
  325. RTCP_FIR_PART parts[1];
  326. void preparePacket(SSRC messageSSRC, uint8_t seqNo) {
  327. header.header.prepareHeader(206, 4, 2 + 2 * 1);
  328. header.setPacketSenderSSRC(messageSSRC);
  329. header.setMediaSourceSSRC(messageSSRC);
  330. parts[0].ssrc = htonl(messageSSRC);
  331. parts[0].seqNo = seqNo;
  332. }
  333. void print() { header.log(); }
  334. [[nodiscard]] static unsigned int size() {
  335. return sizeof(RTCP_FB_HEADER) + sizeof(RTCP_FIR_PART);
  336. }
  337. };
  338. struct RTCP_NACK_PART {
  339. uint16_t pid;
  340. uint16_t blp;
  341. };
  342. class RTCP_NACK {
  343. public:
  344. RTCP_FB_HEADER header;
  345. RTCP_NACK_PART parts[1];
  346. public:
  347. void preparePacket(SSRC ssrc, unsigned int discreteSeqNoCount) {
  348. header.header.prepareHeader(205, 1, 2 + uint16_t(discreteSeqNoCount));
  349. header.setMediaSourceSSRC(ssrc);
  350. header.setPacketSenderSSRC(ssrc);
  351. }
  352. /**
  353. * Add a packet to the list of missing packets.
  354. * @param fciCount The number of FCI fields that are present in this packet.
  355. * Let the number start at zero and let this function grow the number.
  356. * @param fciPID The seq no of the active FCI. It will be initialized automatically, and will
  357. * change automatically.
  358. * @param missingPacket The seq no of the missing packet. This will be added to the queue.
  359. * @return true if the packet has grown, false otherwise.
  360. */
  361. bool addMissingPacket(unsigned int *fciCount, uint16_t *fciPID, uint16_t missingPacket) {
  362. if (*fciCount == 0 || missingPacket < *fciPID || missingPacket > (*fciPID + 16)) {
  363. parts[*fciCount].pid = htons(missingPacket);
  364. parts[*fciCount].blp = 0;
  365. *fciPID = missingPacket;
  366. (*fciCount)++;
  367. return true;
  368. } else {
  369. // TODO SPEEED!
  370. auto blp = ntohs(parts[(*fciCount) - 1].blp);
  371. auto newBit = 1u << (unsigned int)(missingPacket - (1 + *fciPID));
  372. parts[(*fciCount) - 1].blp = htons(blp | newBit);
  373. return false;
  374. }
  375. }
  376. [[nodiscard]] static unsigned int getSize(unsigned int discreteSeqNoCount) {
  377. return offsetof(RTCP_NACK, parts) + sizeof(RTCP_NACK_PART) * discreteSeqNoCount;
  378. }
  379. [[nodiscard]] unsigned int getSeqNoCount() { return header.header.length() - 2; }
  380. };
  381. class RTP_RTX {
  382. private:
  383. RTP header;
  384. public:
  385. size_t copyTo(RTP *dest, size_t totalSize, uint8_t originalPayloadType) {
  386. memmove((char *)dest, (char *)this, header.getSize());
  387. dest->setSeqNumber(getOriginalSeqNo());
  388. dest->setPayloadType(originalPayloadType);
  389. memmove(dest->getBody(), getBody(), getBodySize(totalSize));
  390. return totalSize;
  391. }
  392. [[nodiscard]] uint16_t getOriginalSeqNo() const {
  393. return ntohs(*(uint16_t *)(header.getBody()));
  394. }
  395. [[nodiscard]] char *getBody() { return header.getBody() + sizeof(uint16_t); }
  396. [[nodiscard]] const char *getBody() const { return header.getBody() + sizeof(uint16_t); }
  397. [[nodiscard]] size_t getBodySize(size_t totalSize) {
  398. return totalSize - (getBody() - reinterpret_cast<char *>(this));
  399. }
  400. [[nodiscard]] RTP &getHeader() { return header; }
  401. size_t normalizePacket(size_t totalSize, SSRC originalSSRC, uint8_t originalPayloadType) {
  402. header.setSeqNumber(getOriginalSeqNo());
  403. header.setSsrc(originalSSRC);
  404. header.setPayloadType(originalPayloadType);
  405. // TODO, the -12 is the size of the header (which is variable!)
  406. memmove(header.getBody(), header.getBody() + sizeof(uint16_t),
  407. totalSize - 12 - sizeof(uint16_t));
  408. return totalSize - sizeof(uint16_t);
  409. }
  410. };
  411. #pragma pack(pop)
  412. }; // namespace rtc
  413. #endif