/
RTP.cpp
2568 lines (2227 loc) · 110 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
/*****************************************************************************
*
* Copyright (C) 2009 Thomas Volkert <thomas@homer-conferencing.com>
*
* This software is free software.
* Your are allowed to redistribute it and/or modify it under the terms of
* the GNU General Public License version 2 as published by the Free Software
* Foundation.
*
* This source is published in the hope that it will be useful, but
* WITHOUT ANY WARRANTY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License version 2 for more details.
*
* You should have received a copy of the GNU General Public License version 2
* along with this program. Otherwise, you can write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
* Alternatively, you find an online version of the license text under
* http://www.gnu.org/licenses/gpl-2.0.html.
*
*****************************************************************************/
/*
* Purpose: Implementation for real-time transport protocol
* Author: Thomas Volkert
* Since: 2009-10-28
*/
/*
Result of functional validation:
Sending Receiving
--------------------------------------------------------------------
h261: ok (HC) ok (HC)
h263: ok (HC) ok (linphone, ekiga, HC)
h263+: ok (linphone, HC) ok (linphone, HC)
h264: ok (linphone, HC) ok (HC)
Mpeg1: ok (HC) ok (HC)
Mpeg2: ok (HC) ok (HC)
Mpeg4: ok (linphone, ekiga, HC) ok (linphone, ekiga, HC)
theora: ? ?
pcma (G711): ok (HC, Ekiga) ok (HC, Ekiga)
pcmu (G711): ok (HC, Ekiga) ok (HC, Ekiga)
adpcm(G722): ok (HC, Ekiga) ok (HC, Ekiga)
mp3: ok (HC) ok (HC)
pcm16be: ok (HC) ok (HC)
unsupported:
mjpeg
RTP parameters: http://www.iana.org/assignments/rtp-parameters
MP3 hack:
Problem: ffmpeg buffers mp3 fragments but there is no value in the RTP headers to store the size of the entire original MP3 buffer
Solution: we store the size of all MP3 fragments in "mMp3Hack_EntireBufferSize" and set MBZ from the RTP header to this value
further, we use this value when parsing the RTP packets
*/
#include <string>
#include <sstream>
#include <RTP.h>
#include <Header_Ffmpeg.h>
#include <PacketStatistic.h>
#include <HBSocket.h>
#include <MediaSourceNet.h>
#include <Logger.h>
namespace Homer { namespace Multimedia {
using namespace std;
using namespace Homer::Monitor;
///////////////////////////////////////////////////////////////////////////////
// how many consecutive timestamp overflows do we want to accept before we assume that the remote source has changed?
#define RTP_MAX_CONSECUTIVE_TIMESTAMP_OVERFLOWS 1
// how many consecutive sequence number overflows do we want to accept before we assume that the remote source has changed?
#define RTP_MAX_CONSECUTIVE_SEQUENCE_NUMBER_OVERFLOWS 1
///////////////////////////////////////////////////////////////////////////////
#define IS_RTCP_TYPE(x) ((x >= 72) && (x <= 76))
///////////////////////////////////////////////////////////////////////////////
#define RTP_PAYLOAD_TYPE_NONE 0x7F
///////////////////////////////////////////////////////////////////////////////
/* ##################################################################################
// ########################## Resulting packet structure ############################
// ##################################################################################
Size Offfset Element
20 0 IP header
8 20 UDP header
12 28 RTP header
m 40 RTP payload header
n 40+m RTP payload = codec packet (rtcp feedback, h261, h263, h263+, h264, mpeg4, PCMA, PCMU, MP3 a.s.o.)
Ethernet/WLan frame(1500) - IP(20)-UDP(8)-RTP(12) = 1460 bytes RTP payload limit
*/
unsigned int RTP::mH261PayloadSizeMax = 0;
///////////////////////////////////////////////////////////////////////////////
// ########################## AMR-NB (RFC 3267) ###########################################
union AMRNBHeader{ //TODO
struct{
unsigned int dummy0:24;
unsigned int Mi:3; /* Mode Index (MI) */
unsigned int Reserved:5; /* Reserved bits */
} __attribute__((__packed__));
uint32_t Data[1];
};
// ########################## G.711 ###########################################
union G711Header{
struct{
unsigned int dummy0:24;
unsigned int Mi:3; /* Mode Index (MI) */
unsigned int Reserved:5; /* Reserved bits */
} __attribute__((__packed__));
uint32_t Data[1];
};
// ############################ MP3 ADU #######################################
union MP3AduHeader{
struct{
unsigned int dummy1:16;
unsigned int SizeExt:8;
unsigned int Size:6; /* ADU size */
unsigned int T:1; /* Descriptor Type flag */
unsigned int C:1; /* Continuation flag */
} __attribute__((__packed__));
uint32_t Data[1];
};
// ############################ MPA audio #####################################
union MPAHeader{
struct{
unsigned short int Offset:16; /* fragmentation offset */
unsigned short int Mbz:16; /* some funny zero values */
} __attribute__((__packed__));
uint32_t Data[1];
};
// ############################ MPV video #####################################
union MPVHeader{
struct{
unsigned int Ffc:3; /* forward f code? */
unsigned int Ffv:1; /* full pel forward vector? */
unsigned int Bfc:3; /* backward f code? */
unsigned int Fbv:1; /* full pel backward vector? */
unsigned int PType:3; /* picture type */
unsigned int E:1; /* end of slice? */
unsigned int B:1; /* beginning of slice? */
unsigned int S:1; /* sequence header present? */
unsigned int N:1; /* N bit: new picture header? */
unsigned int An:1; /* active N bit */
unsigned int Tr:10; /* temporal reference: chronological order of pictures within current GOP */
unsigned int T:1; /* two headers present? next one is MPEG 2 header */
unsigned int Mbz:5; /* some funny zero values */
} __attribute__((__packed__));
uint32_t Data[1];
};
// ####################### MPV mpeg2 extension #################################
union MPVMpeg2Header{
struct{
unsigned short int dummy0;
unsigned short int dummy1;
/* X: Unused (1 bit). Must be set to zero in current
specification. This space is reserved for future use.
E: Extensions present (1 bit). If set to 1, this header
f_[0,0]: forward horizontal f_code (4 bits)
f_[0,1]: forward vertical f_code (4 bits)
f_[1,0]: backward horizontal f_code (4 bits)
f_[1,1]: backward vertical f_code (4 bits)
DC: intra_DC_precision (2 bits)
PS: picture_structure (2 bits)
T: top_field_first (1 bit)
P: frame_predicted_frame_dct (1 bit)
C: concealment_motion_vectors (1 bit)
Q: q_scale type (1 bit)
V: intra_vlc_format (1 bit)
A: alternate scan (1 bit)
R: repeat_first_field (1 bit)
H: chroma_420_type (1 bit)
G: progressive frame (1 bit)
D: composite_display_flag (1 bit). If set to 1, next 32 bits
following this one contains 12 zeros followed by 20 bits
of composite display information.*/
} __attribute__((__packed__));
uint32_t Data[1];
};
// ########################## H 261 ###########################################
union H261Header{
struct{
unsigned int Vmvd:5; /* Vertical motion vector data (VMVD) */
unsigned int Hmvd:5; /* Horizontal motion vector data (HMVD */
unsigned int Quant:5; /* Quantizer (QUANT) */
unsigned int Mbap:5; /* Macroblock address predictor (MBAP) */
unsigned int Gobn:4; /* GOB number (GOBN) */
unsigned int V:1; /* Motion Vector flag (V) */
unsigned int I:1; /* INTRA-frame encoded data (I) */
unsigned int Ebit:3; /* End bit position (EBIT) */
unsigned int Sbit:3; /* Start bit position (SBIT) */
} __attribute__((__packed__));
uint32_t Data[1];
};
#define H261_HEADER_SIZE sizeof(H261Header)
// **** H261/RTP payload limitation workaround ***********************************
// HINT: workaround, but static value: RTP_MAX_PAYLOAD_SIZE - H261_HEADER_SIZE,
// at the moment the packet size limitation works via the limitation of codec packets
#define RTP_MAX_H261_PAYLOAD_SIZE (mH261PayloadSizeMax)
// *******************************************************************************
// ########################## H 263 ############################################
union H263Header{
struct{
unsigned int dummy0:21;
unsigned int Src:3; /* source format: resolution of current picture */
unsigned int Ebit:3; /* End bit position (EBIT) */
unsigned int Sbit:3; /* Start bit position (SBIT) */
unsigned int P:1; /* optional p-frames: "0" implies normal I or P frame, "1" PB-frames. When F=1, P also indicates modes: mode B if P=0, mode C if P=1 */
unsigned int F:1; /* mode flag: F=0, mode A; F=1, mode B or mode C depending on P bit */
unsigned int dummy1, dummy2;
} __attribute__((__packed__));
struct{
unsigned int Tr:8; /* Temporal Reference for p-frames */
unsigned int Trb:3; /* Temporal Reference for b-frames */
unsigned int Dbq:2; /* Differential quantization parameter */
unsigned int Reserved:4; /* Reserved bits */
unsigned int A:1; /* Advanced Prediction option */
unsigned int S:1; /* Syntax-based Arithmetic Coding option */
unsigned int U:1; /* Unrestricted Motion Vector option */
unsigned int I:1; /* i-frame: "0" is intra-coded, "1" is inter-coded */
unsigned int Src:3; /* source format: resolution of current picture */
unsigned int Ebit:3; /* End bit position (EBIT) */
unsigned int Sbit:3; /* Start bit position (SBIT) */
unsigned int P:1; /* optional p-frames: "0" implies normal I or P frame, "1" PB-frames. When F=1, P also indicates modes: mode B if P=0, mode C if P=1 */
unsigned int F:1; /* mode flag: F=0, mode A; F=1, mode B or mode C depending on P bit */
unsigned int dummy1, dummy2;
} __attribute__((__packed__)) ModeA;
struct{
unsigned int Reserved:2; /* Reserved bits */
unsigned int Mba:9; /* address within the GOB */
unsigned int Gobn:5; /* GOB number */
unsigned int Quant:5; /* Quantizer (QUANT) */
unsigned int Src:3; /* source format: resolution of current picture */
unsigned int Ebit:3; /* End bit position (EBIT) */
unsigned int Sbit:3; /* Start bit position (SBIT) */
unsigned int P:1; /* optional p-frames: "0" implies normal I or P frame, "1" PB-frames. When F=1, P also indicates modes: mode B if P=0, mode C if P=1 */
unsigned int F:1; /* mode flag: F=0, mode A; F=1, mode B or mode C depending on P bit */
unsigned int Vmv2:7; /* Vertical motion vector predictor */
unsigned int Hmv2:7; /* Horizontal motion vector predictor */
unsigned int Vmv1:7; /* Vertical motion vector predictor */
unsigned int Hmv1:7; /* Horizontal motion vector predictor */
unsigned int A:1; /* Advanced Prediction option */
unsigned int S:1; /* Syntax-based Arithmetic Coding option */
unsigned int U:1; /* Unrestricted Motion Vector option */
unsigned int I:1; /* i-frame: "0" is intra-coded, "1" is inter-coded */
unsigned int dummy1;
} __attribute__((__packed__)) ModeB;
struct{
unsigned int Reserved1:2; /* Reserved bits */
unsigned int Mba:9; /* address within the GOB */
unsigned int Gobn:5; /* GOB number */
unsigned int Quant:5; /* Quantizer (QUANT) */
unsigned int Src:3; /* source format: resolution of current picture */
unsigned int Ebit:3; /* End bit position (EBIT) */
unsigned int Sbit:3; /* Start bit position (SBIT) */
unsigned int P:1; /* optional p-frames: "0" implies normal I or P frame, "1" PB-frames. When F=1, P also indicates modes: mode B if P=0, mode C if P=1 */
unsigned int F:1; /* mode flag: F=0, mode A; F=1, mode B or mode C depending on P bit */
unsigned int Vmv2:7; /* Vertical motion vector predictor */
unsigned int Hmv2:7; /* Horizontal motion vector predictor */
unsigned int Vmv1:7; /* Vertical motion vector predictor */
unsigned int Hmv1:7; /* Horizontal motion vector predictor */
unsigned int A:1; /* Advanced Prediction option */
unsigned int S:1; /* Syntax-based Arithmetic Coding option */
unsigned int U:1; /* Unrestricted Motion Vector option */
unsigned int I:1; /* i-frame: "0" is intra-coded, "1" is inter-coded */
unsigned int Tr:8; /* Temporal Reference for p-frames */
unsigned int Trb:3; /* Temporal Reference for b-frames */
unsigned int Dbq:2; /* Differential quantization parameter */
unsigned int Reserved2:19; /* Reserved bits */
} __attribute__((__packed__)) ModeC;
uint32_t Data[3];
};
// ########################## H 263+ ###########################################
union H263PHeader{
struct{
unsigned int dummy1:16;
unsigned int Pebit:3; /* amount of ignored bits (PEBIT) */
unsigned int Plen:6; /* extra picture header length (PLEN) */
unsigned int V:1; /* Video Redundancy Coding (VRC) */
unsigned int P:1; /* picture start (P) */
unsigned int Reserved:5; /* Reserved bits (PR) */
} __attribute__((__packed__));
struct{
unsigned int dummy1:8;
unsigned int S:1; /* sync frame? (S) */
unsigned int Trunc:4; /* packet number within each thread */
unsigned int Tid:3; /* Thread ID (TID) */
unsigned int Pebit:3; /* amount of ignored bits (PEBIT) */
unsigned int Plen:6; /* extra picture header length (PLEN) */
unsigned int V:1; /* Video Redundancy Coding (VRC) */
unsigned int P:1; /* picture start (P) */
unsigned int Reserved:5; /* Reserved bits (PR) */
} __attribute__((__packed__))Vrc;
uint32_t Data[1];
};
// ########################## H 264 ###########################################
union H264Header{
struct{
unsigned int dummy1:24;
unsigned int Type:5; /* NAL unit type */
unsigned int Nri:2; /* NAL reference indicator (NRI) */
unsigned int F:1; /* forbidden zero bit (F) */
} __attribute__((__packed__));
struct{
unsigned int dummy1:24;
unsigned int Type:5; /* NAL unit type */
unsigned int Nri:2; /* NAL reference indicator (NRI) */
unsigned int F:1; /* forbidden zero bit (F) */
} __attribute__((__packed__))StapA;
struct{
unsigned int dummy1:8;
unsigned short int Don; /* decoding order number (DON) */
unsigned int Type:5; /* NAL unit type */
unsigned int Nri:2; /* NAL reference indicator (NRI) */
unsigned int F:1; /* forbidden zero bit (F) */
} __attribute__((__packed__))StapB, Mtap16, Mtap32;
struct{
unsigned int dummy1:16;
unsigned int PlType:5; /* NAL unit payload type */
unsigned int R:1; /* reserved bit, must be 0 */
unsigned int E:1; /* end of a fragmented NAL unit (E) */
unsigned int S:1; /* start of a fragmented NAL unit (S) */
unsigned int Type:5; /* NAL unit type */
unsigned int Nri:2; /* NAL reference indicator (NRI) */
unsigned int F:1; /* forbidden zero bit (F) */
} __attribute__((__packed__))FuA;
struct{
unsigned short int Don; /* decoding order number (DON) */
unsigned int PlType:5; /* NAL unit payload type */
unsigned int R:1; /* reserved bit, must be 0 */
unsigned int E:1; /* end of a fragmented NAL unit (E) */
unsigned int S:1; /* start of a fragmented NAL unit (S) */
unsigned int Type:5; /* NAL unit type */
unsigned int Nri:2; /* NAL reference indicator (NRI) */
unsigned int F:1; /* forbidden zero bit (F) */
} __attribute__((__packed__))FuB;
uint32_t Data[1];
};
// ############################ THEORA) ############################################
union THEORAHeader{
struct{
unsigned int Packets:4; /* packet count */
unsigned int TDT:2; /* data type */
unsigned int F:2; /* fragment type */
unsigned int ConfigId:24; /* configuration ID */
} __attribute__((__packed__));
uint32_t Data[1];
};
// ########################## VP8 (webm) ###########################################
union VP8Header{
struct{
unsigned int PartID:4; /* partition index */
unsigned int S:1; /* start of VP8 partition */
unsigned int N:1; /* non-reference frame */
unsigned int R:1; /* must be zero */
unsigned int X:1; /* Extended control bits present */
} __attribute__((__packed__));
uint8_t Data[1];
};
union VP8ExtendedHeader{
struct{
unsigned int RsvA:5; /* must be zero */
unsigned int T:1; /* TID present */
unsigned int L:1; /* TL0PICIDX present */
unsigned int I:1; /* picture ID present */
} __attribute__((__packed__));
uint8_t Data[1];
};
///////////////////////////////////////////////////////////////////////////////
RTP::RTP()
{
LOG(LOG_VERBOSE, "Created");
mH261LocalSequenceNumber = 0;
mIntermediateFragment = 0;
mPacketStatistic = NULL;
mRtpFormatContext = NULL;
mEncoderOpened = false;
mH261UseInternalEncoder = false;
mRtpPacketStream = NULL;
mRtpPacketBuffer = NULL;
mTargetHost = "";
mTargetPort = 0;
mStreamCodecID = CODEC_ID_NONE;
mLocalSourceIdentifier = 0;
Init();
}
RTP::~RTP()
{
LOG(LOG_VERBOSE, "Destroyed");
}
///////////////////////////////////////////////////////////////////////////////
void RTP::SetH261PayloadSizeMax(unsigned int pMaxSize)
{//workaround for separation of RTP packetizer and the payload limit problem which is caused by the missing RTP support for H261 within ffmpeg
mH261PayloadSizeMax = pMaxSize - RTP_HEADER_SIZE - H261_HEADER_SIZE;
}
unsigned int RTP::GetH261PayloadSizeMax()
{
return mH261PayloadSizeMax;
}
///////////////////////////////////////////////////////////////////////////////
void RTP::Init()
{
// reset variables
mRemoteSequenceNumberLastPacket = 0;
mRemoteTimestampLastPacket = 0;
mRemoteTimestampLastCompleteFrame = 0;
mRemoteSourceIdentifier = 0;
mRemoteStartTimestamp = 0;
mRemoteStartSequenceNumber = 0;
mRtcpLastRemoteTimestamp = 0;
mRtcpLastRemoteNtpTime = 0;
mRemoteTimestampOverflowShift = 0;
mRemoteTimestampConsecutiveOverflows = 0;
mRemoteTimestamp = 0;
mLastTimestampFromRTPHeader = 0;
mLastSequenceNumberFromRTPHeader = 0;
mLostPackets = 0;
if (mPacketStatistic != NULL)
mPacketStatistic->SetLostPacketCount(0);
mPayloadId = RTP_PAYLOAD_TYPE_NONE;
mRemoteSequenceNumberOverflowShift = 0;
mRemoteSequenceNumber = 0;
}
bool RTP::OpenRtpEncoderH261(string pTargetHost, unsigned int pTargetPort, AVStream *pInnerStream)
{
// get a timestamp
time_t tTimestamp;
time(&tTimestamp);
LOG(LOG_VERBOSE, "Using lib internal rtp packetizer for H261 codec");
LOG(LOG_INFO, "Opened...");
LOG(LOG_INFO, " ..rtp target: %s:%u", pTargetHost.c_str(), pTargetPort);
LOG(LOG_INFO, " ..rtp header size: %d", RTP_HEADER_SIZE);
LOG(LOG_INFO, " ..rtp SRC: %u", mLocalSourceIdentifier);
LOG(LOG_INFO, " Wrapping following codec...");
LOG(LOG_INFO, " ..codec name: %s", pInnerStream->codec->codec->name);
LOG(LOG_INFO, " ..codec long name: %s", pInnerStream->codec->codec->long_name);
LOG(LOG_INFO, " ..resolution: %d * %d pixels", pInnerStream->codec->width, pInnerStream->codec->height);
// LOG(LOG_INFO, " ..codec time_base: %d/%d", mCodecContext->time_base.den, mCodecContext->time_base.num); // inverse
LOG(LOG_INFO, " ..stream rfps: %d/%d", pInnerStream->r_frame_rate.num, pInnerStream->r_frame_rate.den);
LOG(LOG_INFO, " ..stream time_base: %d/%d", pInnerStream->time_base.den, pInnerStream->time_base.num); // inverse
LOG(LOG_INFO, " ..stream codec time_base: %d/%d", pInnerStream->codec->time_base.den, pInnerStream->codec->time_base.num); // inverse
LOG(LOG_INFO, " ..sample rate: %d Hz", pInnerStream->codec->sample_rate);
LOG(LOG_INFO, " ..channels: %d", pInnerStream->codec->channels);
LOG(LOG_INFO, " ..i-frame distance: %d pictures", pInnerStream->codec->gop_size);
LOG(LOG_INFO, " ..bit rate: %d Hz", pInnerStream->codec->bit_rate);
LOG(LOG_INFO, " ..qmin: %d", pInnerStream->codec->qmin);
LOG(LOG_INFO, " ..qmax: %d", pInnerStream->codec->qmax);
LOG(LOG_INFO, " ..mpeg quant: %d", pInnerStream->codec->mpeg_quant);
LOG(LOG_INFO, " ..pixel format: %d", (int)pInnerStream->codec->pix_fmt);
LOG(LOG_INFO, " ..sample format: %d", (int)pInnerStream->codec->sample_fmt);
LOG(LOG_INFO, " ..frame size: %d bytes", pInnerStream->codec->frame_size);
//LOG(LOG_INFO, " ..max packet size: %d bytes", mRtpFormatContext->pb->max_packet_size);
LOG(LOG_INFO, " ..rtp payload size: %d bytes", pInnerStream->codec->rtp_payload_size);
mEncoderOpened = true;
mH261UseInternalEncoder = true;
return true;
}
bool RTP::OpenRtpEncoder(string pTargetHost, unsigned int pTargetPort, AVStream *pInnerStream)
{
AVDictionary *tOptions = NULL;
if (mEncoderOpened)
return false;
mRtpPacketStream = (char*)malloc(MEDIA_SOURCE_AV_CHUNK_BUFFER_SIZE);
if (mRtpPacketStream == NULL)
LOG(LOG_ERROR, "Error when allocating memory for RTP packet stream");
else
LOG(LOG_VERBOSE, "Created RTP packet stream memory of %d bytes at %p", MEDIA_SOURCE_AV_CHUNK_BUFFER_SIZE, mRtpPacketStream);
mRtpPacketBuffer = (char*)malloc(pInnerStream->codec->rtp_payload_size);
if (mRtpPacketBuffer == NULL)
LOG(LOG_ERROR, "Error when allocating memory for RTP packet buffer");
else
LOG(LOG_VERBOSE, "Created RTP packet buffer memory of %d bytes at %p", MEDIA_SOURCE_AV_CHUNK_BUFFER_SIZE, mRtpPacketBuffer);
const char *tCodecName = pInnerStream->codec->codec->name;
mPayloadId = CodecToPayloadId(tCodecName);
LOG(LOG_VERBOSE, "New payload id: %4u, Codec: %s", mPayloadId, tCodecName);
mTargetHost = pTargetHost;
mTargetPort = pTargetPort;
mStreamCodecID = pInnerStream->codec->codec_id;
Init();
// set SRC ID
mLocalSourceIdentifier = av_get_random_seed();
if (mStreamCodecID == CODEC_ID_H261)
return OpenRtpEncoderH261(pTargetHost, pTargetPort, pInnerStream);
int tResult;
AVOutputFormat *tFormat;
AVStream *tOuterStream;
// allocate new format context
mRtpFormatContext = AV_NEW_FORMAT_CONTEXT();
// find format
tFormat = AV_GUESS_FORMAT("rtp", NULL, NULL);
if (tFormat == NULL)
{
LOG(LOG_ERROR, "Invalid suggested format");
// Close the format context
av_free(mRtpFormatContext);
return false;
}
// set correct output format
mRtpFormatContext->oformat = tFormat;
// verbose timestamp debugging mRtpFormatContext->debug = FF_FDEBUG_TS;
// allocate new stream structure
tOuterStream = HM_avformat_new_stream(mRtpFormatContext, 0);
if (tOuterStream == NULL)
{
LOG(LOG_ERROR, "Memory allocation failed");
return false;
}
// copy stream description from original stream description
memcpy(tOuterStream, pInnerStream, sizeof(AVStream));
tOuterStream->priv_data = NULL;
// create monotone timestamps
tOuterStream->cur_dts = 0;
tOuterStream->reference_dts = 0;
// set target coordinates for rtp stream
snprintf(mRtpFormatContext->filename, sizeof(mRtpFormatContext->filename), "rtp://%s:%u", pTargetHost.c_str(), pTargetPort);
// create I/O context which splits RTP stream into packets
MediaSource::CreateIOContext(mRtpPacketBuffer, tOuterStream->codec->rtp_payload_size, NULL, StoreRtpPacket, this, &mAVIOContext);
// set new I/O context
mRtpFormatContext->pb = mAVIOContext;
// limit packet size, otherwise ffmpeg will deliver unpredictable results ;)
mRtpFormatContext->pb->max_packet_size = mAVIOContext->max_packet_size;
mRtpFormatContext->start_time_realtime = av_gettime();
// Dump information about device file
av_dump_format(mRtpFormatContext, 0, "RTP Encoder", true);
// open RTP stream for avformat_Write_header()
OpenRtpPacketStream();
// allocate streams private data buffer and write the streams header, if any
avformat_write_header(mRtpFormatContext, NULL);
// close memory stream
char *tBuffer = NULL;
CloseRtpPacketStream(&tBuffer);
switch(mStreamCodecID)
{
case CODEC_ID_H263:
// use older rfc2190 for RTP packetizing
av_opt_set(mRtpFormatContext->priv_data, "rtpflags", "rfc2190", 0);
break;
default:
break;
}
tOuterStream->time_base.den = CalculateClockRateFactor() * 1000;
tOuterStream->time_base.num = 1;
int64_t tAVPacketPts = (float)tOuterStream->pts.val + tOuterStream->pts.num / tOuterStream->pts.den;
LOG(LOG_INFO, "Opened...");
LOG(LOG_INFO, " ..rtp target: %s:%u", pTargetHost.c_str(), pTargetPort);
LOG(LOG_INFO, " ..rtp header size: %d", RTP_HEADER_SIZE);
LOG(LOG_INFO, " Wrapping following codec...");
LOG(LOG_INFO, " ..codec name: %s", tOuterStream->codec->codec->name);
LOG(LOG_INFO, " ..codec long name: %s", tOuterStream->codec->codec->long_name);
LOG(LOG_INFO, " ..resolution: %d * %d pixels", tOuterStream->codec->width, tOuterStream->codec->height);
// LOG(LOG_INFO, " ..codec time_base: %d/%d", mCodecContext->time_base.den, mCodecContext->time_base.num); // inverse
LOG(LOG_INFO, " ..stream start real-time: %ld", mRtpFormatContext->start_time_realtime);
LOG(LOG_INFO, " ..stream start time: %ld", tOuterStream->start_time);
LOG(LOG_INFO, " ..max. delay: %d", mRtpFormatContext->max_delay);
LOG(LOG_INFO, " ..audio preload: %d", mRtpFormatContext->audio_preload);
LOG(LOG_INFO, " ..start A/V PTS: %ld", tAVPacketPts);
LOG(LOG_INFO, " ..stream rfps: %d/%d", tOuterStream->r_frame_rate.num, tOuterStream->r_frame_rate.den);
LOG(LOG_INFO, " ..stream time_base: %d/%d", tOuterStream->time_base.den, tOuterStream->time_base.num); // inverse
LOG(LOG_INFO, " ..stream codec time_base: %d/%d", tOuterStream->codec->time_base.den, tOuterStream->codec->time_base.num); // inverse
LOG(LOG_INFO, " ..sample rate: %d Hz", tOuterStream->codec->sample_rate);
LOG(LOG_INFO, " ..channels: %d", tOuterStream->codec->channels);
LOG(LOG_INFO, " ..i-frame distance: %d pictures", tOuterStream->codec->gop_size);
LOG(LOG_INFO, " ..bit rate: %d Hz", tOuterStream->codec->bit_rate);
LOG(LOG_INFO, " ..qmin: %d", tOuterStream->codec->qmin);
LOG(LOG_INFO, " ..qmax: %d", tOuterStream->codec->qmax);
LOG(LOG_INFO, " ..mpeg quant: %d", tOuterStream->codec->mpeg_quant);
LOG(LOG_INFO, " ..pixel format: %d", (int)tOuterStream->codec->pix_fmt);
LOG(LOG_INFO, " ..sample format: %d", (int)tOuterStream->codec->sample_fmt);
LOG(LOG_INFO, " ..frame size: %d bytes", tOuterStream->codec->frame_size);
LOG(LOG_INFO, " ..max packet size: %d bytes", mAVIOContext->max_packet_size);
LOG(LOG_INFO, " ..rtp payload size: %d bytes", tOuterStream->codec->rtp_payload_size);
mEncoderOpened = true;
mMp3Hack_EntireBufferSize = 0;
return true;
}
bool RTP::CloseRtpEncoder()
{
LOG(LOG_VERBOSE, "Going to close");
if (mEncoderOpened)
{
if (!mH261UseInternalEncoder /* h261 */)
{
// write the trailer, if any
av_write_trailer(mRtpFormatContext);
// close RTP stream
av_free(mAVIOContext);
// free stream 0
av_freep(&mRtpFormatContext->streams[0]);
// Close the format context
av_free(mRtpFormatContext);
}
if (mRtpPacketStream != NULL)
{
delete mRtpPacketBuffer;
mRtpPacketBuffer = NULL;
delete mRtpPacketStream;
mRtpPacketStream = NULL;
}
LOG(LOG_INFO, "...closed");
}else
LOG(LOG_INFO, "...wasn't open");
mEncoderOpened = false;
mH261UseInternalEncoder = false;
return true;
}
void RTP::RTPRegisterPacketStatistic(PacketStatistic *pStatistic)
{
mPacketStatistic = pStatistic;
}
bool RTP::IsPayloadSupported(enum CodecID pId)
{
bool tResult = false;
// check for supported codecs
switch(pId)
{
// list from "libavformat::rtpenc.c::is_supported"
case CODEC_ID_H261:
case CODEC_ID_H263:
case CODEC_ID_H263P:
case CODEC_ID_H264:
case CODEC_ID_MPEG1VIDEO:
case CODEC_ID_MPEG2VIDEO:
case CODEC_ID_MPEG4:
case CODEC_ID_MP3:
case CODEC_ID_PCM_ALAW:
case CODEC_ID_PCM_MULAW:
case CODEC_ID_PCM_S16BE:
// case CODEC_ID_MPEG2TS:
// case CODEC_ID_VORBIS:
case CODEC_ID_THEORA:
case CODEC_ID_VP8:
case CODEC_ID_ADPCM_G722:
// case CODEC_ID_ADPCM_G726:
tResult = true;
break;
default:
tResult = false;
break;
}
return tResult;
}
int RTP::GetPayloadHeaderSizeMax(enum CodecID pCodec)
{
int tResult = 0;
if (!IsPayloadSupported(pCodec))
return 0;
switch(pCodec)
{
// list from "libavformat::rtpenc.c::is_supported"
case CODEC_ID_H261:
tResult = sizeof(H261Header);
break;
case CODEC_ID_H263:
tResult = sizeof(H263Header);
break;
case CODEC_ID_H263P:
tResult = sizeof(H263PHeader);
break;
case CODEC_ID_H264:
tResult = sizeof(H264Header);
break;
case CODEC_ID_MPEG1VIDEO:
case CODEC_ID_MPEG2VIDEO:
tResult = sizeof(MPVHeader); //HINT: we neglect the MPEG2 add-on header
break;
case CODEC_ID_MPEG4:
tResult = 0;
break;
case CODEC_ID_MP3:
tResult = sizeof(MPAHeader);
break;
case CODEC_ID_PCM_ALAW:
tResult = 0;
break;
case CODEC_ID_PCM_MULAW:
tResult = 0;
break;
case CODEC_ID_PCM_S16BE:
tResult = 0;
break;
// case CODEC_ID_MPEG2TS:
// case CODEC_ID_VORBIS:
case CODEC_ID_THEORA:
tResult = sizeof(THEORAHeader);
break;
case CODEC_ID_VP8:
tResult = sizeof(VP8Header); // we neglect the extended header and the 3 other optional header bytes
break;
case CODEC_ID_ADPCM_G722:
tResult = 0;
break;
// case CODEC_ID_ADPCM_G726:
default:
tResult = 0;
break;
}
return tResult;
}
int RTP::GetHeaderSizeMax(enum CodecID pCodec)
{
return RTP_HEADER_SIZE + GetPayloadHeaderSizeMax(pCodec);
}
void RTP::OpenRtpPacketStream()
{
mRtpPacketStreamPos = mRtpPacketStream;
}
int RTP::CloseRtpPacketStream(char** pBuffer)
{
*pBuffer = mRtpPacketStream;
return (mRtpPacketStreamPos - mRtpPacketStream);
}
int RTP::StoreRtpPacket(void *pOpaque, uint8_t *pBuffer, int pBufferSize)
{
RTP* tRTPInstance = (RTP*)pOpaque;
#if defined(RTP_DEBUG_PACKET_ENCODER_FFMPEG) || defined(RTCP_DEBUG_PACKET_ENCODER_FFMPEG)
LOGEX(RTP, LOG_VERBOSE, "Storing RTP packet of %d bytes", pBufferSize);
RtpHeader *tRtpHeader = (RtpHeader*)pBuffer;
for (int i = 0; i < 3; i++)
tRtpHeader->Data[i] = ntohl(tRtpHeader->Data[i]);
int tPayloadType = tRtpHeader->PayloadType;
for (int i = 0; i < 3; i++)
tRtpHeader->Data[i] = htonl(tRtpHeader->Data[i]);
RtcpHeader *tRtcpHeader = (RtcpHeader*)pBuffer;
if ((tPayloadType < 72) || (tPayloadType > 76))
{
#ifdef RTP_DEBUG_PACKET_ENCODER_FFMPEG
LogRtpHeader(tRtpHeader);
#endif
}else
{
#ifdef RTCP_DEBUG_PACKET_ENCODER_FFMPEG
LogRtcpHeader(tRtcpHeader);
#endif
}
#endif
if (!tRTPInstance->mEncoderOpened)
LOGEX(RTP, LOG_ERROR, "RTP instance wasn't opened yet, RTP packetizing not available");
// write RTP packet size
unsigned int *tRtpPacketSize = (unsigned int*)tRTPInstance->mRtpPacketStreamPos;
*tRtpPacketSize = 0;
*tRtpPacketSize = htonl((uint32_t) pBufferSize);
// increase RTP stream position by 4
tRTPInstance->mRtpPacketStreamPos += 4;
// copy data from original buffer
char *tRtpPacket = (char*)tRTPInstance->mRtpPacketStreamPos;
memcpy(tRtpPacket, pBuffer, pBufferSize);
// increase RTP stream position by size of RTP packet
tRTPInstance->mRtpPacketStreamPos += pBufferSize;
// return the size of the entire RTP packet buffer as result of write operation
return pBufferSize;
}
bool RTP::RtpCreate(char *&pData, unsigned int &pDataSize, int64_t pPacketPts)
{
AVPacket tPacket;
int tResult;
unsigned int tMp3Hack_EntireBufferSize;
if (!mEncoderOpened)
return false;
if (pData == NULL)
return false;
if (pDataSize <= 0)
return false;
//####################################################################
// for H261 use the internal RTP implementation
//####################################################################
if (mH261UseInternalEncoder)
return RtpCreateH261(pData, pDataSize, pPacketPts);
//####################################################################
// for all non H261 codec use the ffmpeg RTP implementation
//####################################################################
if (mRtpFormatContext)
{
if (mRtpFormatContext->streams[0])
{
if(mRtpFormatContext->streams[0]->codec)
{
if (mStreamCodecID != mRtpFormatContext->streams[0]->codec->codec_id)
LOG(LOG_ERROR, "Unsupported codec change in input stream detected");
}
}
}
// check for supported codecs
if(!IsPayloadSupported(mStreamCodecID))
{
LOG(LOG_ERROR, "Codec %s(%d) is unsupported", mRtpFormatContext->streams[0]->codec->codec_name, mStreamCodecID);
pDataSize = 0;
return true;
}
// save the amount of bytes of the original codec packet
// HINT: we use this to store the size of the original codec packet within MPA header's MBZ entry
// later we use this MBZ entry inside of MediaSourceNet to detect the fragment/packet boundaries
// without this hack we wouldn't be able to provide correct processing because of buggy rfc for MPA payload definition
tMp3Hack_EntireBufferSize = pDataSize;
av_init_packet(&tPacket);
// we only have one stream per media stream
tPacket.stream_index = 0;
tPacket.data = (uint8_t *)pData;
tPacket.size = pDataSize;
tPacket.pts = pPacketPts * CalculateClockRateFactor(); // clock rate adaption according to rfc (mpeg uses 90 kHz)
#ifdef RTP_DEBUG_PACKET_ENCODER
LOG(LOG_VERBOSE, "Encapsulating codec packet:");
LOG(LOG_VERBOSE, " ..pts: %ld", tPacket.pts);
LOG(LOG_VERBOSE, " ..dts: %ld", tPacket.dts);
LOG(LOG_VERBOSE, " ..size: %d", tPacket.size);
LOG(LOG_VERBOSE, " ..pos: %ld", tPacket.pos);
LOG(LOG_VERBOSE, " ..packet pts: ", pPacketPts);
#endif
//####################################################################
// create memory stream and init ffmpeg internal structures
//####################################################################
#ifdef RTP_DEBUG_PACKET_ENCODER
LOG(LOG_VERBOSE, "Encapsulate frame of codec %s and size: %u while maximum resulting RTP packet size is: %d", mRtpFormatContext->streams[0]->codec->codec_name, pDataSize, mAVIOContext->max_packet_size);
#endif
// open RTP stream for av_Write_frame()
OpenRtpPacketStream();
//####################################################################
// send encoded frame to the RTP muxer
//####################################################################
if ((tResult = av_write_frame(mRtpFormatContext, &tPacket)) < 0)
{
LOG(LOG_ERROR, "Couldn't write encoded frame into RTP buffer because of \"%s\".", strerror(AVUNERROR(tResult)));
return false;
}
// close memory stream and get all the resulting packets for sending
char *tData = NULL;
pDataSize = CloseRtpPacketStream(&tData);
pData = (char*)tData;
#ifdef RTP_DEBUG_PACKET_ENCODER
if (pDataSize == 0)
LOG(LOG_WARN, "Resulting RTP stream is empty");
else
LOG(LOG_VERBOSE, "Resulting RTP stream at %p with size of %d bytes", pData, pDataSize);
#endif
//####################################################################
// patch the payload ID for standardized IDs as defined by rfc 3551
// usually ffmpeg uses an ID from the dynamic ID range (96 in most cases)
// which confuses my wireshark and makes debugging impossible ;)
//####################################################################
if ((pData != 0) && (pDataSize > 0))
{
char *tRtpPacket = pData + 4;
uint32_t tRtpPacketSize = 0;
uint32_t tRemainingRtpDataSize = pDataSize;
MPAHeader* tMPAHeader = NULL;
// go through all created RTP packets
do{
tRtpPacketSize = ntohl(*(uint32_t*)(tRtpPacket - 4));
#ifdef RTP_DEBUG_PACKET_ENCODER
LOG(LOG_VERBOSE, "Found RTP packet at %p with size of %u bytes", tRtpPacket, tRtpPacketSize);
#endif
// if there is no packet data we should leave the send loop
if (tRtpPacketSize == 0)
break;
RtpHeader* tRtpHeader = (RtpHeader*)tRtpPacket;
// convert from network to host byte order
for (int i = 0; i < 3; i++)
tRtpHeader->Data[i] = ntohl(tRtpHeader->Data[i]);
#ifdef RTP_DEBUG_PACKET_ENCODER
LOG(LOG_VERBOSE, "RTP packet has payload type: %d", tRtpHeader->PayloadType);
#endif
//#################################################################################
//### patch payload type and hack packet size for MP3 streaming
//### do this only if we don't have a RTCP packet from the ffmpeg lib
//### HINT: ffmpeg uses payload type 14 and several others like dyn. range 96-127
//#################################################################################
bool tRtcpPacket = false;
if (!IS_RTCP_TYPE(tRtpHeader->PayloadType))
{// usual RTP packet