qstream 71.9 KB
Newer Older
Olav Kvittem's avatar
Olav Kvittem committed
1
2
3
#!/usr/bin/perl

# compute packet stream quality statistics for UDP/RTP from network or captured files(pcap)
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
4
5
6
# Base Olav Kvittem
# Mpeg support Odd Rune Mykkeltveit Lykkbo,  2009-2010
# Mos values computation Gurvinder Singh, 2010-05-07
Olav Kvittem's avatar
Olav Kvittem committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# use Socket;
use IO::Socket qw(:DEFAULT :crlf);
use IO::Socket::INET;
use IO::Socket::Multicast;
use IO::Select;
use Net::Pcap;
use NetPacket::Ethernet qw(:strip);
use NetPacket::IP;
use NetPacket::IP qw(:protos);
use NetPacket::UDP;
use Net::RTP;
use Net::RTP::Packet;
use Time::HiRes qw/ sleep time tv_interval gettimeofday/;
use Data::Dumper;
Olav Kvittem's avatar
Olav Kvittem committed
22
23
24
#use bigint qw/ hex oct/;
use Math::BigInt;
use Math::BigFloat;
25
use Carp;
Olav Kvittem's avatar
Olav Kvittem committed
26
27
28

use constant MTU => 1580;

Olav Kvittem's avatar
Olav Kvittem committed
29
30
31
32

#use mpegpackets;


Olav Kvittem's avatar
Olav Kvittem committed
33
34
35
36
37
$DEFAULT_PORT = 1955;
my $timeout=1 ; # frac seconds to wait for receiving packets

require "newgetopt.pl";
$usage="$0 [option]... [file...|ip/|:port]...
Olav Kvittem's avatar
Olav Kvittem committed
38
39
40
41
42
43
44
45
46
-list list flows in files
-dump dump data part to file
-format [full|pretty] print full numbers foror short pretty numbers
-net open network stream rather than file(s)
-crude the log is from crude
-bins bins for gaps in ms : b1,b2,,,
-log log gaps longer than 1 (use with crude)
-rtp look forinto rtp headers (default just udp)
-mpeg decode mpeg-2 transport stream and look for sequence and mediatime
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
47
48
-rtt  roundtrip  - round trip time in ms (for MOS)
-codec codec - codec G.711, G.723.1, G.729A, iLBC (G.711)
Olav Kvittem's avatar
Olav Kvittem committed
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
-pcap listen to all multicast groups with pcap at the same time
-period seconds - period in seconds between stats output
-nperiod number of periodes
-last seconds - exit after seconds
-packets packets - exit after packets
-src source - limit stats to given source
-flow_key flow key - limit stats to this flow(src_ip:src_port->dest_ip:dest_port)
-flow_no flow no - limit stats to this flow no from -list
-flow_min numb  - discard flows with less packets that numb
-nohead - no headings for batch use
-id name - report name instead of flow_key in flows
-sum name - make a summary of all flows to name rather than per flow
-ttl - print ttl values for stream
-verbose - more details packet distances and sizes
-debug  - print debugging info
-help/h this message
Olav Kvittem's avatar
Olav Kvittem committed
65
\n";
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
66
@opts=('list', 'fullformat', 'net', 'rtp', 'mpeg', 'pcap', 'crude', 'bins=s', 'log', 'nperiod=s', 'period=s', 'last=s', 'packets=s', 'src=s', 'flow_key=s', 'flow_no=s', 'flow_min=s', 'nohead', 'dump=s', 'format=s', 'id=s', 'sum=s', 'ttl', 'rtt=s', 'codec=s', 'log', 'verbose', 'v', 'help', 'h', 'debug');
Olav Kvittem's avatar
Olav Kvittem committed
67
68
69
70
&NGetOpt(@opts) || die $usage;
die $usage if $opt_h or $opt_help;
$continous= ! $opt_packets;
$opt_v=$opt_v or $opt_verbose;
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
71
72
73
74
my $codec = $opt_codec || 'G.711';
my $rtt = $opt_rtt || 10;		# ms round trip time of the connection


Olav Kvittem's avatar
Olav Kvittem committed
75
76
my @streams=@ARGV;

Olav Kvittem's avatar
Olav Kvittem committed
77
78
79
80
if ($opt_bins){
    @bins=split(/,/, $opt_bins);
}

Olav Kvittem's avatar
Olav Kvittem committed
81
82
83
84
85
86
87
88
89
90
91
my $format = $opt_format || "pretty";


my %hdr=();
my $err="";
my $us=0; # current packet time in us
my $nkill=0;
my $nint=0;
my $n_packets=0;
my $endstream=0;

Olav Kvittem's avatar
Olav Kvittem committed
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
#MPEG-TS measurement globals (most are reset in init)
my $CHECK_NUM_TSP = 2;
#globals for mpeg ts 
my @cc = ();
my $discontinuities = 0;
my %last_ccs = ();
my $packets_between_pcr = 0;
#my $PTS_MAX = 95443.7176888888888888
my $PTS_MAX = 95443;
my $PCR_MAX = 95443;
# pcr_stats {filename/handle}
my %pcr_stats = ();
#PTS-stats {filename/handle}
my %pts_stats = ();
my %mpeg_stats = ();
#PTS stuff
#my $real_time = time();
my $late_video_packets = 0;

#CC distribution
my $num_cc = 0;
my %cc_dist = ();
my %pid_next_cc = ();

my %dist1 = ();
my %dist2 = ();

$opt_period = $opt_last if not $opt_period;
#MPEG-TS END




125
126
127
$SIG{USR2} = sub {confess "Caught by SIGUSR2"; };


Olav Kvittem's avatar
Olav Kvittem committed
128
129
130
131
132
133
134
$SIG{INT} = sub { $uninterrupted=0; # return if $nint++  < 1;
		  &display_stats();  die "End after interrupt.\n";exit(0) };
$SIG{KILL} = sub { $uninterrupted=0; # return if $nkill++ < 1;
		   &display_stats();  die "End after kill.\n";exit(0) };
$SIG{ALRM} = sub { 
#    die "No packets received" if $n_packets < 1;
#    $uninterrupted=0;
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
135
    &display_stats if ! $endstream;
Olav Kvittem's avatar
Olav Kvittem committed
136
137
#	die "End after alarm\n"; 
#	return(0);
Olav Kvittem's avatar
Olav Kvittem committed
138
139
    $endstream=1;
    print "endstream=1" if $opt_debug;
Olav Kvittem's avatar
Olav Kvittem committed
140
};
Olav Kvittem's avatar
Olav Kvittem committed
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

if ($opt_dump){
    open DUMP, ">$opt_dump";
}

# $wanted_flow = $opt_flow_key;

if ($opt_pcap){ # listen in parallell
    alarm($opt_last) if $opt_last; 
    $uninterrupted=1;
    $endstream=0;
    eat_pcap_streams(@streams); 
    &display_stats();
} else { # listen serially
    foreach $id (@streams) {
	alarm($opt_last) if $opt_last; 
	$uninterrupted=1;
	$endstream=0;

	init_file($id);
	eat_stream($id);

	if (! ( $opt_list || $opt_sum)){
	    &display_stats() if !$endstream;
	}
	last if ! $uninterrupted;
    }
}
&list_flows if $opt_list;
&display_stats() if $opt_sum;
Olav Kvittem's avatar
Olav Kvittem committed
171
172
&display_bins if $opt_bins;

Olav Kvittem's avatar
Olav Kvittem committed
173
174
175
176
177
178
179
180
181
182
183
184
exit(0);


#------------------------------------------------------------------------------

# unpack uri's to ip-address

sub prepare_ip {
    my $uri=shift;
    $uri =~ s/^(udp|rtp)://;
    $uri =~ s#//##;
    die "Unsupported streaming $1" if $uri =~/^(\w:)/;
Olav Kvittem's avatar
Olav Kvittem committed
185
186
187
    if ($multicast = ($uri =~ /@/)){
	($source, $uri)=split(/@/, $uri);
    }
Olav Kvittem's avatar
Olav Kvittem committed
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

    my ($host, $port)=split(/[\/:]/, $uri);
    die $usage . "undefined address inn $host" unless (defined $host);
    $port = $DEFAULT_PORT unless (defined $port);
    my $address=$host;
    if ($host !~ /^\d+\.\d+\.\d+\.\d+$/){ # hostname
	my $padr=gethostbyname($host) || die "Gethostbyname - $host - $padr : $!";
	$address=Socket::inet_ntoa($padr);
    }   
    my @nib=split(/\./,$address);
    $multicast = $multicast || $nib[0] >= 224 && $nib[0] <= 240;

    return ($address, $port, $multicast);

}


sub eat_stream {
    my $id=shift;
    $tstart{$id}=[gettimeofday];

    if ($opt_net && $opt_rtp){
	# Create RTP socket
	my $elapsed=0;
	my $t0=0.0;
	$n_packets=0;
	my ($address, $port, $multicast) = prepare_ip($id);

	my $rtp = new Net::RTP( LocalPort=>$port,
				LocalAddr=>$address ) || die "Failed to create RTP socket: $!";
	my $select=IO::Select->new($rtp->fileno);

	my $tjoined=[gettimeofday];
	if ($opt_align){ # align to $opt_period
	}

	while ($uninterrupted && !($opt_packets && $n_packets > $opt_packets)) {

	    my $packet;
	    last if ! $uninterrupted || $endstream;
	    if ($select->can_read($timeout) && ($packet = $rtp->recv())){
		my $ssrc = $packet->ssrc();
		$cur_id=$packet->source_ip . ", $address:$port";

		if ( !$file{$cur_id}){
		    push(@myflows, $cur_id);
		    $file{$cur_id}=$id;
		}
		$n_packets++;
		next if $opt_src and $opt_src ne $cur_id;

		$tc=[gettimeofday]; # current flow time
		if( $t0){
		    $elapsed=tv_interval ( $t0, $tc);
		} else {
		    $t0 = $tc;
		    $elapsed=0.0;
		    &init_stats($cur_id);
		}
		$us=$elapsed*10**6;
		
		$tjoined{$cur_id} = $tjoined if !$tjoined{$cur_id};
		# No stats for that SSRC yet?
		&pkt_stats($cur_id, $packet->encode, $elapsed * 10**6, $packet->size());
		if ($opt_dump){
		    print DUMP $packet;
		}
	    } else { # anticipate interrupted by alarm	
#		warn "Failed to receive $n_packets packets from $address:$port : $!";
#		next; #### exit
	    }
	}
#	&display_stats();

#	$mc->shutdown; # gives error message


    } elsif ($opt_net) {			# udp stream

	# Create UDP socket
	my $elapsed=0;
	my $t0=0.0;
        $n_packets=0;
	my ($address, $port, $multicast) = prepare_ip($id);
	my $mc;

	if ( $multicast){
	    $mc = IO::Socket::Multicast->new(LocalPort=>$port, LocalAddr=>$address, ReuseAddr=>1) ||
		die "Could not connect to port $port : $!";
	    $mc->mcast_add($address) || die "could not join $address:$port : $!";
	} else { # unicast
	    $mc = IO::Socket::INET->new( LocalAddr=> $address, LocalPort => $port);
	}
	my $tjoined=[gettimeofday];

	my $select=IO::Select->new($mc->fileno);

	if ($opt_align){ # align to $opt_period
	}

	while ($uninterrupted && ! $endstream && !($opt_packets && $n_packets > $opt_packets)){
	    
	    if ($select->can_read($timeout) && $mc->recv($packet, 1560)) {
		last if ! $uninterrupted || $endstream;
		$n_packets++;
		my $ssrc = $mc->peerhost;
		my $cur_id = $mc->peerhost . ":" . $mc->peerport  . "->$address:$port";
		if ( !$file{$cur_id}){
		    push(@myflows, $cur_id);
		    $file{$cur_id}=$id;
		}
		
		next if $opt_src and $opt_src ne $cur_id;

		$tc=[gettimeofday]; # current flow time
		if( $t0){
		    $elapsed=tv_interval ( $t0, $tc);
		} else {
		    $t0 = $tc;
		    $elapsed=0.0;
		    &init_stats($cur_id);
		}
		$us=$elapsed*10**6;
		
		$tjoined{$cur_id} = $tjoined if !$tjoined{$cur_id};
		# No stats for that SSRC yet?
		&pkt_stats($cur_id, $packet, $elapsed * 10**6, length($packet));
		if ($opt_dump){
		    print DUMP $packet;
		}
Olav Kvittem's avatar
Olav Kvittem committed
318
		$endstream = tv_interval($t0, $tc) >= $opt_last if $opt_last;
Olav Kvittem's avatar
Olav Kvittem committed
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
	    } else { # assume that we got an interrupt
#		die "Failed to receive packet: $!"; 
	    }
	}
#	&display_stats();
#        $mc->mcast_drop($address);

    } else {			# files
	my $f=$id;
	my $pcap; 
	my $tmp_file;

	my $pcap_file=$f;
	if ($f =~ /\.gz$|\.Z/){ # gzipped ?
	    $tmp_file="/tmp/pcap$$";
	    $pcap_file=$tmp_file;
	    system( "/bin/zcat $f > $tmp_file") ; # rc code ? || die "Could not unpack $f to $tmp_file : $!";
	}
337
338
	if ($opt_crude){
	    my $flow_key;
Olav Kvittem's avatar
Olav Kvittem committed
339
	    open CRUDE, "<$pcap_file" || die "Could not open $f : $err";
340
	    while(<CRUDE>){  # crude.sourceforge.net
Olav Kvittem's avatar
Olav Kvittem committed
341
342
		my $tx0;
		
343
344
345
346
347
		if (($fid, $seq, $src, $dst, $tx, $rx, $size)=
		    /ID=(\d+)\s+SEQ=(\d+)\s+SRC=([\d.:]+)\s+DST=([\d.:]+)\s+Tx=([\d.,]+)\s+Rx=([\d.,]+)\s+SIZE=(\d+)/){

		    $flow_key="$src->$dst";
		    $flow_pkts{$flow_key}++;
Olav Kvittem's avatar
Olav Kvittem committed
348
		    $tc=[int($rx), ($tx-int($rx))*10^6] ; # tval
349
350
351
352
353
		    if ($flow_pkts{$flow_key} <= 1) { # new flow
			push(@flows, $flow_key);  # 
			$flow_no++; 
			$file{$flow_key}=$f;
			$source{$flow_key}=$src;
Olav Kvittem's avatar
Olav Kvittem committed
354
355
356
357
358
			$rx0{$flow_key}=$rx;
			$tx0{$flow_key}=$tx;
			$tjoined{$flow_key}=$tc;
		    } 
		    
359
360
361
362
363
364
365
366
367
		    next if $opt_list;  # just count packets per flow
		    next if $opt_flow_key && $flow_key !~ $wanted_flow;
		    next if $opt_flow_no && $opt_flow_no !~ /\b$flow_no\b/;
		    
		    if ($flow_pkts{$flow_key} <= 1) { #
			&init_stats($flow_key);
			push (@myflows, $flow_key);
		    }

Olav Kvittem's avatar
Olav Kvittem committed
368
369
370
371
372
373
374
		    $seq_num{$flow_key}=$seq;
		    $ptx{$flow_key}=$tx{$flow_key}; # previous
		    $tx{$flow_key}=$tx;
		    $rx{$flow_key}=$rx;
		    $mtime{$flow_key}=($tx-$tx0{$flow_key})*10**6;
		    $us=($rx-$rx0{$flow_key})*10**6; # us
		    &pkt_stats($flow_key, 0, $us, $size);
375
		}
Olav Kvittem's avatar
Olav Kvittem committed
376
	    }
377
378
379
380
381
382
383
384
385
386
	    
	} else {
	    if ($pcap=Net::Pcap::open_offline($pcap_file, \$err)){ 
		#	my $select=IO::Select->new(Net::Pcap::fileno($pcap));
		
		until ( ! $uninterrupted || $endstream || ($opt_packets && $n_packets > $opt_packets) 
			|| ! (my $pkt=Net::Pcap::next($pcap, \%hdr) ) ) {
		    eat_pcap($f, $pcap, $pkt);
		    $n_packets++;
		}
Olav Kvittem's avatar
Olav Kvittem committed
387
388
		printf "%s\n", $ttl_log if  $opt_ttl;

389
390
391
392
	    } else { # open failed 
		if ($format ne "full"){ # always put out data when format full
		    die "Could not open $f : $err";
		}
Olav Kvittem's avatar
Olav Kvittem committed
393
394
395
396
397
398
399
400
401
402
403
404
	    }
	}
	undef $t0;
	unlink $tmpfile if $tmp_file;
    } # of files
} # of eat_stream


sub eat_pcap_streams{ # open groups and listen on pcap
    my @streams=@_; 
    my $filter="( ";
    my $mc = IO::Socket::Multicast->new(LocalPort=>$DEFAULT_PORT, ReuseAddr=>1) ||
Olav Kvittem's avatar
Olav Kvittem committed
405
406
	die "Could not connect to port $port : $!";

Olav Kvittem's avatar
Olav Kvittem committed
407
    foreach $id (@streams){ # listen to all groups
Olav Kvittem's avatar
Olav Kvittem committed
408
409
410
411
412
413
414
415
	my ($address, $port, $multicast) = prepare_ip($id);
	$filter .= " or " if $filter =~ /\(\s+\(/;
	if ($multicast){
	    $mc->mcast_add($address) || die "could not join $address:$port : $!";
	    $filter .= "(dst $address and port $port)"; 	
	} else {
	    $filter .= "(src $address and port $port)"; 
	}	
Olav Kvittem's avatar
Olav Kvittem committed
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
    }
    $tjoined{$f}=[gettimeofday];
    $filter .= " )";
#    $filter .= " and ip multicast";
#    $filter ="ip";

    my ($net, $netmask, $filter_t, $err, $dev);
#    printf $filter;
    $dev = Net::Pcap::lookupdev(\$err) || die "Could not lookupdev $dev : $err : $!";
    my $r = Net::Pcap::lookupnet( $dev, \$net, \$netmask, \$err);
    die "Failed lookupnet for $dev : $r : $err : $!" if $r != 0;

    $pcap=Net::Pcap::open_live( $dev, 100, 1, 0,\$err) || die "Could not open $dev : $err";
    $r=Net::Pcap::compile($pcap, \$filter_t, $filter, 0, $netmask);
    die "Could not compile filter : $r : $filter : $!)" if $r != 0;
    $r=Net::Pcap::setfilter($pcap, $filter_t);
    die "Could not set pcap filter : $r : $filter : $! " if $r != 0 ;
    my $select=IO::Select->new( Net::Pcap::fileno($pcap));
Olav Kvittem's avatar
Olav Kvittem committed
434

Olav Kvittem's avatar
Olav Kvittem committed
435
436
437
438
439
440
    while ($select->can_read($timeout) && (my $pkt=Net::Pcap::next($pcap, \%hdr)) ) { # get all packets
	last if ! $uninterrupted || $endstream;
	eat_pcap("pcap", $pcap, $pkt);
	$n_packets++;
	last if  $opt_packets && $n_packets > $opt_packets;
    }
Olav Kvittem's avatar
Olav Kvittem committed
441
442
    printf "%s\n", $ttl_log if  $opt_ttl;

Olav Kvittem's avatar
Olav Kvittem committed
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

}


sub eat_pcap { # process pcap packets
    my ($f, $pcap, $pkt)=@_;
    my $ip=null;
    my $rtp = new Net::RTP::Packet(); # spare rtp obj
    if (Net::Pcap::datalink($pcap) == 1){ # ethernet
	$ip = NetPacket::IP->decode(eth_strip($pkt));
    } elsif (Net::Pcap::datalink($pcap) == 113) { # DLT_LINUX_SLL
	my ($head, $data)=unpack('a16a*', $pkt);  
	$ip = NetPacket::IP->decode($data);
    } else {
	die "Invalid link layer type : ".Net::Pcap::datalink($pcap);
    }
    next if $ip->{proto} != IP_PROTO_UDP;
    my $udp = NetPacket::UDP->decode($ip->{data});
    my $dlen = $ip->{len} - $ip->{hlen}*4;
    my $flow_key;

    if ($opt_sum){
	$flow_key=$opt_sum;
    } else {
	$flow_key=sprintf "%s:%d->%s:%d", 
        $ip->{src_ip}, $udp->{src_port}, $ip->{dest_ip}, $udp->{dest_port};
    }
    $flow_pkts{$flow_key}++;
    if ($flow_pkts{$flow_key} <= 1) { # new flow
	push(@flows, $flow_key);  # 
	$flow_no++; 
	$file{$flow_key}=$f;
	$source{$flow_key} =sprintf "%s:%d", $ip->{src_ip}, $udp->{src_port};
    }
Olav Kvittem's avatar
Olav Kvittem committed
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
    if ($opt_ttl){
	if ($pttl{$flow_key} && ($opt_log ||  ($pttl{$flow_key} !=  $ip->{ttl}))){ # change in ttl
	    printf "%s\n",  $ttl_log;
	    $nttl{$flow_key}=0;		
	}
	$pttl{$flow_key}= $ip->{ttl};
	$nttl{$flow_key}++;
	($sequence_number{$flow_key}, $tx_time_seconds{$flow_key}, $tx_time_useconds{$flow_key}, $flow_id{$flow_key})= unpack('NNNN', $udp->{data});
	$ttl_log=sprintf "ID=%u SEQ=%u SRC=%s DST=%s Tx=%u.%06u  Rx=%u.%06u TTL=%u",  
	$flow_id{$flow_key}, $sequence_number{$flow_key}, 
	$ip->{src_ip}, $ip->{dest_ip}, $tx_time_seconds{$flow_key}, 
	$tx_time_useconds{$flow_key}, $hdr{tv_sec}, $hdr{tv_usec}, $pttl{$flow_key};
	$ttl_log.= sprintf(" No=%08d\n",  $nttl{$flow_key},) if !$opt_log;

    }
Olav Kvittem's avatar
Olav Kvittem committed
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
    next if $opt_list;  # just count packets per flow
    next if $opt_flow_key && $flow_key !~ $wanted_flow;
    next if $opt_flow_no && $opt_flow_no !~ /\b$flow_no\b/;

    if ($flow_pkts{$flow_key} <= 1) { #
	&init_stats($flow_key);
	push (@myflows, $flow_key);
#    printf "$flow_key\n";
    }
    $tc= [$hdr{tv_sec}, $hdr{tv_usec}];
    if (! defined($t0)) {
	$t0=$tc;
    }
    $tjoined{$f}=$tc if !$tjoined{$f};
    $tjoined{$flow_key} = $tjoined{$f} if !exists($tjoined{$flow_key});

    $us = tv_interval ( $t0, $tc) * 10**6 ; # us relative packet time 	  

# fixate on first flow to appear
#    if ( $first_port) {
#	next if $udp->{dest_port} != $first_port;
#    } else {
#	$first_port =  $udp->{dest_port};
#    }

Olav Kvittem's avatar
Olav Kvittem committed
517
    &pkt_stats($flow_key, $udp->{data}, $us, $dlen);
Olav Kvittem's avatar
Olav Kvittem committed
518
519
520
521
    
}

sub init_stats {
Olav Kvittem's avatar
Olav Kvittem committed
522
    my $f=shift;
Olav Kvittem's avatar
Olav Kvittem committed
523

Olav Kvittem's avatar
Olav Kvittem committed
524
525
    $pinterval=0;
    $npkt{$f}=$sumbyte{$f}=$ssbyte{$f}=0;
Olav Kvittem's avatar
Olav Kvittem committed
526
    $first_sec=0;
Olav Kvittem's avatar
Olav Kvittem committed
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
    delete $pmtime{$f}; delete $pus{$f} ; delete $first_us{$f};  delete $last_us{$f}; 
    delete $prev_1s{$f}; delete $prev_100ms{$f};
    delete $per1s{$f}; delete $per100ms{$f};
    delete $sum1s{$f}; delete $sum100ms{$f};
    $n100ms{$f}=0; $sum100ms{$f}=0; $ss100bps{$f}; $akk100ms{$f}=0;
    $sumbyte{$f}=$sumps{$f}=0;			# sum byte per second
    $maxbps{$f}=0; $max100ms{$f}=0;
    $dup{$f}=$lost{$f}=$late{$f}=0;
    $maxbyte{$f}=0; $minbyte{$f}=2**31;
    $sumgap{$f}=$ssgap{$f}=0;
    $ngap{$f}=0; $maxgap{$f}=0, $mingap{$f}=2**63-5;
    $njitter{$f}=$sumjitter{$f}=$ssjitter{$f}=0;
    $maxjitter{$f}=-2**63-5; $minjitter{$f}=2**63-5; delete $est_jitter{$f}; delete $pest_jitter{$f}; 
    $first_port = 0;  $n_seq=-1;
    delete $tstart{$f}; delete $tend{$f}; 

#MPEG-TS initalizing and resetting (new period!)
    $discontinuities = 0;
    %last_ccs = ();
    @cc = ();
# r_stats {filename/handle}
    @pcr_stats{$f} = ();
#P-stats {filename/handle}
    @pts_stats{$f} = ();
    @mpeg_stats{$f} = ();
#P stuff
    $late_video_packets = 0;
#MPEG-TS END
    %dist1 = ();
    %dist2 = ();
    $num_cc = 0;

Olav Kvittem's avatar
Olav Kvittem committed
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
}

sub init_file {
    undef $t0;
    my $f=shift;
    undef $tjoined; delete $tjoined{$f}; delete $setuptime{$f}; delete($joined{$file{$f}});
    delete $file{$f};
    @myflows=() if !$opt_sum;
    $flow_pkts{$f}=0;  # new flow on new file

    undef $pus;
    undef $psec;
    delete($pmtime{$f});
    delete($pseq_num{$f});
    delete($pus{$f});
}

Olav Kvittem's avatar
Olav Kvittem committed
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
sub seq_stat {
    my ($f, $seq_num, $mtime)=@_;

    my $seq_diff= $seq_num - $pseq_num{$f};
    unless ($opt_crude && $seq_diff == 1){ #
	$gap = $us - $pus{$f};		# packet time gap
	$ngap{$f}++;
	$sumgap{$f} +=  $gap;
	$ssgap{$f} += $gap**2;
	$maxgap{$f}=  $gap if $gap > $maxgap{$f};
	$mingap{$f}=  $gap if $gap < $mingap{$f};

	foreach $i (0 .. $#bins){
	    if( $gap < ($bins[$i]*1000)){
		$nbin[$i]++;
		last;
	    }
	}
	printf "Tx=%.6f gap=%d gap=%.1fms\n", $ptx{$f}, $seq_diff-1, $gap/1000, if $opt_log;
    }
Olav Kvittem's avatar
Olav Kvittem committed
596

Olav Kvittem's avatar
Olav Kvittem committed
597
    if ($seq_diff != 1) {
Olav Kvittem's avatar
Olav Kvittem committed
598
599
#	printf "seq %d,", $rtp->seq_num;

Olav Kvittem's avatar
Olav Kvittem committed
600
601
602
603
	if ($seq_diff == 0) { # Duplicated
	    $dup{$f} ++;
	} elsif ($seq_diff < 0) { # Out Of Order
	    $late{$f}++;
Olav Kvittem's avatar
Olav Kvittem committed
604
#		$lost{$f}--;
Olav Kvittem's avatar
Olav Kvittem committed
605
606
607
608
609
610
611
612
613
614
	} else {			# Lost                   
	    $lost{$f}+= $seq_diff - 1;
	    $nloss{$f}++;
	    $sumloss{$f} += $seq_diff;
	    $ssumloss{$f} += $seq_diff**2;
	    $maxloss{$f} = $seq_diff if  $seq_diff >  $maxloss{$f};
	}
    } elsif ( $mtime <= $pmtime{$f}){
	$ntimeerr{$f}++;
    } else { # the jitter can be measured
Olav Kvittem's avatar
Olav Kvittem committed
615
#  compute jitter relative to previous packet
Olav Kvittem's avatar
Olav Kvittem committed
616
617
	$mgap= ($mtime - $pmtime{$f} ); # media time gap in samples 8khz=us
	$jitter=abs($gap - $mgap);
Olav Kvittem's avatar
Olav Kvittem committed
618
619
620
#ok compute jitter relative to start
#ok	    $mgap= ($mtime - $first_mtime); # media time gap in us
#ok	    $jitter=abs($us - $mtime - $first_jitter);
Olav Kvittem's avatar
Olav Kvittem committed
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
	$njitter{$f}++;
	$sumjitter{$f} +=  $jitter;
	$ssjitter{$f} += $jitter**2;
	$maxjitter{$f}=  $jitter if $jitter > $maxjitter{$f};
	$minjitter{$f}=  $jitter if $jitter < $minjitter{$f};

	# rfc 3550 
	if (defined($est_jitter{$f})){
	    $est_jitter{$f} = $est_jitter{$f} + ( $jitter - $est_jitter{$f} )/16;
	} else { # inital value
	    $est_jitter{$f} = $jitter;
	}
    }

}


sub pkt_stats {
    my $f = shift; # file or stream name
    my $packet = shift;
    my $us = shift;
    my $dlen = shift;
    my $rtp = new Net::RTP::Packet();

    if (! exists($tstart{$f})){
	$tstart{$f} = $tc;
	$first_us{$f}=$prev1s_us{$f}=$prevt100ms_us{$f}=$us;
	if (! exists($setuptime{$f}) ){
	    if ( $pinterval){
		$setuptime{$f}=0;
	    } else {
		$setuptime{$f}=tv_interval ( $tjoined{$f}, $tstart{$f}) * 10**3;
Olav Kvittem's avatar
Olav Kvittem committed
653
	    }
Olav Kvittem's avatar
Olav Kvittem committed
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
	    printf "setup $f : %.3f\n",  $setuptime{$f} if $opt_debug;
	}
    }
    $tend{$f} = $tc;
    $last_us{$f}=$us;
    
    #	next if $dlen < 20;  # typically small background noice packets added

    $npkt{$f}++;
    $sumbyte{$f}+=$dlen; $sum1s{$f}+=$dlen; $sum100ms{$f}+=$dlen;
    $ssbyte{$f}+=$dlen**2;
    $maxbyte{$f}=  $dlen if $dlen > $maxbyte{$f};
    $minbyte{$f}=  $dlen if $dlen < $minbyte{$f};

    $sumps{$f}+=$dlen;		# sum per second

    if ($opt_dump){
	print DUMP $packet;
    }

    if ($opt_mpeg){ 
	mpeg_stats($f, $packet, $us);
    }

    if ($opt_rtp){
	if ( $rtp->decode($packet) ) { #assume RTP
#	    printf "RTP: %10s %5d %5d\n", $rtp->ssrc(), $rtp->timestamp(), $rtp->size();
#	    $dlen = $rtp->size();
	} else {
	    print "??? $f # $npkt{$f} $dlen B\n";
		if ($opt_debug){
		    my $n=0;
		    foreach $w( unpack("C*", $packet)) {
			printf "%0X",$w;
			if ($n > 0){
			    print " " if $n % 4 == 0;
			    print "\n" if $n % 32 == 0;
			}
			$n++;
		    }
		    printf "\n";
		}
	    next;
	}
	# Calculate next number in sequence
	$n_seq = $rtp->seq_num()+1;
	if ($n_seq > 65535) {
	    $n_seq=0;
	}
	$mtime{$f}=$rtp->timestamp() * &time_unit($rtp->payload_type);  # mediatime in us
	$seq_num{$f}=$rtp->seq_num;
    }

    if (defined($pus{$f})) {
	$gap = $us - $pus{$f};		# packet time gap
	$ngap{$f}++;
	$sumgap{$f} +=  $gap;
	$ssgap{$f} += $gap**2;
	$maxgap{$f}=  $gap if $gap > $maxgap{$f};
	$mingap{$f}=  $gap if $gap < $mingap{$f};

	if ($opt_rtp){

	    &seq_stat($f, $seq_num{$f}, $mtime{$f});

Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
719
720
721
722
723
724
	}
	if ($adapt == 1 ) { # adaption field coming
	    my ($length, $aflags, $rest2)=unpack "C1C1C*", $rest;
	    my ($dif, $raif, $espif, $pcrf, $opcrf, $splicef, $tpdf, $afextf)=split(//, $aflags); 
	    if ($pcrf == 1){
		;
Olav Kvittem's avatar
Olav Kvittem committed
725
	    }
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
726
	    printf "%5d %6d %5d %5d %5d %5d %5d\n",$rtp->seq_num,$us,$rtp->timestamp(), $gap,  $mgap, $jitter, $first_jitter if $opt_debug;
Olav Kvittem's avatar
Olav Kvittem committed
727
728
729
730
731
732
733
	    
	} elsif ($opt_crude){
	    &seq_stat($f, $seq_num{$f}, $mtime{$f});

	} elsif ($opt_mpeg){ # incomplete code under exploration
	    # meg transport stream layout http://en.wikipedia.org/wiki/Transport_stream
	    my ($flag, $b2, $b3, $rest)= unpack "H2n1C1C*", $packet;
Olav Kvittem's avatar
Olav Kvittem committed
734
#	my ($ts_err, $payload, $ts_pri)=split( //, unpack "B3", $b2); # does not work
Olav Kvittem's avatar
Olav Kvittem committed
735
736
	    my ($ts_err, $payload, $ts_pri) = ( $b2 & 0x8000 , $b2 & 0x4000,  $b2 & 0x2000);
	    my $pid= $b2 & 0x1F00; 
Olav Kvittem's avatar
Olav Kvittem committed
737
#	my ($scramble1, $scramble2, $adapt, $data) = split( //, unpack "B4", $b3); # not working
Olav Kvittem's avatar
Olav Kvittem committed
738
739
	    my ($scramble1, $scramble2, $adapt, $data) = ( $b3 & 0x80,  $b3 & 0x40, $b3 & 0x20, $b3 & 0x10);
	    my $contin= $b3 & 0x0F;
Olav Kvittem's avatar
Olav Kvittem committed
740
741
742
#	printf "%5d %5s %5d %5X %5d %5d %s\n", $npkt{$f}, $flag, $pid, $b2, $data, $contin, unpack("H*",$packet)
#	     if $payload > 0 ; # $contin == 13;  #$ts_pri > 0 ;  # $b2 > 256;

Olav Kvittem's avatar
Olav Kvittem committed
743
744
	    if ($payload && $pid > 0){  # PES follows http://en.wikipedia.org/wiki/Packetized_Elementary_Stream
		my ($ts_prefix, $code, $id, $pes_lth, $pes_rest )= unpack("H8H6C1C2C*", $packet);
Olav Kvittem's avatar
Olav Kvittem committed
745
746
#	    printf "%5d %5s %5d %5X %5d %5d %s\n", $npkt{$f}, $flag, $pid, $code, $data, $id, unpack("H*",$packet);

Olav Kvittem's avatar
Olav Kvittem committed
747
748
749
750
751
752
		if ($code == 0x000001){
		    if ( $id >= 0xE0 ){ # video PES-header
			my ($ts_prefix, $pes_head, $pes_opt, $head_lth)=unpack("H8H6C2C1", $packet);
			if ($pes_opt & 0x0080){ # PTS ind
			    printf "%5d %5s %5d %5X %5d %5d %s\n", $npkt{$f}, $flag, $pid, $id, $pes_lth, $head_lth, unpack("H*",$packet) if $opt_debug;
			}
Olav Kvittem's avatar
Olav Kvittem committed
753
		    }
Olav Kvittem's avatar
Olav Kvittem committed
754
		    
Olav Kvittem's avatar
Olav Kvittem committed
755
756
		}
	    }
Olav Kvittem's avatar
Olav Kvittem committed
757
758
759
760
761
762
	    if ($adapt == 1 ) { # adaption field coming
		my ($length, $aflags, $rest2)=unpack "C1C1C*", $rest;
		my ($dif, $raif, $espif, $pcrf, $opcrf, $splicef, $tpdf, $afextf)=split(//, $aflags); 
		if ($pcrf == 1){
		    ;
		}
Olav Kvittem's avatar
Olav Kvittem committed
763
764
765
	    }
	}

Olav Kvittem's avatar
Olav Kvittem committed
766
	&burst($f);
Olav Kvittem's avatar
Olav Kvittem committed
767
768

    }
Olav Kvittem's avatar
Olav Kvittem committed
769
770
771
772
773
774
775
776
777
778
    if ($opt_period){
	$interval=int($us/10**6 / $opt_period);
	if ($interval > $pinterval){
	    &mpeg_debug() if $opt_debug;
	    &display_stats() ;
	    $pinterval=$interval;
	    $pinterval{$f}=$interval;
	    $endstream = $opt_nperiod && $interval >= $opt_nperiod;
	}
    }
Olav Kvittem's avatar
Olav Kvittem committed
779

Olav Kvittem's avatar
Olav Kvittem committed
780
781
782
783
784
785
    $pus=$us;
    $psec=$sec;
    $pmtime{$f}=$mtime{$f} if $opt_rtp || $opt_crude;
    $pseq_num{$f}= $seq_num{$f} if $opt_rtp ||  $opt_crude;
    $pus{$f}=$us;
} # of pkt_stats
Olav Kvittem's avatar
Olav Kvittem committed
786
787
788
789
790
791


sub burst {
    my $f=shift;
    my $span=$last_us{$f}-$first_us{$f};
    my $per1s=int($span/10**6);
Olav Kvittem's avatar
Olav Kvittem committed
792
    #printf "per1s: %f\n", $per1s;
Olav Kvittem's avatar
Olav Kvittem committed
793
    my $per100ms=int($span/10**5);
Olav Kvittem's avatar
Olav Kvittem committed
794
795
    #printf "per1s_f%f\n", $per1s{$f};
    
Olav Kvittem's avatar
Olav Kvittem committed
796
797
    if ( $per1s > $per1s{$f} ){ # period expired
	my $per=($last_us{$f}-$prev_1s{$f})/10**6;
Olav Kvittem's avatar
Olav Kvittem committed
798
	#		printf "per: %f\n", $per;
Olav Kvittem's avatar
Olav Kvittem committed
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
	if ($per>0){
	    my $bps = $sum1s{$f} * 8 / $per;
	    $maxbps{$f} =  $bps if $bps > $maxbps{$f};
	    $per1s{$f} =  $per1s;
	    $prev_1s{$f} = $last_us{$f};
	    $sum1s{$f}=0;
	}
    }
    if ( $per100ms > $per100ms{$f} ){ # period expired
	my $per=($last_us{$f}-$prev_100ms{$f})/10**6;
	if ($per>0){
	    my $bps = $sum100ms{$f} * 8 / $per;
	    $max100ms{$f} =  $bps if $bps > $max100ms{$f};
	    $n100ms{$f}++;
	    $ss100bps{$f}+= $bps**2;
	    $akk100ms{$f}+=$bps;
	    $per100ms{$f} =  $per100ms;
	    $prev_100ms{$f} = $last_us{$f};
	    $sum100ms{$f}=0;
#	print "$bps ";
	}
    }

}

sub display_stats{

#    my $f = shift;

    my $media="file";
#    $media = "host, group" if $opt_net;
    $media = "host:port" if $opt_net;

    @myflows=@streams if ($#myflows < 0); # no response

Olav Kvittem's avatar
Olav Kvittem committed
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
    foreach $f (sort @myflows) { 
	my $id=$f;
	next if $npkt{$f} <= $opt_flow_min;
	my $source=$f; 
	$source=$source{$f} if  ! $opt_v && $source{$f} ne "";
	$source=$opt_id if $opt_id;
	my $jitter_stat= $opt_rtp || $opt_crude;

	my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = localtime($tstart{$f}->[0]);
	my $time=sprintf "%02d:%02d:%02d", $hour, $min, $sec;
	if ($format eq "full"){
	    $time.=sprintf ".%06d", $tstart{$f}->[1];
	} else {
	    my $time=sprintf "%02d:%02d:%02d", $hour, $min, $sec;
	}
	my $date=sprintf "%4d-%02d-%02d", $year+1900, $mon+1, $mday;
	my $span=&tv_interval($tstart{$f}, $tend{$f}); # second

	&burst($f); # in case a second is interrupted
Olav Kvittem's avatar
Olav Kvittem committed
853
854
855
856
#	printf "dus %d min %.2f\n", $us-$pus, $max100ms{$f};
#	$max100ms{$f}=-1  if  $max100ms{$f} > 2**61;
#	$maxbps{$f}=-1  if ! $maxbps{$f} > 0;
	
Olav Kvittem's avatar
Olav Kvittem committed
857
858
859
860
861
862
863
864
865
	if ($opt_v) {

	    if ($date ne $pdate) {
		if (! $opt_nohead){
		    print "\nDate $date            packet  size(byte)           packet distance(ms) ";
		    print "       time    sequence         loss               packet jitter(ms)        " if $jitter_stat;

		    print  "      flu-    pcr_jitter(ms)             dwell_time(ms)   " if $opt_mpeg;

Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
866
		    print "             load(bps)            source\n";                      
Olav Kvittem's avatar
Olav Kvittem committed
867
868
869
870
871
872
		    printf "%-8s %6s %6s     %4s%4s %4s %4s %4s   %6s %4s %4s %4s %4s",
		    "time","span", "setup",
		    "numb ", "avg", "sdv", "min", "max",
		    "numb", "avg", "sdv", "min", "max";
		    printf "  %5s %5s %5s %5s %5s %5s %5s",
		    "stamp", "dup", "late", "lost", "gaps", "avg", "sdv", if $jitter_stat;
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
873
		    printf " %6s %4s %4s %4s %4s %4s %5s ", "numb", "avg", "sdv", "min", "max", "rfc", "MOS" if $jitter_stat;
Olav Kvittem's avatar
Olav Kvittem committed
874
875
876
877
878
879


		    printf " %5s ", "ency", "" if $opt_mpeg;
		    printf " %4s %5s %5s %5s ", "avg", "sdv", "min", "max" if $opt_mpeg;
		    printf " %4s %5s %5s %5s ", "avg", "sdv", "min", "max" if $opt_mpeg;

Olav Kvittem's avatar
Olav Kvittem committed
880
881
882
883
884
885
886
		    printf "  %5s %5s %5s %5s  %-15s\n", 
		    "avg",  "1s", "100ms", "sdv", $media;
		}

	    }

	    if ( $npkt{$f} >= 0 && $ngap{$f}>= 0) {
Olav Kvittem's avatar
Olav Kvittem committed
887
		if (! $jitter_stat) { $minjitter{$f}=0; $maxjitter{$f}=0;}
Olav Kvittem's avatar
Olav Kvittem committed
888
889
		if ($ngap{$f} < 1 ){
		    $mingap{$f}=0; $maxgap{$f}=0;
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
890
		    printf "Resetting maxbps\n" if $opt_debug;
Olav Kvittem's avatar
Olav Kvittem committed
891
892
		    $max100ms{$f}=0; $maxbps{$f}=0;
		}
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
893
894
895
896
897
898
		my $mos;
		if ($jitter_stat){
		    $mos=&mos_r($codec, $rtt,  avg( $sumgap{$f}, $ngap{$f}) / 1000,
					avg($sumjitter{$f}, $njitter{$f})/1000, 
					100*$nloss{$f}/$npkt{$f} );
		}
Olav Kvittem's avatar
Olav Kvittem committed
899
900

		printf "%8s %6s %6s %8s", 
Olav Kvittem's avatar
Olav Kvittem committed
901
		$time, &lesbars($span,3), &lesbars($setuptime{$f},3), &lesbar($npkt{$f},8);
Olav Kvittem's avatar
Olav Kvittem committed
902
903
		my $n=$npkt{$f}; $n=1 if $npkt{$f} <1; # divide by zero protection
		printf " %4s %4s %4d %4d  ", &lesbar($sumbyte{$f}/$n,4), 
Olav Kvittem's avatar
Olav Kvittem committed
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
		&lesbar(sdv($npkt{$f}, $sumbyte{$f}, $ssbyte{$f})),	
		$minbyte{$f}, $maxbyte{$f};

		printf " %6s %4s %4s %4s %4s ", 
		&lesbar($ngap{$f},6), &lesbars( avg( $sumgap{$f}, $ngap{$f}) / 1000 ),
		&lesbars(sdv($ngap{$f}, $sumgap{$f},$ssgap{$f})/1000),
		&lesbars($mingap{$f}/1000),  &lesbars($maxgap{$f}/1000);

#				printf (" %5s %.1e",
#					&lesbar($mpeg_stats{$f}{'num'},3),
#					(&largest_deviation(1/16, $mpeg_stats{$f}{'num'}, \@cc),6)) if $opt_mpeg;
		printf (" %4s",
			&lesbar(compare_cc_dists(\%dist1,\%dist2)),
			"") if $opt_mpeg;


		printf " %5s %5s %5s %5s", 
		&lesbar( (10**3) * avg($pcr_stats{$f}{'pcr_jitter_sum'}, $pcr_stats{$f}{'num'})),
		&lesbar( (10**3) * sdv($pcr_stats{$f}{'num'}, 
				       $pcr_stats{$f}{'pcr_jitter_sum'}, 
				       $pcr_stats{$f}{'pcr_jitter_square'})),
		&lesbar( (10**3) * $pcr_stats{$f}{'min_jit'}),
		&lesbar( (10**3) * $pcr_stats{$f}{'max_jit'})
		    if $opt_mpeg;

		printf " %5s %5s %5s %5s ", 
		lesbar( (10**3) * avg($pts_stats{$f}{'dwell_sum'}, $pts_stats{$f}{'num'})),
		lesbar( (10**3) * sdv($pts_stats{$f}{'num'}, 
				      $pts_stats{$f}{'dwell_sum'}, 
				      $pts_stats{$f}{'dwell_squared'})),
		lesbar( (10**3) * $pts_stats{$f}{'min_dwell'}),
		lesbar( (10**3) * $pts_stats{$f}{'max_dwell'}),
		if $opt_mpeg;
Olav Kvittem's avatar
Olav Kvittem committed
937

Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
938
		printf " %5s %5s %5s %5s %5s %5s %5s ",
Olav Kvittem's avatar
Olav Kvittem committed
939
940
		&lesbar($ntimeerr{$f}), &lesbar($dup{$f}),  &lesbar($late{$f}),  &lesbar($lost{$f}), 
		&lesbar($nloss{$f}),  &lesbar( avg( $sumloss{$f}, $nloss{$f}) ),  
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
941
		&lesbar( sdv($lost{$f}, $sumloss{$f},  $ssumloss{$f}))
Olav Kvittem's avatar
Olav Kvittem committed
942
		    if $jitter_stat;
Olav Kvittem's avatar
Olav Kvittem committed
943

Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
944
		printf " %6s %4.1f %4.1f %4.1f %4.1f %4.1f %4.1f ",
Olav Kvittem's avatar
Olav Kvittem committed
945
946
947
948
		&lesbar($njitter{$f}),
		avg($sumjitter{$f}, $njitter{$f})/1000,
		sdv($njitter{$f}, $sumjitter{$f}, $ssjitter{$f})/1000,
		$minjitter{$f}/1000, $maxjitter{$f}/1000,
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
949
			 $est_jitter{$f}/1000, $mos
Olav Kvittem's avatar
Olav Kvittem committed
950
		    if $jitter_stat;
Olav Kvittem's avatar
Olav Kvittem committed
951

Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
952
		printf " %5s %5s %5s %5s  %s\n",
Olav Kvittem's avatar
Olav Kvittem committed
953
		&lesbar( avg( $sumbyte{$f}*8, $span ) ), 
Olav Kvittem's avatar
Olav Kvittem committed
954
955
956
957
958
		&lesbar($maxbps{$f}), 
		&lesbar($max100ms{$f}), 
		&lesbar(sdv($n100ms{$f},
			    $akk100ms{$f}, 
			    $ss100bps{$f})), 
Olav Kvittem's avatar
Olav Kvittem committed
959
960
		$source;

Olav Kvittem's avatar
Olav Kvittem committed
961

Olav Kvittem's avatar
Olav Kvittem committed
962
963
964
965
	    } else { # not reached
		printf "%-8s %6s %6s %8s %4s %4d %4d %4d %6d %4s %4s %4s %4s %5d %5d %5d %5d %s\n", $time, 0, 0, &lesbar($npkt{$f},4), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, $source if $f ne "" && $npkt{$f}>=0;
	    }

Olav Kvittem's avatar
Olav Kvittem committed
966
	} else {  #not -v
Olav Kvittem's avatar
Olav Kvittem committed
967
968
	    if ($date ne $pdate) {
		if (! $opt_nohead){
Olav Kvittem's avatar
Olav Kvittem committed
969
970
		    if($opt_mpeg){
			print "\nDate $date       packet      flu-    ";
Olav Kvittem's avatar
Olav Kvittem committed
971
		    } else {
Olav Kvittem's avatar
Olav Kvittem committed
972
973
974
975
976
977
978
			print "\nDate $date       packet      size(byte)   ";
		    }
		    if ($jitter_stat){
			print "jitter(ms)                " ;
		    } elsif ($opt_mpeg) {
			print "pcrjit(ms)  dwell (ms)    " ;
		    } else  {
Olav Kvittem's avatar
Olav Kvittem committed
979
980
981
			print "gap(ms)                   " ;
		    }
		    print "thrust(bps)       source\n";                      
Olav Kvittem's avatar
Olav Kvittem committed
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003

		    if($opt_mpeg) {
			printf "%-8s %8s %4s %4s %4s %4s ", 
                        #"time","numb", "dup", "late", "lost", "numb", "dscnt";
			"time","numb", "dup", "late", "lost", "ency";
		    } else {
			printf "%-8s %8s %4s %4s %4s %4s %4s", 
			"time","numb", "dup", "late", "lost", "avg", "sdv";
		    }	


		    if($opt_mpeg) {
			printf "   %5s %5s %5s %5s",
			"avg", "sdv", "avg", "sdv";

		    } else {
			printf "  %5s %5s %5s %5s",
			"avg", "sdv", "min", "max" ; # if $jitter_stat;
		    }	

		    printf "    %4s %5s %5s   %s\n",
		    "avg", "1s", "100ms", $media;
Olav Kvittem's avatar
Olav Kvittem committed
1004
1005
1006
1007
1008
1009
1010
1011
1012
		}

	    }


	    if ( $npkt{$f}>= 0 && $ngap{$f}>= 0) { 
		my @jitterstat=(0,0,0,0);
		my $n=$npkt{$f}; $n=1 if $npkt{$f} <1; # divide by zero protection

Olav Kvittem's avatar
Olav Kvittem committed
1013
		if ($jitter_stat){
Olav Kvittem's avatar
Olav Kvittem committed
1014
		    @jitterstat= (&lesbars($sumjitter{$f}/$njitter{$f}/1000),
Olav Kvittem's avatar
Olav Kvittem committed
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
				  &lesbars(sdv($njitter{$f}, $sumjitter{$f}, $ssjitter{$f})/1000),
				  &lesbars($minjitter{$f}/1000), 
				  &lesbars($maxjitter{$f}/1000));
		} elsif ($opt_mpeg) {


		    @jitterstat = (

				   &lesbar( (10**3) * avg($pcr_stats{$f}{'pcr_jitter_sum'}, $pcr_stats{$f}{'num'})),
				   &lesbar( (10**3) * sdv($pcr_stats{$f}{'num'}, 
							  $pcr_stats{$f}{'pcr_jitter_sum'}, 
							  $pcr_stats{$f}{'pcr_jitter_square'})),
				   &lesbar( (10**3) * avg($pts_stats{$f}{'dwell_sum'}, $pts_stats{$f}{'num'})),
				   &lesbar( (10**3) * sdv($pts_stats{$f}{'num'}, 
							  $pts_stats{$f}{'dwell_sum'}, 
							  $pts_stats{$f}{'dwell_squared'})),
				   );	

Olav Kvittem's avatar
Olav Kvittem committed
1033
1034
1035
1036
1037
		} else {
		    @jitterstat=( &lesbars( avg($sumgap{$f}, $ngap{$f}) / 1000),
				  &lesbars(sdv($ngap{$f}, $sumgap{$f},$ssgap{$f})/1000),
				  &lesbars($mingap{$f}/1000),  &lesbars($maxgap{$f}/1000) );
		}
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1038
1039
		printf "%8s %8d %4d %4d %4s",
		$time, $npkt{$f}, $dup{$f}+$ntimeerr{$f}, $late{$f}, &lesbar($lost{$f},4);
Olav Kvittem's avatar
Olav Kvittem committed
1040

Olav Kvittem's avatar
Olav Kvittem committed
1041
		if($opt_mpeg){
Olav Kvittem's avatar
Olav Kvittem committed
1042

Olav Kvittem's avatar
Olav Kvittem committed
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
		    printf (" %4s  ",  
			    &lesbar(compare_cc_dists(\%dist1, \%dist2))) if $opt_mpeg;

		} else {
		    printf "%4d %4.1f", $sumbyte{$f}/$n, sdv($n, $sumbyte{$f}, $ssbyte{$f});
		}

		printf   "  %5s %5s %5s %5s",@jitterstat;
		printf "   %5s %5s %5s  %s\n", 
		&lesbar( avg($sumbyte{$f}*8, $span)), 
		&lesbar($maxbps{$f}), 
		&lesbar($max100ms{$f}),
Olav Kvittem's avatar
Olav Kvittem committed
1055
1056
		$source;

Olav Kvittem's avatar
Olav Kvittem committed
1057
		#printf "in-print: \n\n%f\n\n", $maxbps{$f};
Olav Kvittem's avatar
Olav Kvittem committed
1058
1059
1060
	    } else {
		printf "%-8s %8s %68s     %s\n",$time, lesbar($npkt{$f},4),"", $source if $f ne "" && $npkt{$f}>0;
	    }
Olav Kvittem's avatar
Olav Kvittem committed
1061

Olav Kvittem's avatar
Olav Kvittem committed
1062
1063
1064
	}
	$opt_nohead=1;
	$pdate=$date;
Olav Kvittem's avatar
Olav Kvittem committed
1065
1066
	$flow_pkts{$f}=0;
	&init_stats($f);
Olav Kvittem's avatar
Olav Kvittem committed
1067
1068
1069
1070

    }
}

Olav Kvittem's avatar
Olav Kvittem committed
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
sub display_bins{
    print "\n\nBins    ";
    foreach $bin (@bins){
	printf "%5d ", $bin;
    }
    print "\nGaps    ";
    foreach $i (0 .. $#bins){
	printf "%5d ", $nbin[$i];
    }
    print "\n";
}

Olav Kvittem's avatar
Olav Kvittem committed
1083
1084
1085
1086
1087
1088
sub avg {  
    my ($sum, $n)=@_;
    return 0 if $n <= 0;
    return $sum/$n;
}
sub sdv {
Olav Kvittem's avatar
Olav Kvittem committed
1089
1090
1091
1092
1093
1094
    my ($n, $sum, $sumsq)=@_;
    if ($n > 1) {
	return sqrt( abs($sumsq/$n -  ($sum/$n)**2));
    } else {
	return  0;
    }
Olav Kvittem's avatar
Olav Kvittem committed
1095
1096
1097
1098
}


sub lesbar{
Olav Kvittem's avatar
Olav Kvittem committed
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
    my ($n, $figs)=@_;
    $figs = 3 if ! $figs;
    return sprintf ("%.1f", $n) if $format ne "pretty";

    @dekade=("", "K", "M", "G", "T", "P");
    for ($d=0; $d<=$#dekade; $d++){
	$dekade=10**(3*$d);
	my $nd=$n / $dekade;

	if ( $nd < 10**$figs){ # 3 siffer OK
	    if ( $nd > 100 || ($n < 10000 && $n == int($n))){
		return (sprintf "%d", $nd) . $dekade[$d];
	    } else { 
		return sprintf "%.1f%s", $nd, $dekade[$d];
	    }
Olav Kvittem's avatar
Olav Kvittem committed
1114
1115
1116

	}
    }
Olav Kvittem's avatar
Olav Kvittem committed
1117
1118
    return sprintf "%E", $n;

Olav Kvittem's avatar
Olav Kvittem committed
1119
1120
1121
}

sub lesbars {
Olav Kvittem's avatar
Olav Kvittem committed
1122
1123
1124
1125
1126
1127
1128
1129
1130
    my ($n, $figs)=@_;
    return &lesbar($n, $figs) if $format ne "pretty";
    if ($n > 1000){
	my $num = &lesbar($n /1000, $figs) . "s";
	$num=~s/ //; 
	return $num;
    } else {
	return  &lesbar($n, $figs);
    }
Olav Kvittem's avatar
Olav Kvittem committed
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179

}

# compute timeunits in mediatime from rfc 3551
# limited to static payload-types
sub time_unit{
    my $payload_type=shift;
    $sample_freq{0}=8000;
    $sample_freq{3}=8000;
    $sample_freq{4}=8000;
    $sample_freq{5}=8000;
    $sample_freq{6}=16000;
    $sample_freq{7}=8000;
    $sample_freq{8}=8000;
    $sample_freq{9}=8000;
    $sample_freq{10}=44100;
    $sample_freq{11}=44100;
    $sample_freq{12}=8000;
    $sample_freq{13}=8000;
    $sample_freq{14}=90000;
    $sample_freq{15}=8000;
    $sample_freq{16}=11025;
    $sample_freq{17}=22050;
    $sample_freq{18}=8000;
    $sample_freq{726}=8000;
    $sample_freq{726}=8000;
    $sample_freq{726}=8000;
    $sample_freq{726}=8000;
    $sample_freq{729}=8000;
    $sample_freq{729}=8000;
    $sample_freq{25}=90000;
    $sample_freq{26}=90000;
    $sample_freq{28}=90000;
    $sample_freq{31}=90000;
    $sample_freq{32}=90000;
    $sample_freq{33}=90000;
    $sample_freq{34}=90000;

    return 10**6/($sample_freq{$payload_type}||8000);
}

sub list_flows {
    my $n=0;
    printf "\n\n%4s   %-50s %10s    %s\n", "No", "    Flow key", "Packets", "File" if  ! $opt_nohead;;
    foreach $f ( @flows){
	printf "%4d   %-50s %10d    %s\n", $n+++1, $f, $flow_pkts{$f}, $file{$f};
    }    
    $opt_nohead=1;
}
Olav Kvittem's avatar
Olav Kvittem committed
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230


sub mpeg_stats
{
    my ($flow_id, $packet, $us) = @_;
#Assume the packet-size is 188 bytes. Might be 204 if error-correcting codes 
#are in use.
    my $l = length ($packet);
#my $n = $l / 188;
    my $n = $CHECK_NUM_TSP;

#One UDP-packet contains $n number of MPEG-TS packets, check every one:
    for(my $j = 0; $j < $n; ++$j) {
	$mpeg_stats{$flow_id}{'num'} += 1;
	my $tspack = mpegtspacket->new (substr($packet, $j*188, 188));


#Update continuity counters
	cc_update_stats($flow_id, $tspack, $us);


	if ($tspack->is_valid() != 1) { next; }

#PCR calcs			
	if ($tspack->pcr_flag() == 1) {
	    pcr_update_stats($flow_id, $tspack);
	}


#Dwell calculations
	if ($tspack->payload_unit_start() == 1) {
	    dwell_update_stats($flow_id, $tspack);
	} else {
	    next;
	}

    }

#Set the time for the last UDP packet
    $mpeg_stats{$flow_id}{'last_udp_time'} = time();
}



#This function uses globals:
#%pcr_stats()
sub pcr_update_stats
{
    my ($f, $tspack) = @_;

# We might have wrapped around, which creates weird results.
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1231
1232
1233
1234
1235
1236
1237
# this is just a work-around... - reset pcr_checks if large values

	if (($pcr_stats{$f}{'last_pcr'} > $tspack->pcr_s())  and
		($pcr_stats{$f}{'last_pcr'} > 47000) and
		($tspack->pcr_s() < 10000)) {
	    $pcr_stats{$f}{'initialized'} = 0;
	}
Olav Kvittem's avatar
Olav Kvittem committed
1238
1239
1240
#
    if ($pcr_stats{$f}{'initialized'}) { 
	$d_pcr = (($tspack->pcr_s() - $pcr_stats{$f}{'last_pcr'}) + $PCR_MAX) % $PCR_MAX;
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1241
        # Time between our local clocks
Olav Kvittem's avatar
Olav Kvittem committed
1242
1243
1244
1245
	$d_t = time() - $pcr_stats{$f}{'real_last_time'};

	$pcr_stats{$f}{'real_last_time'} = time();
#		++$pcr_stats{$f}{'num'};
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1246
1247
1248
        if($d_pcr < 0){ # resequenced
	    $late{$f}++;
	}
Olav Kvittem's avatar
Olav Kvittem committed
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
	my $sample = abs($d_pcr - $d_t);
	my $k = $pcr_stats{$f}{'num'};

	$pcr_stats{$f}{'pcr_jitter_sum'} += $sample;
	$pcr_stats{$f}{'pcr_jitter_square'} += ($sample**2);
	++$pcr_stats{$f}{'num'};
#Max/Min-checks for PCR jitter

	if ($sample > $pcr_stats{$f}{'max_jit'}) {
	    $pcr_stats{$f}{'max_jit'} = $sample;
	} 
	if ($sample < $pcr_stats{$f}{'min_jit'}) {
	    $pcr_stats{$f}{'min_jit'} = $sample;
	}

#This calculates the PCR arrival difference mean and std 	
#$sample = $d_pcr;
	$tm = $pcr_stats{$f}{'running_dpcr_mean'};
	$ts = $pcr_stats{$f}{'running_dpcr_std'};
	$pcr_stats{$f}{'running_dpcr_mean'} = $tm + (($sample - $tm)/$k);
	$tm2 = $pcr_stats{$f}{'running_dpcr_mean'};	
	$pcr_stats{$f}{'running_dpcr_std'} = $ts + (($sample - $tm)*($sample - $tm2));
#		print $pcr_stats{$f}{'running_dpcr_mean'}."\n";

#Max/Min-checks for delta-PCR
	if ($sample > $pcr_stats{$f}{'max_dpcr'}) {
	    $pcr_stats{$f}{'max_dpcr'} = $sample;
	} 
	if ($sample < $pcr_stats{$f}{'min_jit'}) {
	    $pcr_stats{$f}{'min_dpcr'} = $sample;
	}



	$pcr_stats{$f}{'last_pcr'} = $tspack->pcr_s();
	$pcr_stats{$f}{'last_pcrb'} = $tspack->pcrb_s();

	$packets_between_pcr = 0;

#Got a new PCR-value, so synch the clocks
    } else {
#This is the first time we see a PCR, intialize hash.
#Time between this pcr and the last measured.
#$d_pcr = (($tspack->pcr() - $pcr_stats{$f}{'last_pcr'}))/(27*10**6);
#Time between our local clocks
#$d_t = time() - $pcr_stats{$f}{'real_last_time'};


	$pcr_stats{$f}{'running_jit_mean'} = 0; #($d_pcr - $d_t);
	$pcr_stats{$f}{'running_jit_std'} = 0;
	$pcr_stats{$f}{'running_dpcr_mean'} = 0; #first time
	$pcr_stats{$f}{'running_dpcr_std'} = 0;
	$pcr_stats{$f}{'real_last_time'} = time();
	$pcr_stats{$f}{'last_pcr'} = $tspack->pcr_s();
	$pcr_stats{$f}{'last_pcrb'} = $tspack->pcrb_s();
	$pcr_stats{$f}{'pcr_jitter_sum'} = 0;
	$pcr_stats{$f}{'num'} = 0;
	$pcr_stats{$f}{'max_jit'} = 0;
	$pcr_stats{$f}{'min_jit'} = (2**32)-1;
	$pcr_stats{$f}{'max_dpcr'} = 0;
	$pcr_stats{$f}{'min_dpcr'} = (2**32)-1;
	$pcr_stats{$f}{'initialized'} = true;
	$pcr_stats{$f}{'missing_pcrs'} = 0;
    }

}

#uses :
#last_ccs
#
sub cc_update_stats
{
    my ($f, $tspack, $us) = @_;
    my $secs = $us*10**(-6);
    my $prior = $last_ccs{$pid};
    $last_ccs{$tspack->PID()} = $tspack->continuity_counter();
    check_continuity($tspack->PID(), 
		     $prior,
		     $tspack->{'discontinuity'}, 	
		     $tspack->payload_unit_start() );

#printf("%d %d\n", $tspack->PID(), $tspack->continuity_counter());

#update continuity overview
    $last_ccs{$tspack->PID()} = $tspack->continuity_counter();

#update the per-counter continuity.
    $cc[$tspack->continuity_counter()]++;

#distribution updates
    if(!$opt_period || ($secs % $opt_period < ($opt_period/2))) {
	$dist1{$tspack->PID()} += 1;
    } elsif($secs % $opt_period <= ($opt_period)) {
	$dist2{$tspack->PID()} += 1;
    } 
}

sub compare_cc_dists
{
    my ($a, $b) = @_;
#	print Dumper(%$a); 
#	print "\n";
#	print Dumper(%$b); 
    my $metric = 0;
    foreach my $pid (keys %$a) {
	my $diff = $a->{$pid} - $b->{$pid};
	my $sum = $a->{$pid} + $b->{$pid};
#	print "sum: $sum diff: $diff\n";
#       $metric += $diff / $sum;
	$metric = exp($diff/1000);
    }

Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1361
1362
1363
1364
1365
1366
    if ($metric){
	return 10/$metric;
    } else {
	warn "Metric invalid $metric" if $opt_debug;
	return -1;
    }
Olav Kvittem's avatar
Olav Kvittem committed
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
}



sub dwell_update_stats
{
    my ($f, $tspack) = @_;
    my $pespack = mpegpespacket->new ($tspack->payload());	
    next if ($pespack->is_valid != 1);

#pts_stuff
    if($pespack->{'PTS_flag'} == 1) {
	++$pts_stats{$f}{'num'};

	if($pts_stats{$f}{'initialized'} == 1) {
#check if frame is late
	    if($pespack->pts_s() < $pcr_stats{$f}{'last_pcr'}) {
		$pts_stats{'late_frames'}++;
	    }

# 4 - Dwell-time calculations
	    if($pcr_stats{$f}{'last_pcr'} > 0 and $pespack->pts_s() > 0) {   #we want to compare against valid PCR
		my $dwell = ((abs($pcr_stats{$f}{'last_pcr'} - $pespack->pts_s())) + $PTS_MAX) % $PTS_MAX;
		$pts_stats{$f}{'dwell_sum'} += $dwell;
		$pts_stats{$f}{'dwell_squared'} += $dwell**2;
		$pts_stats{$f}{'last_dwell'} = $dwell;

#min/max calcoolatins
		if ($dwell > $pts_stats{$f}{'max_dwell'}) {
		    $pts_stats{$f}{'max_dwell'} = $dwell;
		} 
		if ($dwell < $pts_stats{$f}{'min_dwell'}) {
		    $pts_stats{$f}{'min_dwell'} = $dwell;
		}
	    }

	} else {
	    my $dwell = ((abs($pcr_stats{$f}{'last_pcr'} - $pespack->pts_s())) + $PTS_MAX) % $PTS_MAX;
	    $presentation_time = $pespack->pts_s();
	    $pts_stats{$f}{'mean_dwell'} = 0;
	    $pts_stats{$f}{'dwell_squared'} = 0;
	    $pts_stats{$f}{'std_dwell'} = $dwell;
	    $pts_stats{$f}{'max_dwell'} = 0;
	    $pts_stats{$f}{'min_dwell'} = (2**32)-1;
	    $pts_stats{$f}{'last_dwell'} = $dwell;
	    $pts_stats{$f}{'late_frames'} = 0;
	    $pts_stats{$f}{'num'} = 0;
	    $pts_stats{$f}{'initialized'} = 1;
	}
    }

}


sub check_continuity
{
    my ($pid, $cc, $discont, $payload) = @_;

    if (not exists $last_ccs{$pid}) {
	return;
    }	
    if ($last_ccs{$pid} == $cc and $payload == 0) {
	return;	
    }
    if (($last_ccs{$pid} + 1)%16 == $cc) {
	return;
    }
    if ($last_ccs{$pid} == $cc) {
	return;
    }
    $discontinuities++;
}




sub mpeg_debug
{
    print "Debug: ";
    print Dumper(%pcr_stats);
    print Dumper(%pts_stats);
    print Dumper(%mpeg_stats);
    print Dumper(@cc);
}

sub largest_deviation
{
    my ($expected, $num, $values) = @_;
#	print "\n\nhnnng: $num\n\n";
    my $max = 100000000;
    foreach $id (@$values) {
	my $val = abs(($id/$num) - $expected) if $num != 0;
#		printf("\nValue:%s, Expected: %s\n", $id/$num, $expected);
	if( $val < $max) {
	    $max = $val;
	}
    }
    return $max;
}




Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
#########################################################################
#
# compute the MOS value from R in the E-model
# Gurvinder Singh, 2010-05-07


sub init_mos{
     $Nc = -70;	# sum of all circuit noise powers, referred to the 0 dBr point
     $Ps = 35;	# room noise Ps at the sender side
     $Pr = 35;	# room noise Ps at the receiver side
     $slr = 8;	# Sender Loudness Rating
     $rlr = 2;	# Receiver Loudness Rating
     $Ds = 3;	# D-Value of Telephone, Sender Side
     $Dr = 3;	# D-Value of Telephone, Receiver Side
     $lstr = 18;	# Listener Sidetone Rating
     $stmr = 15;	# Sender Sidetone Masking Rating
     $Nfor = -64;	# Noise Floor at the Receiver Side
     $telr = 65;	# Talker Echo Loudness Rating
     $wepl = 110;	# Weighted Echo Path Loss
}

# Subtorutine to convert the natural log value to log base 10
    sub log10 {
	my $n = shift;
	return log($n)/log(10);
    }
    
# Subroutine to calculate the time related variable values to be used
# in calculating the impairements caused by the delay (Id)
    sub calc_timevar
    {
	my ($l_pl, $l_jitter, $l_rtt) = @_;
	my $Ta = 2 * $l_pl + $l_jitter + $l_rtt;
	my $T = $Ta;
	my $Tr = 2 * $Ta;
	
	return $Ta, $T, $Tr;
    }

# Subroutine to calculate the Mean Opinion Score (MOS) value from the given 
# R value obtained from E-model (ITU-T Rec. G.107). An estimate of the result
# of a subjective test. Higher values indicate better quality
sub calc_mos
{
    my ($r) = @_;
    my $mos;
    
    if ($r < 0) {
	$mos = 1;
    } elsif ($r > 100) {
	$mos = 4.5;
    } else {
	$mos = 1 + 0.035*$r + $r * ($r - 60) * (100 - $r) * 7 * (10 ** (-6));
	if ($mos < 1) {
	    $mos = 1;
	}
    }

    printf "Mos value is: %.02f \n",$mos if $opt_debug;
    return $mos;
}

# Subroutine to calculate the Ro, which represents in principle the basic
# signal-to-noise ratio, including noise sources such as circuit noise and
# room noise. T
sub calc_Ro
{
    my $Nfo = $Nfor + $rlr;
    my $olr = $slr + $rlr;
    my $Pre =35 + 10 * log10(1 + (10 ** (-0.8)));
    my $Nor = $rlr - 121 + $Pre + 0.008 * (($Pre - 35)**2);
    my $Nos = $Ps - $slr - $Ds - 100 + 0.004 *(($Ps - $olr - $Ds - 14)**2);
    my $No = 10 * log10((10**($Nc/10)) + (10**($Nos/10)) +
			(10**($Nor/10)) + (10**($Nfo/10)));

    my $Ro = 15 - (1.5 * ($slr + $No));
    print "Ro is: $Ro No is: $No\n"  if $opt_debug;
    return $Ro, $No;
}

# Subroutine to calculate Is, where Is is a combination of all impairments
# which occur more or less simultaneously with the voice signal.
sub calc_Is
{
    my ($qdu, $Ro, $No, $T) = @_;

    ######### Calculate the Iolr ##########
    my $olr = $slr + $rlr;
    my $xolr = $olr + 0.2*(64 + $No - $rlr);
    my $Iolr = 20 * (((1 + ($xolr/8)**8)**(1/8)) - ($xolr/8));

    ######### Calculate the Ist ##########
    my $stmro = -10 * log10((10**(-$stmr/10))+(exp(-$T/10) *
					       (10**(-$telr/10))));

    my $Ist = (12 * ((1+((($stmro - 13)/6)**8))**(1/8))) -
	(28 * ((1+((($stmro + 1)/19.4)**35))**(1/35))) -
	(13 * ((1+((($stmro - 3)/33)**13))**(1/13))) + 29;

    ######### Calculate the Iq ##########
    my $Q = 37;
    $Q -= 15 * log10($qdu) if $qdu > 0;
    my $G = 1.07 + (0.258 * $Q) + (0.0602 * ($Q**2));
    my $Z = 1.53 - $G/40;	# 46/30 = 1.53
    my $Y = (($Ro - 100)/15) + 5.47 - $G/9;	# 46/8.4 = 5.47
    my $Iq = 15 * log10(1 + 10**$Y + 10 **$Z);

    ######### Calculate the Is ##########
    my $Is = $Iolr + $Ist + $Iq;
    print "Is is: $Is, Iolr is: $Iolr, Ist is: $Ist, Iq is : $Iq\n" if $opt_debug;

    return $Is, $Ist;
}

# Subroutine to calculate the Id, which represents the impairments caused
# by the delay
sub calc_Id
{
    my ($Ro, $No, $Ist, $Ta, $T, $Tr) = @_;

    ######### Calculate the Idte ##########
    my $Idte;
    my $terv;
    if ($T < 1) {
	$Idte = 0;
    } else {
	$terv = $telr - 40 * log10((1 + ($T/10))/(1 + ($T/150))) +
	    6 * exp(-0.3 * ($T**2));
	if ($stmr < 9) {
	    $terv += $Ist/2;
	}
	
	my $Re = 80 + 2.5 * ($terv - 14);
	my $Roe = -1.5 * ($No - $rlr);
	$Idte = (($Roe - $Re)/2 +
		 sqrt(((($Ro - $Re)**2)/4) + 100) - 1)*
		 (1 - exp(-$T));
    }

    if ($stmr > 20) {
	my $Idtes = sqrt($Idte**2 + $Ist**2);
	$Idte = $Idtes;
    }

    ######### Calculate the Idle ##########
    my $Rle = 10.5 * ($wepl + 7) * (($Tr + 1)**(-1/4));
    my $Idle = ($Ro - $Rle)/2 + sqrt(((($Ro - $Rle)**2)/4) + 169);

    ######### Calculate the Idd ##########
    my $Idd;
    if ($Ta > 100) {
	my $X = log10($Ta/100) / log10(2);
	$Idd = 25 * (((1+ ($X**6))**(1/6)) - (3 * ((1+ (($X/3)**6))**(1/6))) + 2);
    } else {
	$Idd = 0;
    }
    
    ######### Calculate the Id ##########
    my $Id = $Idte + $Idle +$Idd;
    print"Id is: $Id Idte is: $Idte Idle is: $Idle Idd is: $Idd\n"  if $opt_debug;

    return $Id;
}

# Subroutine to calculate the impairement value depending
# upon the codec used in the communication
# Ref: Short- and Long-Term Packet Loss Behavior: Towards 
# Speech Quality Prediction for Arbitrary Loss Distributions
# by Alexander Raake
sub calc_codecvar
{
    my $l_codec = shift;
    
    # Initialize the impairment values
    my $Ie = 0;	# A scalar number allocated to a specific type of
    # impairment (codec), indicating the anticipated
    # incremental value of impairment (decrease of the
    # transmission rating factor R) resulting from the
    # type of impairment (codec). 

    my $Bpl = 0;	# Bpl is the robustness of a codec to random packet
    # loss. 

    my $Pc = 0.3;	# conditional packet loss probability in case of
    # consecutive packets loss

    if  ($l_codec eq "G.711") {
	$Ie = 0;
	$Bpl = 25.1;
    } elsif ($l_codec eq "G.723.1") {
	$Ie = 15;
	$Bpl = 16.1;
    } elsif ($l_codec eq "G.729A") {
	$Ie = 11;
	$Bpl = 19;
    } elsif ($l_codec eq "iLBC") {
	$Ie = 11;
	$Bpl = 32;
    }

    return $Ie, $Bpl, $Pc;
}

# Subroutine to calculate the Ie-eff, which represents impairments caused
# by low bit rate codecs and  impairment due to packet-losses of random
# distribution
sub calc_Ieff
{
    my ($Ie, $Bpl, $Pc, $Ppl) = @_;
    my $pl = $Ppl / 100;
    my $burstR = (1 - $pl) / (1 - $Pc);
    my $Ieff = $Ie + (95 - $Ie)*($Ppl/(($Ppl/$burstR) + $Bpl));
    
    print"Ieff is: $Ieff\n" if $opt_debug;
    return $Ieff;
}

# Subroutine to calculate the R value using E-model (ITU-T Rec. G.107)
# R is the result of the E-model, estimating users' satisfaction for
# transmission planning purposes.
sub calc_r
{
    my ($Ro, $Is, $Id, $Ieff, $A) = @_;
    my $r = $Ro - $Is - $Id - $Ieff + $A;
    printf"R is: %.02f \n",$r if $opt_debug;
    return $r;
}

# Analogue/Digital and Digital/Analogue conversions involve a distortion of
# the signal, perceived as a quantization noise. qdu is defined as the
# quantization noise resulting from a complete A/D encoding and D/A decoding
# following the 8 bit A-law (or mu-law), according to ITU-T Recommendation
# G.711. Note, that the qdu concept is no longer used for coders other than
# G.711. If an impairment factor Ie is used for a piece of equipment, then the
# qdu value for that same piece of equipment must not be used.
# my $qdu = 1;		# Number of Quantization Distortion Units



# Advantage factor, depends upon the communication device used
# This factor enables the planner to take into account the fact that users
# may accept some decrease in quality for access advantage, e.g. mobility
# or connections into hard-to-reach regions
# my $A = 0;	# For fixed wired phones it is 0 (Ref. ITU-T G.107)

sub mos_r{
# Time values related to the monitored connection
#    my $codec = $opt_codec || 'G.711';
#    my $rtt = $opt_rtt || 10;		# ms round trip time of the connection
#    my $pl;		# RTP packet length in ms
#    my $jitter;	        # Jitter value for this connection
#    my $Ppl;		# Percentage of the packet loss
    my ($codec, $rtt, $pl, $jitter, $Ppl)=@_;

    &init_mos;

    my $qdu = 0;		# Number of Quantization Distortion Units
    my $A = 0;	# For fixed wired phones it is 0 (Ref. ITU-T G.107)

    my @time_ret = calc_timevar($pl, $jitter, $rtt);
    my @codec_ret = calc_codecvar($codec);
    my @ro_ret = calc_Ro;
    my @Is_ret = calc_Is($qdu, $ro_ret[0], $ro_ret[1],$time_ret[1]);
    my $Id_ret = calc_Id($ro_ret[0], $ro_ret[1], $Is_ret[1], $time_ret[0],
			 $time_ret[1], $time_ret[2]);
    my $Ieff_ret = calc_Ieff($codec_ret[0], $codec_ret[1], $codec_ret[2], $Ppl);
    my $r_ret = calc_r($ro_ret[0], $Is_ret[0], $Id_ret, $Ieff_ret, $A);
    my $mos_ret = calc_mos($r_ret);

    return($mos_ret);
} # of mos_r


################################################################################

Olav Kvittem's avatar
Olav Kvittem committed
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
package mpegtspacket;

################
#
# Net::MPEG-TS::Packet: MPEG-TS packet object (perl only)
#
# UNINETT 2009 (www.uninett.no)
# Dabbler in code: Odd Rune S. Lykkebø <lykkebo@pvv.ntnu.no>
#
# References:
# [1] - ISO 13818-1

use strict;
use Carp; #The mother hen is watchful.
use Bit::Vector;

use vars qw/$VERSION/;
$VERSION="0.05";


sub new 
{
    my $class = shift;
    my ($packet) = @_;

    my $self = {
	valid => 1,
	size => undef,
	sync_byte => 0x47,
	transport_error => 0,
	transport_priority => 0,
	payload_unit_start => 0,
	PID => undef,
	transport_scrambling => 0,
	adaption_field_control => undef,
	continuity_counter => 0,

#Adaption fields
	adaption_field_length => 0,
# flags
	discontinuity => 0,
	random_access => 0,
	elementary_stre