forked from DDVTECH/mistserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtp.cpp
1465 lines (1353 loc) · 55.6 KB
/
rtp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "adts.h"
#include "bitfields.h"
#include "defines.h"
#include "encode.h"
#include "h264.h"
#include "mpeg.h"
#include "rtp.h"
#include "sdp.h"
#include "timing.h"
#include <arpa/inet.h>
namespace RTP{
double Packet::startRTCP = 0;
unsigned int MAX_SEND = 1500 - 28;
unsigned int PACKET_REORDER_WAIT = 5;
unsigned int PACKET_DROP_TIMEOUT = 30;
unsigned int Packet::getHsize() const{
unsigned int r = 12 + 4 * getContribCount();
if (getExtension()){r += (1 + Bit::btohs(data + r + 2)) * 4;}
return r;
}
unsigned int Packet::getPayloadSize() const{
// If there is more padding than content, ignore the packet
if (getHsize() + (getPadding() ? data[maxDataLen - 1] : 0) >= maxDataLen){
WARN_MSG("Packet has more padding than payload; ignoring packet");
return 0;
}
return maxDataLen - getHsize() - (getPadding() ? data[maxDataLen - 1] : 0);
}
char *Packet::getPayload() const{return data + getHsize();}
uint32_t Packet::getVersion() const{return (data[0] >> 6) & 0x3;}
uint32_t Packet::getPadding() const{return (data[0] >> 5) & 0x1;}
uint32_t Packet::getExtension() const{return (data[0] >> 4) & 0x1;}
uint32_t Packet::getContribCount() const{return (data[0]) & 0xE;}
uint32_t Packet::getMarker() const{return (data[1] >> 7) & 0x1;}
uint32_t Packet::getPayloadType() const{return (data[1]) & 0x7F;}
uint16_t Packet::getSequence() const{return Bit::btohs(data + 2);}
uint32_t Packet::getTimeStamp() const{return Bit::btohl(data + 4);}
unsigned int Packet::getSSRC() const{return Bit::btohl(data + 8);}
const char *Packet::getData(){return data + 8 + 4 * getContribCount() + getExtension();}
void Packet::setTimestamp(uint32_t timestamp){Bit::htobl(data + 4, timestamp);}
void Packet::setSequence(uint16_t seq){Bit::htobs(data + 2, seq);}
void Packet::setSSRC(uint32_t ssrc){Bit::htobl(data + 8, ssrc);}
void Packet::increaseSequence(){setSequence(getSequence() + 1);}
/// \brief Enables Pro-MPEG FEC with the specified amount of rows and columns
bool Packet::configureFEC(uint8_t rows, uint8_t columns){
if (rows < 4 || rows > 20){
ERROR_MSG("Rows should have a value between 4-20");
return false;
} else if (columns < 1 || columns > 20){
ERROR_MSG("Columns should have a value between 1-20");
return false;
} else if (rows * columns > 100){
ERROR_MSG("The product of rows * columns cannot exceed 100");
return false;
}
fecEnabled = true;
fecContext.needsInit = true;
fecContext.rows = rows;
fecContext.columns = columns;
fecContext.maxIndex = rows * columns;
INFO_MSG("Enabling 2d-fec with %u rows and %u columns", rows, columns);
return true;
}
void Packet::initFEC(uint64_t bufSize){
fecContext.needsInit = false;
fecContext.isFirst = true;
fecContext.index = 0;
fecContext.pktSize = bufSize;
fecContext.lengthRecovery = bufSize - 12;
// Add room for FEC and RTP header
fecContext.rtpBufSize = fecContext.lengthRecovery + 28;
// Add room for P, X, CC, M, PT, SN, TS fields
fecContext.bitstringSize = fecContext.lengthRecovery + 8;
fecContext.fecBufferRows.bitstring = 0;
fecContext.fecBufferColumns.clear();
fecContext.columnSN = 0;
fecContext.rowSN = 0;
}
/// \brief Takes an RTP packet containing TS packets and returns the modified payload
void Packet::generateBitstring(const char *payload, unsigned int payloadlen, uint8_t *bitstring){
// Write 8 bits of header data (P, X, CC, M, PT, timestamp)
bitstring[0] = data[0] & 0x3f;
bitstring[1] = data[1];
bitstring[2] = data[4];
bitstring[3] = data[5];
bitstring[4] = data[6];
bitstring[5] = data[7];
// Set length recovery
bitstring[7] = fecContext.lengthRecovery;
bitstring[6] = fecContext.lengthRecovery >> 8;
// Append payload of RTP packet
memcpy(bitstring + 8, payload, fecContext.lengthRecovery);
}
void Packet::applyXOR(const uint8_t *in1, const uint8_t *in2, uint8_t *out, uint64_t size){
uint64_t index = 0;
for (index = 0; index < size; index++) {
out[index] = in1[index] ^ in2[index];
}
}
/// \brief Sends buffered FEC packets
/// \param socket UDP socket ready to send packets
/// \param buf bitstring we want to contain in a FEC packet
/// \param isColumn whether the buf we want to send represents a completed column or row
void Packet::sendFec(void *socket, FecData *fecData, bool isColumn){
uint8_t *data = fecData->bitstring;
// Create zero filled buffer
uint8_t *rtpBuf = (uint8_t *)malloc(fecContext.rtpBufSize);
memset(rtpBuf, 0, fecContext.rtpBufSize);
uint16_t thisSN = isColumn ? ++fecContext.columnSN : ++fecContext.rowSN;
// V, P, X, CC
rtpBuf[0] = 0x80 | (data[0] & 0x3f);
// M, PT
rtpBuf[1] = (data[1] & 0x80) | 0x60;
// SN
rtpBuf[3] = thisSN;
rtpBuf[2] = thisSN >> 8;
// TS
rtpBuf[7] = fecData->timestamp;
rtpBuf[6] = fecData->timestamp >> 8;
rtpBuf[5] = fecData->timestamp >> 16;
rtpBuf[4] = fecData->timestamp >> 24;
// Keep SSRC 0 and skip CSRC
// SNBase low (lowest sequence number of the sequence of RTP packets in this FEC packet)
rtpBuf[13] = fecData->sequence;
rtpBuf[12] = fecData->sequence >> 8;
// Length recovery
rtpBuf[14] = data[6];
rtpBuf[15] = data[7];
// E=1, PT recovery
rtpBuf[16] = 0x80 | data[1];
// Keep Mask 0
// TS recovery
rtpBuf[20] = data[2];
rtpBuf[21] = data[3];
rtpBuf[22] = data[4];
rtpBuf[23] = data[5];
// X=0, D, type=0, index=0
rtpBuf[24] = isColumn ? 0x0 : 0x40;
// offset (number of columns)
rtpBuf[25] = isColumn ? fecContext.columns : 0x1;
// NA (number of rows)
rtpBuf[26] = isColumn ? fecContext.rows : fecContext.columns;
// Keep SNBase ext bits 0
// Payload
memcpy(rtpBuf + 28, data + 8, fecContext.lengthRecovery);
((Socket::UDPConnection *)socket)->SendNow(reinterpret_cast<char*>(rtpBuf), fecContext.rtpBufSize);
sentPackets++;
sentBytes += fecContext.rtpBufSize;
free(rtpBuf);
}
/// \brief Parses new RTP packets
void Packet::parseFEC(void *columnSocket, void *rowSocket, uint64_t & bytesSent, const char *payload, unsigned int payloadlen){
if (!fecEnabled){
return;
}
uint8_t *bitstring;
uint8_t thisColumn;
uint8_t thisRow;
// Check to see if we need to reinit FEC data
if (fecContext.needsInit){
// Add space for the RTP header
initFEC(payloadlen + 12);
}
// Check the buffer size which should be constant
if (payloadlen != fecContext.lengthRecovery){
WARN_MSG("RTP packet size should be constant, expected %u but got %u", fecContext.lengthRecovery, payloadlen);
return;
}
// Create bitstring
bitstring = (uint8_t *)malloc(fecContext.pktSize);
generateBitstring(payload, payloadlen, bitstring);
thisColumn = fecContext.index % fecContext.columns;
thisRow = (fecContext.index / fecContext.columns) % fecContext.rows;
// Check for completed rows of data
if (thisColumn == 0){
// Double check if we have a final FEC row of data before sending it
if (!fecContext.isFirst || fecContext.index > 0){
if (thisRow == 0){
INSANE_MSG("Sending completed FEC packet at row %u", fecContext.rows - 1);
} else {
INSANE_MSG("Sending completed FEC packet at row %u", thisRow - 1);
}
sendFec(rowSocket, &fecContext.fecBufferRows, false);
bytesSent += fecContext.rtpBufSize;
}
free(fecContext.fecBufferRows.bitstring);
fecContext.fecBufferRows.bitstring = bitstring;
// Set the SN and TS of this first packet in the sequence
fecContext.fecBufferRows.sequence = getSequence() - 1;
fecContext.fecBufferRows.timestamp = getTimeStamp();
} else {
// This is an intermediate packet, apply XOR operation and continue
applyXOR(fecContext.fecBufferRows.bitstring, bitstring, fecContext.fecBufferRows.bitstring, fecContext.bitstringSize);
}
// XOR or set new bitstring
if (thisRow == 0){
// Make a copy if we are already using this bitstring for the FEC row
if (thisColumn == 0){
uint8_t *bitstringCopy;
bitstringCopy = (uint8_t *)malloc(fecContext.pktSize);
memcpy(bitstringCopy, bitstring, fecContext.pktSize);
fecContext.fecBufferColumns[thisColumn].bitstring = bitstringCopy;
} else {
fecContext.fecBufferColumns[thisColumn].bitstring = bitstring;
}
fecContext.fecBufferColumns[thisColumn].sequence = getSequence() - 1;
fecContext.fecBufferColumns[thisColumn].timestamp = getTimeStamp();
} else {
// This is an intermediate packet, apply XOR operation and continue
applyXOR(fecContext.fecBufferColumns[thisColumn].bitstring, bitstring, fecContext.fecBufferColumns[thisColumn].bitstring, fecContext.bitstringSize);
}
// Check for completed columns of data
if (thisRow == fecContext.rows - 1){
INSANE_MSG("Sending completed FEC packet at column %u", thisColumn);
sendFec(columnSocket, &fecContext.fecBufferColumns[thisColumn], true);
bytesSent += fecContext.rtpBufSize;
free(fecContext.fecBufferColumns[thisColumn].bitstring);
}
// Update variables
fecContext.index++;
if (fecContext.index >= fecContext.maxIndex){
fecContext.isFirst = false;
fecContext.index = 0;
}
}
void Packet::sendNoPacket(unsigned int payloadlen){
// Increment counters
sentPackets++;
sentBytes += payloadlen + getHsize();
setTimestamp(Util::bootMS());
increaseSequence();
}
void Packet::sendTS(void *socket, const char *payload, unsigned int payloadlen){
// Add TS payload
memcpy(data + getHsize(), payload, payloadlen);
INSANE_MSG("Sending RTP packet with header size %u and payload size %u", getHsize(), payloadlen);
// Set timestamp to current time
setTimestamp(Util::bootMS()*90);
// Send RTP packet itself
((Socket::UDPConnection *)socket)->SendNow(data, getHsize() + payloadlen);
// Increment counters
sentPackets++;
sentBytes += payloadlen + getHsize();
increaseSequence();
}
void Packet::sendH264(void *socket, void callBack(void *, const char *, size_t, uint8_t),
const char *payload, uint32_t payloadlen, uint32_t channel, bool lastOfAccesUnit){
/// \todo This function probably belongs in DMS somewhere.
if (payloadlen + getHsize() + 2 <= maxDataLen){
data[1] &= 0x7F; // setting the RTP marker bit to 0
if (lastOfAccesUnit){
data[1] |= 0x80; // setting the RTP marker bit to 1
}
uint8_t nal_type = (payload[0] & 0x1F);
if (nal_type < 1 || nal_type > 5){
data[1] &= 0x7F; // but not for non-vlc types
}
memcpy(data + getHsize(), payload, payloadlen);
callBack(socket, data, getHsize() + payloadlen, channel);
sentPackets++;
sentBytes += payloadlen + getHsize();
increaseSequence();
}else{
data[1] &= 0x7F; // setting the RTP marker bit to 0
unsigned int sent = 0;
unsigned int sending = maxDataLen - getHsize() - 2; // packages are of size MAX_SEND, except for the final one
char initByte = (payload[0] & 0xE0) | 0x1C;
char serByte = payload[0] & 0x1F; // ser is now 000
data[getHsize()] = initByte;
while (sent < payloadlen){
if (sent == 0){
serByte |= 0x80; // set first bit to 1
}else{
serByte &= 0x7F; // set first bit to 0
}
if (sent + sending >= payloadlen){
// last package
serByte |= 0x40;
sending = payloadlen - sent;
if (lastOfAccesUnit){
data[1] |= 0x80; // setting the RTP marker bit to 1
}
}
data[getHsize() + 1] = serByte;
memcpy(data + getHsize() + 2, payload + 1 + sent, sending);
callBack(socket, data, getHsize() + 2 + sending, channel);
sentPackets++;
sentBytes += sending + getHsize() + 2;
sent += sending;
increaseSequence();
}
}
}
void Packet::sendVP8(void *socket, void callBack(void *, const char *, size_t, uint8_t),
const char *payload, unsigned int payloadlen, unsigned int channel){
bool isKeyframe = ((payload[0] & 0x01) == 0) ? true : false;
bool isStartOfPartition = true;
size_t chunkSize = MAX_SEND;
size_t bytesWritten = 0;
uint32_t headerSize = getHsize();
while (payloadlen > 0){
chunkSize = std::min<size_t>(1200, payloadlen);
payloadlen -= chunkSize;
data[1] = (0 != payloadlen) ? (data[1] & 0x7F) : (data[1] | 0x80); // marker bit, 1 for last chunk.
data[headerSize] = 0x00; // reset
data[headerSize] |= (isStartOfPartition) ? 0x10 : 0x00; // first chunk is always start of a partition.
data[headerSize] |= (isKeyframe) ? 0x00 : 0x20; // non-reference frame. 0 = frame is needed, 1 = frame can be disgarded.
memcpy(data + headerSize + 1, payload + bytesWritten, chunkSize);
callBack(socket, data, headerSize + 1 + chunkSize, channel);
increaseSequence();
// INFO_MSG("chunk: %zu, sequence: %u", chunkSize, getSequence());
isStartOfPartition = false;
bytesWritten += chunkSize;
sentBytes += headerSize + 1 + chunkSize;
sentPackets++;
}
// WARN_MSG("KEYFRAME: %c", (isKeyframe) ? 'y' : 'n');
}
void Packet::sendH265(void *socket, void callBack(void *, const char *, size_t, uint8_t),
const char *payload, unsigned int payloadlen, unsigned int channel){
/// \todo This function probably belongs in DMS somewhere.
if (payloadlen + getHsize() + 3 <= maxDataLen){
data[1] |= 0x80; // setting the RTP marker bit to 1
memcpy(data + getHsize(), payload, payloadlen);
callBack(socket, data, getHsize() + payloadlen, channel);
sentPackets++;
sentBytes += payloadlen + getHsize();
increaseSequence();
}else{
data[1] &= 0x7F; // setting the RTP marker bit to 0
unsigned int sent = 0;
unsigned int sending = maxDataLen - getHsize() - 3; // packages are of size MAX_SEND, except for the final one
char initByteA = (payload[0] & 0x81) | 0x62;
char initByteB = payload[1];
char serByte = (payload[0] & 0x7E) >> 1; // SE is now 00
data[getHsize()] = initByteA;
data[getHsize() + 1] = initByteB;
while (sent < payloadlen){
if (sent == 0){
serByte |= 0x80; // set first bit to 1
}else{
serByte &= 0x7F; // set first bit to 0
}
if (sent + sending >= payloadlen){
// last package
serByte |= 0x40;
sending = payloadlen - sent;
data[1] |= 0x80; // setting the RTP marker bit to 1
}
data[getHsize() + 2] = serByte;
memcpy(data + getHsize() + 3, payload + 2 + sent, sending);
callBack(socket, data, getHsize() + 3 + sending, channel);
sentPackets++;
sentBytes += sending + getHsize() + 3;
sent += sending;
increaseSequence();
}
}
}
void Packet::sendMPEG2(void *socket, void callBack(void *, const char *, size_t, uint8_t),
const char *payload, unsigned int payloadlen, unsigned int channel){
/// \todo This function probably belongs in DMS somewhere.
if (payloadlen + getHsize() + 4 <= maxDataLen){
data[1] |= 0x80; // setting the RTP marker bit to 1
Mpeg::MPEG2Info mInfo = Mpeg::parseMPEG2Headers(payload, payloadlen);
MPEGVideoHeader mHead(data + getHsize());
mHead.clear();
mHead.setTempRef(mInfo.tempSeq);
mHead.setPictureType(mInfo.frameType);
if (mInfo.isHeader){mHead.setSequence();}
mHead.setBegin();
mHead.setEnd();
memcpy(data + getHsize() + 4, payload, payloadlen);
callBack(socket, data, getHsize() + payloadlen + 4, channel);
sentPackets++;
sentBytes += payloadlen + getHsize() + 4;
increaseSequence();
}else{
data[1] &= 0x7F; // setting the RTP marker bit to 0
unsigned int sent = 0;
unsigned int sending = maxDataLen - getHsize() - 4; // packages are of size MAX_SEND, except for the final one
Mpeg::MPEG2Info mInfo;
MPEGVideoHeader mHead(data + getHsize());
while (sent < payloadlen){
mHead.clear();
if (sent + sending >= payloadlen){
mHead.setEnd();
sending = payloadlen - sent;
data[1] |= 0x80; // setting the RTP marker bit to 1
}
Mpeg::parseMPEG2Headers(payload, sent + sending, mInfo);
mHead.setTempRef(mInfo.tempSeq);
mHead.setPictureType(mInfo.frameType);
if (sent == 0){
if (mInfo.isHeader){mHead.setSequence();}
mHead.setBegin();
}
memcpy(data + getHsize() + 4, payload + sent, sending);
callBack(socket, data, getHsize() + 4 + sending, channel);
sentPackets++;
sentBytes += sending + getHsize() + 4;
sent += sending;
increaseSequence();
}
}
}
void Packet::sendData(void *socket, void callBack(void *, const char *, size_t, uint8_t), const char *payload,
unsigned int payloadlen, unsigned int channel, std::string codec){
if (codec == "H264"){
unsigned long sent = 0;
const char * lastPtr = 0;
size_t lastLen = 0;
while (sent < payloadlen){
unsigned long nalSize = ntohl(*((unsigned long *)(payload + sent)));
// Since we skip filler data, we need to delay sending by one NAL unit to reliably
// detect the end of the access unit.
if ((payload[sent + 4] & 0x1F) != 12){
// If we have a pointer stored, we know it's not the last one, so send it as non-last.
if (lastPtr){sendH264(socket, callBack, lastPtr, lastLen, channel, false);}
lastPtr = payload + sent + 4;
lastLen = nalSize;
}
sent += nalSize + 4;
}
// Still a pointer stored? That means it was the last one. Mark it as such and send.
if (lastPtr){sendH264(socket, callBack, lastPtr, lastLen, channel, true);}
return;
}
if (codec == "VP8"){
sendVP8(socket, callBack, payload, payloadlen, channel);
return;
}
if (codec == "VP9"){
sendVP8(socket, callBack, payload, payloadlen, channel);
return;
}
if (codec == "HEVC"){
unsigned long sent = 0;
while (sent < payloadlen){
unsigned long nalSize = ntohl(*((unsigned long *)(payload + sent)));
sendH265(socket, callBack, payload + sent + 4, nalSize, channel);
sent += nalSize + 4;
}
return;
}
if (codec == "MPEG2"){
sendMPEG2(socket, callBack, payload, payloadlen, channel);
return;
}
/// \todo This function probably belongs in DMS somewhere.
data[1] |= 0x80; // setting the RTP marker bit to 1
size_t offsetLen = 0;
if (codec == "AAC"){
Bit::htobl(data + getHsize(), ((payloadlen << 3) & 0x0010fff8) | 0x00100000);
offsetLen = 4;
}else if (codec == "MP3" || codec == "MP2"){
// See RFC 2250, "MPEG Audio-specific header"
Bit::htobl(data + getHsize(), 0); // this is MBZ and Frag_Offset, which are always 0
if (payload[0] != 0xFF){FAIL_MSG("MP2/MP3 data does not start with header?");}
offsetLen = 4;
}else if (codec == "AC3"){
Bit::htobs(data + getHsize(),
1); // this is 6 bits MBZ, 2 bits FT = 0 = full frames and 8 bits saying we send 1 frame
offsetLen = 2;
}
if (maxDataLen < getHsize() + offsetLen + payloadlen){
if (!managed){
FAIL_MSG("RTP data too big for packet, not sending!");
return;
}
uint32_t newMaxLen = getHsize() + offsetLen + payloadlen;
char *newData = new char[newMaxLen];
if (newData){
memcpy(newData, data, maxDataLen);
delete[] data;
data = newData;
maxDataLen = newMaxLen;
}
}
memcpy(data + getHsize() + offsetLen, payload, payloadlen);
callBack(socket, data, getHsize() + offsetLen + payloadlen, channel);
sentPackets++;
sentBytes += payloadlen + offsetLen + getHsize();
increaseSequence();
}
void Packet::sendRTCP_SR(void *socket, uint8_t channel, void callBack(void *, const char *, size_t, uint8_t)){
char *rtcpData = (char *)malloc(32);
if (!rtcpData){
FAIL_MSG("Could not allocate 32 bytes. Something is seriously messed up.");
return;
}
rtcpData[0] = 0x80; // version 2, no padding, zero receiver reports
rtcpData[1] = 200; // sender report
Bit::htobs(rtcpData + 2, 6); // 6 4-byte words follow the header
Bit::htobl(rtcpData + 4, getSSRC()); // set source identifier
Bit::htobll(rtcpData + 8, Util::getNTP());
Bit::htobl(rtcpData + 16, getTimeStamp()); // rtpts
// it should be the time packet was sent maybe, after all?
//*((int *)(rtcpData+16) ) = htonl(getTimeStamp());//rtpts
Bit::htobl(rtcpData + 20, sentPackets); // packet
Bit::htobl(rtcpData + 24, sentBytes); // octet
callBack(socket, (char *)rtcpData, 28, channel);
free(rtcpData);
}
void Packet::sendRTCP_RR(SDP::Track &sTrk, void callBack(void *, const char *, size_t, uint8_t)){
char *rtcpData = (char *)malloc(32);
if (!rtcpData){
FAIL_MSG("Could not allocate 32 bytes. Something is seriously messed up.");
return;
}
if (!(sTrk.sorter.lostCurrent + sTrk.sorter.packCurrent)){sTrk.sorter.packCurrent++;}
rtcpData[0] = 0x81; // version 2, no padding, one receiver report
rtcpData[1] = 201; // receiver report
Bit::htobs(rtcpData + 2, 7); // 7 4-byte words follow the header
Bit::htobl(rtcpData + 4, sTrk.mySSRC); // set receiver identifier
Bit::htobl(rtcpData + 8, sTrk.theirSSRC); // set source identifier
rtcpData[12] = (sTrk.sorter.lostCurrent * 255) / (sTrk.sorter.lostCurrent + sTrk.sorter.packCurrent); // fraction lost since prev RR
Bit::htob24(rtcpData + 13, sTrk.sorter.lostTotal); // cumulative packets lost since start
Bit::htobl(rtcpData + 16, sTrk.sorter.rtpSeq | (sTrk.sorter.packTotal & 0xFFFF0000ul)); // highest sequence received
Bit::htobl(rtcpData + 20, 0); /// \TODO jitter (diff in timestamp vs packet arrival)
Bit::htobl(rtcpData + 24, 0); /// \TODO last SR (middle 32 bits of last SR or zero)
Bit::htobl(rtcpData + 28, 0); /// \TODO delay since last SR in 2b seconds + 2b fraction
callBack(&(sTrk.rtcp), rtcpData, 32, 0);
sTrk.sorter.lostCurrent = 0;
sTrk.sorter.packCurrent = 0;
free(rtcpData);
}
Packet::Packet(){
managed = false;
data = 0;
maxDataLen = 0;
sentBytes = 0;
sentPackets = 0;
fecEnabled = false;
}
Packet::Packet(uint32_t payloadType, uint32_t sequence, uint64_t timestamp, uint32_t ssrc, uint32_t csrcCount){
managed = true;
data = new char[12 + 4 * csrcCount + 2 + MAX_SEND]; // headerSize, 2 for FU-A, MAX_SEND for maximum sent size
if (data){
maxDataLen = 12 + 4 * csrcCount + 2 + MAX_SEND;
data[0] = ((2) << 6) | ((0 & 1) << 5) | ((0 & 1) << 4) |
(csrcCount & 15); // version, padding, extension, csrc count
data[1] = payloadType & 0x7F; // marker and payload type
}else{
maxDataLen = 0;
}
setSequence(sequence - 1); // we automatically increase the sequence each time when p
setTimestamp(timestamp);
setSSRC(ssrc);
sentBytes = 0;
sentPackets = 0;
fecEnabled = false;
}
Packet::Packet(const Packet &o){
managed = true;
maxDataLen = 0;
if (o.data && o.maxDataLen){
data = new char[o.maxDataLen]; // headerSize, 2 for FU-A, MAX_SEND for maximum sent size
if (data){
maxDataLen = o.maxDataLen;
memcpy(data, o.data, o.maxDataLen);
}
}else{
data = new char[14 + MAX_SEND]; // headerSize, 2 for FU-A, MAX_SEND for maximum sent size
if (data){
maxDataLen = 14 + MAX_SEND;
memset(data, 0, maxDataLen);
}
}
sentBytes = o.sentBytes;
sentPackets = o.sentPackets;
}
void Packet::operator=(const Packet &o){
if (data && managed){delete[] data;}
managed = true;
maxDataLen = 0;
data = 0;
if (o.data && o.maxDataLen){
data = new char[o.maxDataLen]; // headerSize, 2 for FU-A, MAX_SEND for maximum sent size
if (data){
maxDataLen = o.maxDataLen;
memcpy(data, o.data, o.maxDataLen);
}
}else{
data = new char[14 + MAX_SEND]; // headerSize, 2 for FU-A, MAX_SEND for maximum sent size
if (data){
maxDataLen = 14 + MAX_SEND;
memset(data, 0, maxDataLen);
}
}
sentBytes = o.sentBytes;
sentPackets = o.sentPackets;
}
Packet::~Packet(){
if (managed){delete[] data;}
}
Packet::Packet(const char *dat, uint64_t len){
managed = false;
maxDataLen = len;
sentBytes = 0;
sentPackets = 0;
fecEnabled = false;
data = (char *)dat;
}
/// Describes a packet in human-readable terms
std::string Packet::toString() const{
std::stringstream ret;
ret << maxDataLen << "b RTP packet ";
if (getMarker()){ret << "(marked) ";}
ret << "payload type " << getPayloadType() << ", #" << getSequence() << ", @" << getTimeStamp();
ret << " (" << getHsize() << "b header, " << getPayloadSize() << "b payload, " << getPadding() << "b padding)";
return ret.str();
}
MPEGVideoHeader::MPEGVideoHeader(char *d){data = d;}
uint16_t MPEGVideoHeader::getTotalLen() const{
uint16_t ret = 4;
if (data[0] & 0x08){
ret += 4;
if (data[4] & 0x40){ret += data[8];}
}
return ret;
}
std::string MPEGVideoHeader::toString() const{
std::stringstream ret;
uint32_t firstHead = Bit::btohl(data);
ret << "TR=" << ((firstHead & 0x3FF0000) >> 16);
if (firstHead & 0x4000000){ret << " Ext";}
if (firstHead & 0x2000){ret << " SeqHead";}
if (firstHead & 0x1000){ret << " SliceBegin";}
if (firstHead & 0x800){ret << " SliceEnd";}
ret << " PicType=" << ((firstHead & 0x700) >> 8);
if (firstHead & 0x80){ret << " FBV";}
ret << " BFC=" << ((firstHead & 0x70) >> 4);
if (firstHead & 0x8){ret << " FFV";}
ret << " FFC=" << (firstHead & 0x7);
return ret.str();
}
void MPEGVideoHeader::clear(){((uint32_t *)data)[0] = 0;}
void MPEGVideoHeader::setTempRef(uint16_t ref){
data[0] |= (ref >> 8) & 0x03;
data[1] = ref & 0xff;
}
void MPEGVideoHeader::setPictureType(uint8_t pType){data[2] |= pType & 0x7;}
void MPEGVideoHeader::setSequence(){data[2] |= 0x20;}
void MPEGVideoHeader::setBegin(){data[2] |= 0x10;}
void MPEGVideoHeader::setEnd(){data[2] |= 0x8;}
Sorter::Sorter(uint64_t trackId, void (*cb)(const uint64_t track, const Packet &p)){
packTrack = trackId;
rtpSeq = 0;
rtpWSeq = 0;
lostTotal = 0;
lostCurrent = 0;
packTotal = 0;
packCurrent = 0;
callback = cb;
first = true;
preBuffer = true;
lastBootMS = 0;
lastNTP = 0;
}
void Sorter::setCallback(uint64_t track, void (*cb)(const uint64_t track, const Packet &p)){
callback = cb;
packTrack = track;
}
/// Calls addPacket(pack) with a newly constructed RTP::Packet from the given arguments.
void Sorter::addPacket(const char *dat, unsigned int len){addPacket(RTP::Packet(dat, len));}
/// Takes in new RTP packets for a single track.
/// Automatically sorts them, waiting when packets come in slow or not at all.
/// Calls the callback with packets in sorted order, whenever it becomes possible to do so.
void Sorter::addPacket(const Packet &pack){
uint16_t pSNo = pack.getSequence();
if (first){
rtpWSeq = pSNo;
rtpSeq = pSNo - 5;
first = false;
}
DONTEVEN_MSG("Received packet #%u, current packet is #%u", pSNo, rtpSeq);
if (preBuffer){
//If we've buffered the first 5 packets, assume we have the first one known
if (packBuffer.size() >= 5){
preBuffer = false;
rtpSeq = packBuffer.begin()->first;
rtpWSeq = rtpSeq;
}
}else{
// packet is very early - assume dropped after PACKET_DROP_TIMEOUT packets
while ((int16_t)(rtpSeq - pSNo) < -(int)PACKET_DROP_TIMEOUT){
VERYHIGH_MSG("Giving up on track %" PRIu64 " packet %u", packTrack, rtpSeq);
++rtpSeq;
++lostTotal;
++lostCurrent;
++packTotal;
++packCurrent;
}
}
//Update wanted counter if we passed it (1 of 2)
if ((int16_t)(rtpWSeq - rtpSeq) < 0){rtpWSeq = rtpSeq;}
// packet is somewhat early - ask for packet after PACKET_REORDER_WAIT packets
while ((int16_t)(rtpWSeq - pSNo) < -(int)PACKET_REORDER_WAIT){
//Only wanted if we don't already have it
if (!packBuffer.count(rtpWSeq)){
wantedSeqs.insert(rtpWSeq);
}
++rtpWSeq;
}
// send any buffered packets we may have
uint16_t prertpSeq = rtpSeq;
while (packBuffer.count(rtpSeq)){
outPacket(packTrack, packBuffer[rtpSeq]);
packBuffer.erase(rtpSeq);
++rtpSeq;
++packTotal;
++packCurrent;
}
if (prertpSeq != rtpSeq){
INFO_MSG("Sent packets %" PRIu16 "-%" PRIu16 ", now %zu in buffer", prertpSeq, rtpSeq, packBuffer.size());
}
// packet is slightly early - buffer it
if ((int16_t)(rtpSeq - pSNo) < 0){
VERYHIGH_MSG("Buffering early packet #%u->%u", rtpSeq, pack.getSequence());
packBuffer[pack.getSequence()] = pack;
}
// packet is late
if ((int16_t)(rtpSeq - pSNo) > 0){
// negative difference?
//--lostTotal;
//--lostCurrent;
//++packTotal;
//++packCurrent;
//WARN_MSG("Dropped a packet that arrived too late! (%d packets difference)", (int16_t)(rtpSeq - pSNo));
//return;
}
// packet is in order
if (rtpSeq == pSNo){
outPacket(packTrack, pack);
++rtpSeq;
++packTotal;
++packCurrent;
}
//Update wanted counter if we passed it (2 of 2)
if ((int16_t)(rtpWSeq - rtpSeq) < 0){rtpWSeq = rtpSeq;}
}
toDTSC::toDTSC(){
wrapArounds = 0;
recentWrap = false;
cbPack = 0;
cbInit = 0;
multiplier = 1.0;
trackId = INVALID_TRACK_ID;
firstTime = 0;
packCount = 0;
lastSeq = 0;
vp8BufferHasKeyframe = false;
curPicParameterSetId = 0;
}
void toDTSC::setProperties(const uint64_t track, const std::string &c, const std::string &t,
const std::string &i, const double m){
trackId = track;
codec = c;
type = t;
init = i;
multiplier = m;
if (codec == "HEVC" && init.size()){
hevcInfo = h265::initData(init);
h265::metaInfo MI = hevcInfo.getMeta();
fps = MI.fps;
}
if (codec == "H264" && init.size()){
MP4::AVCC avccbox;
avccbox.setPayload(init);
spsData.assign(avccbox.getSPS(), avccbox.getSPSLen());
ppsData[curPicParameterSetId].assign(avccbox.getPPS(), avccbox.getPPSLen());
h264::sequenceParameterSet sps(spsData.data(), spsData.size());
h264::SPSMeta hMeta = sps.getCharacteristics();
fps = hMeta.fps;
}
}
void toDTSC::setProperties(const DTSC::Meta &M, size_t tid){
double m = (double)M.getRate(tid) / 1000.0;
if (M.getType(tid) == "video" || M.getCodec(tid) == "MP2" || M.getCodec(tid) == "MP3"){
m = 90.0;
}
if (M.getCodec(tid) == "opus"){
m = 48.0;
}
setProperties(M.getID(tid), M.getCodec(tid), M.getType(tid), M.getInit(tid), m);
}
void toDTSC::setCallbacks(void (*cbP)(const DTSC::Packet &pkt),
void (*cbI)(const uint64_t track, const std::string &initData)){
cbPack = cbP;
cbInit = cbI;
}
/// Improves A/V sync by providing an NTP time source
/// msDiff is the amount of millis our current NTP time is ahead of the sync moment NTP time
/// May be negative, if we're behind instead of ahead.
void toDTSC::timeSync(uint32_t rtpTime, int64_t msDiff){
if (!firstTime){return;}
uint64_t rtp64Time = rtpTime;
if (recentWrap){
if (rtpTime > 0x80000000lu){rtp64Time -= 0x100000000ll;}
}
uint64_t msTime = (rtp64Time - firstTime + 1 + 0x100000000ull * wrapArounds) / multiplier + milliSync;
int32_t rtpDiff = msTime - (Util::bootMS() - msDiff);
if (rtpDiff > 25 || rtpDiff < -25){
INFO_MSG("RTP difference (%s %s): %" PRId32 "ms, syncing...", type.c_str(), codec.c_str(), rtpDiff);
milliSync -= rtpDiff;
}
}
/// Adds an RTP packet to the converter, outputting DTSC packets and/or updating init data,
/// as-needed.
void toDTSC::addRTP(const RTP::Packet &pkt){
if (pkt.getPayloadType() >= 72 && pkt.getPayloadType() <= 76){
INFO_MSG("RTCP packet, ignoring for decoding");
return;
}
if (codec.empty()){
MEDIUM_MSG("Unknown codec - ignoring RTP packet.");
return;
}
// First calculate the timestamp of the packet, get the pointer and length to RTP payload.
// This part isn't codec-specific, so we do it before anything else.
int64_t pTime = pkt.getTimeStamp();
if (!firstTime){
milliSync = Util::bootMS();
firstTime = pTime + 1;
INFO_MSG("RTP timestamp rollover for %" PRIu64 " (%s) expected in " PRETTY_PRINT_TIME, trackId, codec.c_str(),
PRETTY_ARG_TIME((0xFFFFFFFFul - firstTime) / multiplier / 1000));
}else{
if (recentWrap){
if (pTime < 0x80000000lu && pTime > 0x40000000lu){recentWrap = false;}
if (pTime > 0x80000000lu){pTime -= 0x100000000ll;}
}else{
if (prevTime > pTime && pTime < 0x40000000lu && prevTime > 0x80000000lu){
++wrapArounds;
INFO_MSG("RTP timestamp rollover %" PRIu32 " for %" PRIu64 " (%s) happened; next should be in " PRETTY_PRINT_TIME, wrapArounds, trackId, codec.c_str(), PRETTY_ARG_TIME((0xFFFFFFFFul) / multiplier / 1000));
recentWrap = true;
}
}
}
// When there are B-frames, the firstTime can be higher than the current time
// causing msTime to become negative and thus overflow
if (!wrapArounds && firstTime > pTime + 1){
WARN_MSG("firstTime was higher than current packet time. Readjusting firstTime...");
firstTime = pTime + 1;
}
prevTime = pkt.getTimeStamp();
uint64_t msTime = ((uint64_t)pTime - firstTime + 1 + 0x100000000ull * wrapArounds) / multiplier + milliSync;
char *pl = (char *)pkt.getPayload();
uint32_t plSize = pkt.getPayloadSize();
bool missed = lastSeq != (pkt.getSequence() - 1);
lastSeq = pkt.getSequence();
INSANE_MSG("Received RTP packet for track %" PRIu64 ", time %" PRIu32 " -> %" PRIu64, trackId,
pkt.getTimeStamp(), msTime);
// From here on, there is codec-specific parsing. We call handler functions for each codec,
// except for the trivial codecs.
if (codec == "H264"){
return handleH264(msTime, pl, plSize, missed, false);
}
if (codec == "AAC"){return handleAAC(msTime, pl, plSize);}
if (codec == "MP2" || codec == "MP3"){return handleMP2(msTime, pl, plSize);}
if (codec == "HEVC"){return handleHEVC(msTime, pl, plSize, missed);}
if (codec == "MPEG2"){return handleMPEG2(msTime, pl, plSize);}
if (codec == "VP8"){
return handleVP8(msTime, pl, plSize, missed, false);
}
if (codec == "VP9"){
return handleVP8(msTime, pl, plSize, missed, false);
}
// Trivial codecs just fill a packet with raw data and continue. Easy peasy, lemon squeezy.
if (codec == "ALAW" || codec == "opus" || codec == "PCM" || codec == "ULAW"){
DTSC::Packet nextPack;
nextPack.genericFill(msTime, 0, trackId, pl, plSize, 0, false);
outPacket(nextPack);
return;
}
// If we don't know how to handle this codec in RTP, print an error and ignore the packet.
FAIL_MSG("Unimplemented RTP reader for codec `%s`! Throwing away packet.", codec.c_str());
}
void toDTSC::handleAAC(uint64_t msTime, char *pl, uint32_t plSize){
// assume AAC packets are single AU units
/// \todo Support other input than single AU units
unsigned int headLen = (Bit::btohs(pl) >> 3) + 2; // in bits, so /8, plus two for the prepended size
DTSC::Packet nextPack;
uint16_t samples = aac::AudSpecConf::samples(init);
uint32_t sampleOffset = 0;
uint32_t offset = 0;
uint32_t auSize = 0;
for (uint32_t i = 2; i < headLen; i += 2){
auSize = Bit::btohs(pl + i) >> 3; // only the upper 13 bits
nextPack.genericFill(msTime + sampleOffset / multiplier, 0, trackId, pl + headLen + offset,
std::min(auSize, plSize - headLen - offset), 0, false);
offset += auSize;
sampleOffset += samples;
outPacket(nextPack);
}
}
void toDTSC::handleMP2(uint64_t msTime, char *pl, uint32_t plSize){
if (plSize < 5){
WARN_MSG("Empty packet ignored!");
return;
}
DTSC::Packet nextPack;
nextPack.genericFill(msTime, 0, trackId, pl + 4, plSize - 4, 0, false);
outPacket(nextPack);
}
void toDTSC::handleMPEG2(uint64_t msTime, char *pl, uint32_t plSize){
if (plSize < 5){
WARN_MSG("Empty packet ignored!");
return;
}
///\TODO Merge packets with same timestamp together
HIGH_MSG("Received MPEG2 packet: %s", RTP::MPEGVideoHeader(pl).toString().c_str());
DTSC::Packet nextPack;
nextPack.genericFill(msTime, 0, trackId, pl + 4, plSize - 4, 0, false);
outPacket(nextPack);
}
void toDTSC::handleHEVC(uint64_t msTime, char *pl, uint32_t plSize, bool missed){
if (plSize < 2){
WARN_MSG("Empty packet ignored!");
return;
}
uint8_t nalType = (pl[0] & 0x7E) >> 1;
if (nalType == 48){
unsigned int pos = 2;