#!/usr/bin/perl -w

use strict;

sub usage() {
	print STDERR "Usage: flvlength.pl file1\n";
	exit( 1 );
}

sub flvlength ($) {
    my $filename = $_[0];

    open(FLV, $filename) || return (undef, undef);
    my $buf = '';

	# read FLV file header and check for validity
    my $n = read FLV, $buf, 4;
    return undef if $n < 4;
    return undef unless $buf =~ /FLV/;
    
    # read version
    $n = read FLV, $buf, 1;
    return undef if $n < 1;
    
    # read offset to data
    $n = read FLV, $buf, 4;
    return undef if $n < 4;
    
	# seek to offset
    $n = read FLV, $buf, unpack("N", $buf)-9;


	# main loop, go through all packets until we are at the end of the file
    my $dataLength = 0;
    my $timeStamp = 0;
    while ( !eof(FLV) ) {
    
    	# Read offset
	    $n = read FLV, $buf, 4;
	    return ($timeStamp/1000) if eof(FLV); # If end of file return last time stamp
	    
	    # Read tag type
	    $n = read FLV, $buf, 1;
	    return ($timeStamp/1000) if eof(FLV); # If end of file return last time stamp
	    
	    # Read data size
	    $n = read FLV, $buf, 3;
	    return ($timeStamp/1000) if eof(FLV); # If end of file return last time stamp
	    $buf = "\0".$buf;
	    $dataLength = unpack("N", $buf);
	    
	    # Read time stamp
	    $n = read FLV, $buf, 3;
	    return ($timeStamp/1000) if eof(FLV); # If end of file return last time stamp
	    $buf = "\0".$buf;
	    $timeStamp = unpack("N", $buf);
	    
	    # Read reserved field
	    $n = read FLV, $buf, 4;
	    return ($timeStamp/1000) if eof(FLV); # If end of file return last time stamp
	    
		# Skip over data
	    $n = read FLV, $buf, $dataLength;
	    return ($timeStamp/1000) if eof(FLV); # If end of file return last time stamp
	    
    }
    return ($timeStamp/1000);
}

my $filename = shift or usage();
my $len = flvlength ($filename);
if ( $len ) {
	print STDERR $len." seconds\n";
} else {
	print STDERR "Not a FLV file.\n";
}

exit( 0 );
