qstream 72 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;
		}
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
318
		$endstream = tv_interval($t0, $tc) >= $opt_last if $opt_last && !$endstream;
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
    if ($opt_period){
	$interval=int($us/10**6 / $opt_period);
	if ($interval > $pinterval){
	    &mpeg_debug() if $opt_debug;
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
773
	    &display_stats();
Olav Kvittem's avatar
Olav Kvittem committed
774 775 776 777 778
	    $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

Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1039 1040
		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
1041

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

Olav Kvittem's avatar
Olav Kvittem committed
1044 1045 1046 1047
		    printf (" %4s  ",  
			    &lesbar(compare_cc_dists(\%dist1, \%dist2))) if $opt_mpeg;

		} else {
Jon Kåre Hellan's avatar
Jon Kåre Hellan committed
1048
		    printf " %4d %4.1f", $sumbyte{$f}/$n, sdv($n, $sumbyte{$f}, $ssbyte{$f});
Olav Kvittem's avatar
Olav Kvittem committed
1049 1050 1051 1052 1053 1054 1055
		}

		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
1056 1057
		$source;

Olav Kvittem's avatar
Olav Kvittem committed
1058
		#printf "in-print: \n\n%f\n\n", $maxbps{$f};
Olav Kvittem's avatar
Olav Kvittem committed
1059 1060 1061
	    } 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
1062

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

    }
}

Olav Kvittem's avatar
Olav Kvittem committed
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
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
1084 1085 1086 1087 1088 1089
sub avg {  
    my ($sum, $n)=@_;
    return 0 if $n <= 0;
    return $sum/$n;
}
sub sdv {
Olav Kvittem's avatar
Olav Kvittem committed
1090 1091 1092 1093 1094 1095
    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
1096 1097 1098 1099
}


sub lesbar{
Olav Kvittem's avatar
Olav Kvittem committed
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    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
1115 1116 1117

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

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

sub lesbars {
Olav Kvittem's avatar
Olav Kvittem committed
1123 1124 1125 1126 1127 1128 1129 1130 1131
    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
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 1180

}

# 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
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 1231


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
1232 1233 1234 1235 1236 1237 1238
# 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
1239 1240 1241
#
    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
1242
        # Time between our local clocks
Olav Kvittem's avatar
Olav Kvittem committed
1243 1244 1245 1246
	$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
1247 1248 1249
        if($d_pcr < 0){ # resequenced
	    $late{$f}++;
	}
Olav Kvittem's avatar
Olav Kvittem committed
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 1361
	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
1362 1363 1364 1365 1366 1367
    if ($metric){
	return 10/$metric;
    } else {
	warn "Metric invalid $metric" if $opt_debug;
	return -1;
    }
Olav Kvittem's avatar
Olav Kvittem committed
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 1470
}



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
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 1745
#########################################################################
#
# 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 <