forked from voipmonitor/sniffer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtp.cpp
1319 lines (1183 loc) · 39.4 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
/* Martin Vit [email protected]
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2.
*/
/*
This unit implements class RTP which processes RTP packets and make statistics on them.
Each Call class contains two RTP classes.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <syslog.h>
#include <errno.h>
#include <pcap.h>
#include "voipmonitor.h"
#include "tools.h"
#include "rtp.h"
#include "calltable.h"
#include "codecs.h"
#include "sniff.h"
#include "jitterbuffer/asterisk/channel.h"
#include "jitterbuffer/asterisk/frame.h"
#include "jitterbuffer/asterisk/abstract_jb.h"
#include "jitterbuffer/asterisk/strings.h"
extern int verbosity;
extern int opt_saveRAW; //save RTP payload RAW data?
extern int opt_saveWAV; //save RTP payload RAW data?
extern int opt_saveGRAPH; //save GRAPH data?
extern int opt_gzipGRAPH; //save gzip GRAPH data?
extern int opt_jitterbuffer_f1; // turns off/on jitterbuffer simulator to compute MOS score mos_f1
extern int opt_jitterbuffer_f2; // turns off/on jitterbuffer simulator to compute MOS score mos_f2
extern int opt_jitterbuffer_adapt; // turns off/on jitterbuffer simulator to compute MOS score mos_adapt
extern char opt_cachedir[1024];
extern int opt_savewav_force;
int dtmfdebug = 0;
extern unsigned int graph_delimiter;
using namespace std;
/* Convert timeval structure into microsecond representation */
inline u_int32_t timeval2micro(const timeval t) {
return ((t.tv_sec * 1000000ul) + t.tv_usec);
}
/* Subtract the `struct timeval' values X and Y,
storing the result in RESULT.
Return 1 if the difference is negative, otherwise 0. */
int
timeval_subtract (struct timeval *result, struct timeval x, struct timeval y) {
/* Perform the carry for the later subtraction by updating y. */
if (x.tv_usec < y.tv_usec) {
int nsec = (y.tv_usec - x.tv_usec) / 1000000 + 1;
y.tv_usec -= 1000000 * nsec;
y.tv_sec += nsec;
}
if (x.tv_usec - y.tv_usec > 1000000) {
int nsec = (x.tv_usec - y.tv_usec) / 1000000;
y.tv_usec += 1000000 * nsec;
y.tv_sec -= nsec;
}
/* Compute the time remaining to wait.
tv_usec is certainly p60itive. */
result->tv_sec = x.tv_sec - y.tv_sec;
result->tv_usec = x.tv_usec - y.tv_usec;
/* Return 1 if result is negative. */
return x.tv_sec < y.tv_sec;
}
int get_ticks_bycodec(int codec) {
switch(codec) {
case PAYLOAD_PCMU:
return 8;
break;
case PAYLOAD_GSM:
return 8;
break;
case PAYLOAD_G723:
return 8;
break;
case PAYLOAD_PCMA:
return 8;
break;
case PAYLOAD_G722:
return 8;
break;
case PAYLOAD_G729:
return 8;
break;
case PAYLOAD_ILBC:
return 8;
break;
case PAYLOAD_SPEEX:
return 8;
break;
case PAYLOAD_SILK8:
return 8;
break;
case PAYLOAD_SILK12:
return 12;
break;
case PAYLOAD_SILK16:
return 16;
break;
case PAYLOAD_SILK24:
return 24;
break;
case PAYLOAD_ISAC16:
return 16;
break;
case PAYLOAD_ISAC32:
return 32;
break;
case PAYLOAD_OPUS:
return 8;
break;
case PAYLOAD_OPUS12:
return 12;
break;
case PAYLOAD_OPUS16:
return 16;
break;
case PAYLOAD_OPUS24:
return 24;
break;
case PAYLOAD_OPUS48:
return 48;
break;
default:
return 8;
}
}
/* constructor */
RTP::RTP()
: graph(this) {
samplerate = 8000;
first = true;
first_packet_time = 0;
first_packet_usec = 0;
s = new source;
memset(s, 0, sizeof(source));
memset(&stats, 0, sizeof(stats));
memset(&rtcp, 0, sizeof(rtcp));
nintervals = 1;
saddr = 0;
daddr = 0;
ssrc = 0;
ssrc2 = 0;
gfilename[0] = '\0';
gfileRAW = NULL;
channel_fix1 = (ast_channel*)calloc(1, sizeof(*channel_fix1));
channel_fix1->jitter_impl = 0; // fixed
channel_fix1->jitter_max = 60;
channel_fix1->jitter_resync_threshold = 50;
channel_fix1->last_datalen = 0;
channel_fix1->lastbuflen = 0;
channel_fix1->resync = 1;
channel_fix1->audiobuf = NULL;
channel_fix2 = (ast_channel*)calloc(1, sizeof(*channel_fix2));
channel_fix2->jitter_impl = 0; // fixed
channel_fix2->jitter_max = 200;
channel_fix2->jitter_resync_threshold = 200;
channel_fix2->last_datalen = 0;
channel_fix2->lastbuflen = 0;
channel_fix2->resync = 1;
channel_fix2->audiobuf = NULL;
channel_adapt = (ast_channel*)calloc(1, sizeof(*channel_adapt));
channel_adapt->jitter_impl = 1; // adaptive
channel_adapt->jitter_max = 500;
channel_adapt->jitter_resync_threshold = 500;
channel_adapt->last_datalen = 0;
channel_adapt->lastbuflen = 0;
channel_adapt->resync = 1;
channel_adapt->audiobuf = NULL;
channel_record = (ast_channel*)calloc(1, sizeof(*channel_record));
channel_record->jitter_impl = 0; // fixed
channel_record->jitter_max = 60;
channel_record->jitter_resync_threshold = 1000;
channel_record->last_datalen = 0;
channel_record->lastbuflen = 0;
channel_record->resync = 0;
channel_record->audiobuf = NULL;
//channel->name = "SIP/fixed";
frame = (ast_frame*)calloc(1, sizeof(*frame));
frame->frametype = AST_FRAME_VOICE;
lastframetype = AST_FRAME_VOICE;
//frame->src = "DUMMY";
last_seq = 0;
last_ts = 0;
packetization = 0;
last_packetization = 0;
packetization_iterator = 0;
first_codec = -1;
prev_payload = -1;
prev_codec = -1;
payload2 = -1;
codec = -1;
for(int i = 0; i < MAX_RTPMAP; i++) {
rtpmap[i] = 0;
}
gfileRAW_buffer = NULL;
sid = false;
prev_sid = false;
call_owner = NULL;
pinformed = 0;
last_end_timestamp = 0;
lastdtmf = 0;
forcemark = 0;
}
/* destructor */
RTP::~RTP() {
/*
if(packetization)
RTP::dump();
*/
//Call *owner = (Call*)call_owner;
if(verbosity > 9) {
RTP::dump();
}
if(gfileRAW) {
jitterbuffer_fixed_flush(channel_record);
fclose(gfileRAW);
}
delete s;
ast_jb_destroy(channel_fix1);
ast_jb_destroy(channel_fix2);
ast_jb_destroy(channel_adapt);
ast_jb_destroy(channel_record);
free(channel_fix1);
free(channel_fix2);
free(channel_adapt);
free(channel_record);
free(frame);
if(gfileRAW_buffer) {
free(gfileRAW_buffer);
}
}
const unsigned int RTP::get_payload_len() {
payload_data = data + sizeof(RTPFixedHeader);
payload_len = len - sizeof(RTPFixedHeader);
if(getPadding()) {
/*
* If set, this packet contains one or more additional padding
* bytes at the end which are not part of the payload. The last
* byte of the padding contains a count of how many padding bytes
* should be ignored. Padding may be needed by some encryption
* algorithms with fixed block sizes or for carrying several RTP
* packets in a lower-layer protocol data unit.
*/
payload_len -= ((u_int8_t *)data)[payload_len - 1];
}
if(getCC() > 0) {
/*
* The number of CSRC identifiers that follow the fixed header.
*/
payload_data += 4 * getCC();
payload_len -= 4 * getCC();
}
if(getExtension()) {
/*
* If set, the fixed header is followed by exactly one header extension.
*/
extension_hdr_t *rtpext;
if (payload_len < 4)
payload_len = 0;
// the extension, if present, is after the CSRC list.
rtpext = (extension_hdr_t *)((u_int8_t *)payload_data);
payload_data += sizeof(extension_hdr_t) + rtpext->length;
payload_len -= sizeof(extension_hdr_t) + rtpext->length;
}
return payload_len;
}
/* flush jitterbuffer */
void RTP::jitterbuffer_fixed_flush(struct ast_channel *jchannel) {
jb_fixed_flush_deliver(channel_record);
}
/* add silence to RTP stream from last packet time to current time which is in header->ts */
void
RTP::jt_tail(struct pcap_pkthdr *header) {
if(!ast_jb_test(channel_record)) {
// there is no ongoing recording, return
return;
}
/* protect for endless loops (it cannot happen in theory but to be sure */
if(packetization <= 0) {
Call *owner = (Call*)call_owner;
if(owner) {
syslog(LOG_ERR, "call-id[%s]: packetization is 0 in jitterbuffer function.", owner->get_fbasename_safe());
} else {
syslog(LOG_ERR, "call-id[N/A]: packetization is 0 in jitterbuffer function.");
}
return;
}
/* calculate time difference between last packet and current packet + packetization time*/
if(channel_record->last_ts.tv_sec == 0) {
// previouuse tv_sec is not set, set it
memcpy(&channel_record->last_ts, &header->ts, sizeof(timeval));
return;
}
int msdiff = ast_tvdiff_ms(header->ts, channel_record->last_ts);
msdiff -= packetization;
while( msdiff >= packetization ) {
ast_jb_get_and_deliver(channel_record, &channel_record->last_ts);
/* adding packetization time to last_ts time */
struct timeval tmp = ast_tvadd(channel_record->last_ts, ast_samp2tv(packetization, 1000));
memcpy(&channel_record->last_ts, &tmp, sizeof(struct timeval));
msdiff -= packetization;
}
}
#if 1
/* simulate jitterbuffer */
void
RTP::jitterbuffer(struct ast_channel *channel, int savePayload) {
if(codec == PAYLOAD_TELEVENT) return;
Call *owner = (Call*)call_owner;
if(owner and savePayload and owner->silencerecording) {
// skip recording
frame->skip = 1;
} else {
frame->skip = 0;
}
struct timeval tsdiff;
switch(codec) {
case PAYLOAD_OPUS12:
frame->ts = getTimestamp() / 12;
frame->len = packetization * 2 / 3;
break;
case PAYLOAD_ISAC16:
case PAYLOAD_SILK16:
case PAYLOAD_OPUS16:
frame->ts = getTimestamp() / 16;
frame->len = packetization / 2;
break;
case PAYLOAD_SILK24:
case PAYLOAD_OPUS24:
frame->ts = getTimestamp() / 24;
frame->len = packetization / 3;
break;
case PAYLOAD_OPUS48:
frame->ts = getTimestamp() / 48;
frame->len = packetization / 6;
break;
default:
frame->ts = getTimestamp() / 8;
frame->len = packetization;
}
frame->marker = getMarker();
frame->seqno = getSeqNum();
channel->codec = codec;
memcpy(&frame->delivery, &header->ts, sizeof(struct timeval));
/* protect for endless loops (it cannot happen in theory but to be sure */
if(packetization <= 0) {
if(pinformed == 0) {
if(owner) {
syslog(LOG_ERR, "call-id[%s] ssrc[%x]: packetization is 0 in jitterbuffer function.", owner->get_fbasename_safe(), getSSRC());
} else {
syslog(LOG_ERR, "call-id[N/A] ssrc[%x]: packetization is 0 in jitterbuffer function.", getSSRC());
}
}
pinformed = 1;
return;
} else {
pinformed = 0;
}
if(savePayload) {
struct iphdr2 *header_ip = (struct iphdr2 *)(data - sizeof(struct iphdr2) - sizeof(udphdr2));
int mylen = MIN(len, ntohs(header_ip->tot_len) - header_ip->ihl * 4 - sizeof(udphdr2));
/* get RTP payload header and datalen */
payload_data = data + sizeof(RTPFixedHeader);
payload_len = mylen - sizeof(RTPFixedHeader);
if(getPadding()) {
/*
* If set, this packet contains one or more additional padding
* bytes at the end which are not part of the payload. The last
* byte of the padding contains a count of how many padding bytes
* should be ignored. Padding may be needed by some encryption
* algorithms with fixed block sizes or for carrying several RTP
* packets in a lower-layer protocol data unit.
*/
payload_len -= ((u_int8_t *)data)[payload_len - 1];
}
if(getCC() > 0) {
/*
* The number of CSRC identifiers that follow the fixed header.
*/
payload_data += 4 * getCC();
payload_len -= 4 * getCC();
}
if(getExtension()) {
/*
* If set, the fixed header is followed by exactly one header extension.
*/
extension_hdr_t *rtpext;
if (payload_len < 4)
payload_len = 0;
// the extension, if present, is after the CSRC list.
rtpext = (extension_hdr_t *)((u_int8_t *)payload_data);
payload_data += sizeof(extension_hdr_t) + rtpext->length;
payload_len -= sizeof(extension_hdr_t) + rtpext->length;
}
frame->data = payload_data;
frame->datalen = payload_len > 0 ? payload_len : 0; /* ensure that datalen is never negative */
if(getPayload() == PAYLOAD_G723) {
// voipmonitor does not handle SID packets well (silence packets) it causes out of sync
if((unsigned char)payload_data[0] & 2) {
/* check if jitterbuffer is already created. If not we have to create it because
if call starts with SID packets first it will than cause out of sync calls
*/
if(ast_test_flag(&channel->jb, (1 << 2))) {
// jitterbuffer is created so we can skip SID packets now
return;
}
}
}
if(codec == PAYLOAD_G729 and (payload_len == 2 or payload_len == 12)) {
return;
}
channel->rawstream = gfileRAW;
Call *owner = (Call*)call_owner;
if(iscaller) {
owner->codec_caller = codec;
if(owner->audiobuffer1) {
channel->audiobuf = owner->audiobuffer1;
}
} else {
owner->codec_called = codec;
if(owner->audiobuffer2) {
channel->audiobuf = owner->audiobuffer2;
}
}
if(payload_len > 0) {
channel->last_datalen = frame->datalen;
}
} else {
frame->datalen = 0;
frame->data = NULL;
channel->rawstream = NULL;
}
// create jitter buffer structures
ast_jb_do_usecheck(channel, &header->ts);
if(!channel->jb_reseted) {
// initializing jitterbuffer
if(savePayload) {
channel_record->jitter_max = frame->len * 3;
}
ast_jb_empty_and_reset(channel);
channel->jb_reseted = 1;
memcpy(&channel->last_ts, &header->ts, sizeof(struct timeval));
ast_jb_put(channel, frame, &header->ts);
return;
}
/* calculate time difference between last packet and current packet + packetization time*/
int msdiff = ast_tvdiff_ms( header->ts, ast_tvadd(channel->last_ts, ast_samp2tv(packetization, 1000)) );
//printf("ms:%d\n", msdiff);
if(msdiff > packetization * 1000) {
// difference is too big, reseting last_ts to current packet. If we dont check this it could happen to run while cycle endlessly
memcpy(&channel->last_ts, &header->ts, sizeof(struct timeval));
ast_jb_put(channel, frame, &header->ts);
if(verbosity > 4) syslog(LOG_ERR, "big timestamp jump (msdiff:%d packetization: %d) in this file: %s\n", msdiff, packetization, gfilename);
return;
}
/* between last packet and current packet is big timestamp difference and it could count
* interpolated framed although it was silence so calculate real number of packets based
* on timestamps in packet header, timestamps in rtp header and sequence numbers between
* last packet and current packet
*/
// relative time difference calculated from packet sequence
u_int32_t sequencems = (frame->seqno - last_seq) * packetization;
/* difference (in ms) between timestamps in packet header and rtp timestamps. this should
* be ideally equel to zero. Negative values mean that packet arrives earlier and positive
* values indicates that packet was late
*/
long double transit = (timeval_subtract(&tsdiff, header->ts, s->lastTimeRecJ) ? -timeval2micro(tsdiff)/1000.0 : timeval2micro(tsdiff)/1000.0) - (double)(getTimestamp() - s->lastTimeStampJ)/(double)samplerate/1000;
/* and now if there is bigger (lets say one second) timestamp difference (calculated from packet headers)
* between two last packets and transit time is equel or smaller than sequencems (with 200ms toleration),
* it was silence and manually mark the frame which indicates to not count interpolated frame and resynchronize jitterbuffer
*/
if( msdiff > 1000 and (transit <= (sequencems + 200)) ) {
if(verbosity > 4) printf("jitterbuffer: manually marking packet, msdiff(%d) > 1000 and transit (%Lf) <= ((sequencems(%u) + 200)\n", msdiff, transit, sequencems);
frame->marker = 1;
}
// fetch packet from jitterbuffer every 20 ms regardless on packet loss or delay
while( msdiff >= packetization ) {
if(frame->marker or lastframetype == AST_FRAME_DTMF) {
/* if last frame was marked or DTMF, ignore interpolated frames */
channel->last_loss_burst = 0;
}
ast_jb_get_and_deliver(channel, &channel->last_ts);
/* adding packetization time to last_ts time */
struct timeval tmp = ast_tvadd(channel->last_ts, ast_samp2tv(frame->len, 1000));
memcpy(&channel->last_ts, &tmp, sizeof(struct timeval));
msdiff -= packetization;
}
ast_jb_put(channel, frame, &header->ts);
}
#endif
void
RTP::process_dtmf_rfc2833() {
unsigned int seqno = getSeqNum();
unsigned int event, event_end, samples;
char resp = 0;
unsigned int timestamp = getTimestamp();
unsigned char *pdata = data + sizeof(RTPFixedHeader);
/* Figure out event, event end, and samples */
event = ntohl(*((unsigned int *)(pdata)));
event >>= 24;
event_end = ntohl(*((unsigned int *)(pdata)));
event_end <<= 8;
event_end >>= 24;
samples = ntohl(*((unsigned int *)(pdata)));
samples &= 0xFFFF;
if(dtmfdebug) syslog(LOG_ERR, "Got RTP RFC2833 from %u (seq %-6.6u, ts %-6.6u, len %-6.6u, mark %d, event %08x, end %d, duration %-5.5d) \n",
getMarker(), seqno, timestamp, len, (getMarker()?1:0), event, ((event_end & 0x80)?1:0), samples);
/* Figure out what digit was pressed */
if (event < 10) {
resp = '0' + event;
} else if (event < 11) {
resp = '*';
} else if (event < 12) {
resp = '#';
} else if (event < 16) {
resp = 'A' + (event - 12);
} else if (event < 17) { /* Event 16: Hook flash */
resp = 'X';
} else {
/* Not a supported event */
//syslog(LOG_ERR, "Ignoring RTP 2833 Event: %08x. Not a DTMF Digit.\n", event);
return;
}
if ((last_end_timestamp != timestamp) || (lastdtmf && lastdtmf != resp)) {
lastdtmf = resp;
if(dtmfdebug) syslog(LOG_ERR, "dtmfevent %c\n", resp);
last_end_timestamp = timestamp;
Call *owner = (Call*)call_owner;
if(owner) {
owner->handle_dtmf(resp, ts2double(header->ts.tv_sec, header->ts.tv_usec), saddr, daddr);
}
}
return;
}
/* read rtp packet */
void
RTP::read(unsigned char* data, int len, struct pcap_pkthdr *header, u_int32_t saddr, u_int32_t daddr, int seeninviteok) {
this->data = data;
this->len = len;
this->header = header;
this->saddr = saddr;
this->daddr = daddr;
if(this->first_packet_time == 0 and this->first_packet_usec == 0) {
this->first_packet_time = header->ts.tv_sec;
this->first_packet_usec = header->ts.tv_usec;
}
Call *owner = (Call*)call_owner;
//if(getSSRC() != 0xfbff7e51) return;
if(getVersion() != 2) {
return;
}
seq = getSeqNum();
if(seq == last_seq) {
// ignore duplicated RTP packets
return;
}
int curpayload = getPayload();
// printf("p[%d]\n", curpayload);
if((codec == -1 || (curpayload != prev_payload))) {
if(curpayload >= 96 && curpayload <= 127) {
/* for dynamic payload we look into rtpmap */
for(int i = 0; i < MAX_RTPMAP; i++) {
if(rtpmap[i] != 0 && curpayload == rtpmap[i] / 1000) {
codec = rtpmap[i] - curpayload * 1000;
}
}
} else {
codec = curpayload;
}
}
/* in case there was packet loss we must predict lastTimeStamp to not add nonexistant delays */
forcemark = 0;
if(last_seq != 0 and ((last_seq + 1) != seq)) {
if(s->lastTimeStamp == getTimestamp() - samplerate / 1000 * packetization) {
// there was packet loss but the timestamp is like there was no packet loss
if(opt_jitterbuffer_adapt) {
ast_jb_empty_and_reset(channel_adapt);
ast_jb_destroy(channel_adapt);
}
if(opt_jitterbuffer_f1) {
ast_jb_empty_and_reset(channel_fix1);
ast_jb_destroy(channel_fix1);
}
if(opt_jitterbuffer_f2) {
ast_jb_empty_and_reset(channel_fix2);
ast_jb_destroy(channel_fix2);
}
forcemark = 1;
}
// this fixes jumps in .graph in case of pcaket loss
s->lastTimeStamp = getTimestamp() - samplerate / 1000 * packetization;
struct timeval tmp = ast_tvadd(header->ts, ast_samp2tv(packetization, 1000));
memcpy(&s->lastTimeRec, &tmp, sizeof(struct timeval));
}
if(getMarker()) {
s->lastTimeStamp = getTimestamp() - samplerate / 1000 * packetization;
struct timeval tmp = ast_tvadd(header->ts, ast_samp2tv(packetization, 1000));
memcpy(&s->lastTimeRec, &tmp, sizeof(struct timeval));
}
// ignore CNG
if(curpayload == 13 or curpayload == 19) {
last_seq = seq;
if(update_seq(seq)) {
update_stats();
}
return;
}
if(!owner) return;
if(iscaller) {
if(owner->lastcallerrtp and owner->lastcallerrtp != this) {
// reset last sequence
s->cycles = s->cycles - s->base_seq + s->max_seq;
s->base_seq = seq;
s->max_seq = seq;
}
} else {
if(owner->lastcalledrtp and owner->lastcalledrtp != this) {
s->cycles = s->cycles - s->base_seq + s->max_seq;
s->base_seq = seq;
s->max_seq = seq;
}
}
if(owner->forcemark[iscaller]) {
// on reinvite (which indicates forcemark[iscaller] completely reset rtp jitterbuffer simulator and
// there are cases where on reinvite rtp stream stops and there is gap in rtp sequence and timestamp but
// since it was reinvite the stream just continues as expected
if(opt_jitterbuffer_adapt) {
ast_jb_empty_and_reset(channel_adapt);
ast_jb_destroy(channel_adapt);
}
if(opt_jitterbuffer_f1) {
ast_jb_empty_and_reset(channel_fix1);
ast_jb_destroy(channel_fix1);
}
if(opt_jitterbuffer_f2) {
ast_jb_empty_and_reset(channel_fix2);
ast_jb_destroy(channel_fix2);
}
owner->forcemark[iscaller] = 0;
forcemark = 1;
// this fixes jumps in .graph in case of pcaket loss
s->lastTimeStamp = getTimestamp() - samplerate / 1000 * packetization;
struct timeval tmp = ast_tvadd(header->ts, ast_samp2tv(packetization, 1000));
memcpy(&s->lastTimeRec, &tmp, sizeof(struct timeval));
// reset last sequence
s->cycles = s->cycles - s->base_seq + s->max_seq;
s->base_seq = seq;
s->max_seq = seq;
}
if(codec == PAYLOAD_TELEVENT) {
process_dtmf_rfc2833();
}
/* codec changed */
if(curpayload != prev_payload and codec != PAYLOAD_TELEVENT and prev_codec != PAYLOAD_TELEVENT) {
switch(codec) {
case PAYLOAD_SILK12:
case PAYLOAD_OPUS12:
samplerate = 12000;
break;
case PAYLOAD_ISAC16:
case PAYLOAD_SILK16:
case PAYLOAD_OPUS16:
samplerate = 16000;
break;
case PAYLOAD_SILK24:
case PAYLOAD_OPUS24:
samplerate = 24000;
break;
case PAYLOAD_ISAC32:
samplerate = 32000;
break;
case PAYLOAD_OPUS48:
samplerate = 48000;
break;
default:
samplerate = 8000;
}
if(iscaller) {
owner->last_callercodec = codec;
} else {
owner->last_calledcodec = codec;
}
if(opt_saveRAW || opt_savewav_force || (owner && (owner->flags & FLAG_SAVEWAV)) ||
(owner && (owner->audiobuffer1 || owner->audiobuffer2))// if recording requested
) {
// if(verbosity > 0) syslog(LOG_ERR, "converting WAV! [%u]\n", owner->flags);
/* open file for raw codec */
unsigned long unique = getTimestamp();
char tmp[1024];
sprintf(tmp, "%s.%d.%lu.%d.%ld.%ld.raw", basefilename, ssrc_index, unique, codec, header->ts.tv_sec, header->ts.tv_usec);
if(gfileRAW) {
//there is already opened gfileRAW
jitterbuffer_fixed_flush(channel_record);
fclose(gfileRAW);
} else {
/* look for the last RTP stream belonging to this direction and let jitterbuffer put silence
* which fills potentionally gap between this and previouse RTP so it will stay in sync with
* the other direction of call
*/
RTP *prevrtp = (RTP*)(owner->rtp_prev[iscaller]);
if(prevrtp && prevrtp != this) {
prevrtp->data = data;
prevrtp->len = len;
prevrtp->header = header;
prevrtp->saddr = saddr;
prevrtp->daddr = daddr;
if(owner->flags & FLAG_RUNAMOSLQO or owner->flags & FLAG_RUNBMOSLQO) {
// MOS LQO is calculated only if the call is connected
if(owner->connect_time) {
prevrtp->jitterbuffer(prevrtp->channel_record, opt_saveRAW || opt_savewav_force || (owner->flags & FLAG_SAVEWAV) || (owner && (owner->audiobuffer1 || owner->audiobuffer2)));
}
} else {
prevrtp->jitterbuffer(prevrtp->channel_record, opt_saveRAW || opt_savewav_force || (owner->flags & FLAG_SAVEWAV) || (owner && (owner->audiobuffer1 || owner->audiobuffer2)));
}
}
}
gfileRAW = fopen(tmp, "w");
if(!gfileRAW_buffer) {
gfileRAW_buffer = (char*)malloc(32768 * sizeof(char));
if(gfileRAW_buffer == NULL) {
syslog(LOG_ERR, "Cannot allocate memory for gfileRAW_buffer - low memory this is FATAL");
exit(2);
}
}
if(!gfileRAW) {
syslog(LOG_ERR, "Cannot open file %s for writing: %s\n", tmp, strerror (errno));
exit(2);
}
if(gfileRAW_buffer) {
setvbuf(gfileRAW, gfileRAW_buffer, _IOFBF, 32768);
}
/* write file info to "playlist" */
sprintf(tmp, "%s.rawInfo", basefilename);
FILE *gfileRAWInfo = fopen(tmp, "a");
if(gfileRAWInfo) {
fprintf(gfileRAWInfo, "%d:%lu:%d:%ld:%ld\n", ssrc_index, unique, codec, header->ts.tv_sec, header->ts.tv_usec);
fclose(gfileRAWInfo);
} else {
syslog(LOG_ERR, "Cannot open file %s.rawInfo for writing\n", basefilename);
}
}
}
if(first_codec < 0 && codec != PAYLOAD_TELEVENT && codec != 13 && codec != 19) {
/* save payload to statistics based on first payload. TODO: what if payload is dynamically changing? */
first_codec = codec;
}
if(codec == PAYLOAD_TELEVENT) {
frame->frametype = AST_FRAME_DTMF;
} else {
frame->frametype = AST_FRAME_VOICE;
}
frame->lastframetype = (enum ast_frame_type)(lastframetype);
if(packetization_iterator == 0 || packetization_iterator == 1) {
// we dont know packetization yet. Behave differently n G723 codec
if(curpayload == PAYLOAD_G723) {
default_packetization = 30;
/* check if RTP packet is not Silence packet (SID). Silence packets can have different
packetization and if call starts with SID packets it will guess wrong packetization.
typical sitation is for 60ms packetization and 30ms SID packetization */
payload_data = data + sizeof(RTPFixedHeader);
sid = (unsigned char)payload_data[0] & 2;
} else {
sid = false;
default_packetization = 20;
}
}
if(packetization_iterator == 0) {
if(last_ts != 0 && seq == (last_seq + 1) && (prev_codec != PAYLOAD_TELEVENT && codec != PAYLOAD_TELEVENT) && !sid && !prev_sid) {
// sequence numbers are ok, we can calculate packetization
if(curpayload == PAYLOAD_G729) {
// if G729 packet len is 20, packet len is 20ms. In other cases - will be added later (do not have 40ms packetizations samples right now)
if(get_payload_len() == 20) {
packetization = 20;
} else {
packetization = (getTimestamp() - last_ts) / 8;
}
} else {
packetization = (getTimestamp() - last_ts) / 8;
}
if(packetization > 0) {
last_packetization = packetization;
packetization_iterator++;
}
}
#if 1
// new way of getting packetization from packet datalen
if(curpayload == PAYLOAD_PCMU or curpayload == PAYLOAD_PCMA) {
channel_fix1->packetization = default_packetization =
channel_fix2->packetization = channel_adapt->packetization =
channel_record->packetization = packetization = get_payload_len() / 8;
if(packetization >= 10) {
if(verbosity > 3) printf("packetization:[%d] ssrc[%x]\n", packetization, getSSRC());
packetization_iterator = 10; // this will cause that packetization is estimated as final
if(opt_jitterbuffer_f1)
jitterbuffer(channel_fix1, 0);
if(opt_jitterbuffer_f2)
jitterbuffer(channel_fix2, 0);
if(opt_jitterbuffer_adapt)
jitterbuffer(channel_adapt, 0);
}
}
// new way of getting packetization from packet datalen
if(curpayload == PAYLOAD_GSM) {
channel_fix1->packetization = default_packetization =
channel_fix2->packetization = channel_adapt->packetization =
channel_record->packetization = packetization = get_payload_len() / 33 * 20;
if(packetization >= 10) {
if(verbosity > 3) printf("packetization:[%d] ssrc[%x]\n", packetization, getSSRC());
packetization_iterator = 10; // this will cause that packetization is estimated as final
if(opt_jitterbuffer_f1)
jitterbuffer(channel_fix1, 0);
if(opt_jitterbuffer_f2)
jitterbuffer(channel_fix2, 0);
if(opt_jitterbuffer_adapt)
jitterbuffer(channel_adapt, 0);
}
}
#endif
/* for recording, we cannot loose any packet */
if(opt_saveRAW || opt_savewav_force || (owner->flags & FLAG_SAVEWAV) || (owner && (owner->audiobuffer1 || owner->audiobuffer2))) { // if recording requested
if(packetization < 10) {
packetization = channel_record->packetization = default_packetization;
}
if(owner->flags & FLAG_RUNAMOSLQO or owner->flags & FLAG_RUNBMOSLQO) {
if(owner->connect_time) {
jitterbuffer(channel_record, opt_saveRAW || opt_savewav_force || (owner->flags & FLAG_SAVEWAV) || (owner && (owner->audiobuffer1 || owner->audiobuffer2)));
}
} else {
jitterbuffer(channel_record, opt_saveRAW || opt_savewav_force || (owner->flags & FLAG_SAVEWAV) || (owner && (owner->audiobuffer1 || owner->audiobuffer2)));
}
}
} else if(packetization_iterator == 1) {
if(last_ts != 0 && seq == (last_seq + 1) && codec != PAYLOAD_TELEVENT && prev_codec != PAYLOAD_TELEVENT && !sid && !prev_sid) {
// sequence numbers are ok, we can calculate packetization
if(curpayload == PAYLOAD_G729) {
// if G729 packet len is 20, packet len is 20ms. In other cases - will be added later (do not have 40ms packetizations samples right now)
if(get_payload_len() == 20) {
packetization = 20;
} else {
packetization = (getTimestamp() - last_ts) / 8;
}
} else {
packetization = (getTimestamp() - last_ts) / 8;
}
// now make packetization average
packetization = (packetization + last_packetization) / 2;
if(packetization <= 0 or getMarker()) {
// packetization failed or Marker bit is set, fall back to start
packetization_iterator = 0;
/* for recording, we cannot loose any packet */
if(opt_saveRAW || opt_savewav_force || (owner->flags & FLAG_SAVEWAV) ||
(owner && (owner->audiobuffer1 || owner->audiobuffer2))// if recording requested
){
packetization = channel_record->packetization = default_packetization;
if(owner->flags & FLAG_RUNAMOSLQO or owner->flags & FLAG_RUNBMOSLQO) {
if(owner->connect_time) {
jitterbuffer(channel_record, 1);
}
} else {
jitterbuffer(channel_record, 1);
}
}
} else {
packetization_iterator++;
channel_fix1->packetization = channel_fix2->packetization = channel_adapt->packetization = channel_record->packetization = packetization;
if(verbosity > 3) printf("[%x] packetization:[%d]\n", getSSRC(), packetization);
if(opt_jitterbuffer_f1)
jitterbuffer(channel_fix1, 0);
if(opt_jitterbuffer_f2)
jitterbuffer(channel_fix2, 0);
if(opt_jitterbuffer_adapt)
jitterbuffer(channel_adapt, 0);
if(opt_saveRAW || opt_savewav_force || (owner->flags & FLAG_SAVEWAV) ||
(owner && (owner->audiobuffer1 || owner->audiobuffer2))// if recording requested
){
if(owner->flags & FLAG_RUNAMOSLQO or owner->flags & FLAG_RUNBMOSLQO) {
if(owner->connect_time) {
jitterbuffer(channel_record, 1);
}
} else {
jitterbuffer(channel_record, 1);
}
}
}
} else {
packetization_iterator = 0;
/* for recording, we cannot loose any packet */
if(opt_saveRAW || opt_savewav_force || (owner->flags & FLAG_SAVEWAV) ||