rtp.hpp 17 KB

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