#!/usr/bin/perl
#
# Generate everything needed to burn a DVD
# from DV avi files
#
# use:
# ./GenerateDVD.pl <avi1> <av2> ....
#
# First, generate the mpeg2 files
#
#
my $EncodeCommand = 
'mencoder -oac lavc -ovc lavc -of mpeg -mpegopts format=dvd -vf '
.'scale=720:576,harddup -srate 48000 -af lavcresample=48000 -lavcopts '
.'vcodec=mpeg2video:vrc_buf_size=1835:vrc_maxrate=9800:vbitrate=5000:keyint=15:aspect=4/3:'
.'acodec=ac3:abitrate=192 -ofps 25 -o ';

#
my @FileList = ();
my $baseName = "";
my $TargetDir = '/athena/DVD';

# Create DVD directory
`mkdir -p ${TargetDir}`;

# Convert the avi files
while(@ARGV)
{
	my $currentFile = shift(@ARGV);
	$currentFile =~ /([^\/]+)$/;
	
	# Generate a common base name
	my $PlainFileName = $1;
	
	
	$PlainFileName =~ s/\.[^\.]+$//ig;
	if($baseName)
	{
		my $Point=0;
		while($Point < length($baseName) && 
		      substr($baseName, $Point, 1) == substr($PlainFileName, $Point, 1))
		{
			++$Point;
		};
		$baseName = substr($baseName, 0, $Point);
	}
	else
	{
		$baseName = $PlainFileName;
	};
	
	# Generate output filename
	my $outName = "${TargetDir}/$PlainFileName.mpg";
	push(@FileList, $outName);
	
	# Encode to MPEG2
	# and convert sound into AC3
	unless(-s "$outName")
	{
		`$EncodeCommand '$outName' '$currentFile'`;
	}
	else
	{
		print STDERR "File exists: $outName, ignored\n";
	};
};

# Generate the dvdauthor XML file
open(XMLOUT, ">${TargetDir}/$baseName.xml") || die "$baseName.xml: $!";
print XMLOUT << "ENDOFDVDAUTHORXMLHEAD";
<dvdauthor>
  <vmgm />
  <titleset>
    <titles>
      <pgc>
ENDOFDVDAUTHORXMLHEAD

# Write the list with videos
my $Start = 0;
my $NumberOfChapters=4;
my $ChapterDiff=5;
foreach my $currentMPEG (@FileList)
{
	my $Size = -s $currentMPEG;
	$Chapters="";
	for(my $i=0;$i<$NumberOfChapters;++$i)
	{
		my $ChapterMinutes = $Start;
		$Chapters.= ',' if $i > 0;
		$Chapters.= int($Start/60).':'.$Start%60;
		$Start += $ChapterDiff;
	};
	
        print XMLOUT "<vob file=\"$currentMPEG\" chapters=\"$Chapters\" />\n";
};

print XMLOUT << "ENDOFDVDAUTHORXMLTAIL";
      </pgc>
    </titles>
  </titleset>
</dvdauthor>
ENDOFDVDAUTHORXMLTAIL
close(XMLOUT);

# Create DVD directory
`mkdir -p ${TargetDir}/$baseName`;

# Fill the DVD directory
`dvdauthor -o ${TargetDir}/$baseName -x ${TargetDir}/$baseName.xml`;
# Get rid of the xml file
if(-d "${TargetDir}/$baseName")
{
    `rm ${TargetDir}/$baseName.xml`;
    foreach my $currentMPEG (@FileList)
    {
	    `rm $currentMPEG`;
    }
}
# Create ISO image
# `mkisofs -dvd-video -o ${TargetDir}/$baseName.iso ${TargetDir}/$baseName`
