rtp.hpp 15 KB

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