rtp.hpp 16 KB

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