#!/usr/bin/perl
# find first and last I-Frame based on index.vdr
use strict;

if (1 != @ARGV or !-f "$ARGV[0]/index.vdr" )
{
   print "find second and last Iframe in VDR - Recordings and print out timcode in marks.vdr Format\nUsage: $0 /path/to/recording\n";
   exit (1);
}

my @allIFrames ;
my $allframes = ( -s "$ARGV[0]/index.vdr" ) / 8 ;
	my $buffer = "";
	open (INDEX, "<$ARGV[0]/index.vdr");
	binmode (INDEX);
	for (my $frame = 1; $frame <=$allframes; $frame++) {
		my $pos = 8 * $frame;
		sysseek (INDEX, $pos, 0);
		sysread (INDEX, $buffer, 8);
		my ($offset, $type, $filenumber, $reserved) = unpack ("LCCS", $buffer);
		next if ( $type !=1 ) ;
		push @allIFrames , $frame ;
	}
	close INDEX ; 

# comment out for direct printing in marks.vdr :
#	open (MARKS, ">$ARGV[0]/marks.vdr");
for ( "$allIFrames[0]" , "$allIFrames[$#allIFrames]" ) {
	my ($h, $m, $s, $f) ;
	$f = $_ % 25 ;
	$_ -= $f ;
	$_ /= 25 ;
	$s = $_ % 60 ;
	$_ -= $s ;
	$_ /= 60 ;
	$m = $_ % 60 ;
	$_ -= $m ;
	$_ /= 60 ;
	$h = $_ ;

	printf ("%02d:%02d:%02d.%02d\n", $h, $m, $s, $f) ;
# comment out for direct printing in marks.vdr :
#	printf MARKS ("%02d:%02d:%02d.%02d\n", $h, $m, $s, $f);
}
# comment out for direct printing in marks.vdr :
#	close MARKS