rtp.hpp 16 KB

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