#!/bin/sh


if [ $# -ne "1" ]; then
 echo "Usage: $0 dirname"
 exit
fi


name=$1
pushd $name


# high quality, 80 min / DVD
# fast encoding, slightly unusual MPEG2 (no B frames)
#flags="-c -q 6 -4 2 -2 1 -K file=matrix.txt -s -D 10 -R 0"
# slower encoding, classic MPEG2
#flags="-c -q 6 -4 2 -2 1 -K file=matrix.txt -s -D 10 -R 2"
#
# ok quality, 120 min / DVD
# fast encoding, slightly unusual MPEG2 (no B frames)
#flags="-c -q 6 -4 2 -2 1 -K tmpgenc -s -D 10 -R 0"
# slower encoding, classic MPEG2
flags="-c -q 6 -4 2 -2 1 -K tmpgenc -s -D 10 -R 2"


# Aspect ratio of the original DV tape
# 4:3
asr="--export_asr 2"
# 16:9
#asr="--export_asr 3"


bitr="7500"
xmlf="dvdauthor.xml"


# Steven Schultz's combined HQ matrix
cat - > matrix.txt << MATRIX
# High resolution INTRA table
8,16,18,20,24,25,26,30
16,16,20,23,25,26,30,30
18,20,22,24,26,28,29,31
20,21,23,24,26,28,31,31
21,23,24,25,28,30,30,33
23,24,25,28,30,30,33,36
24,25,26,29,29,31,34,38
25,26,28,29,31,34,38,42
# TMPEGEnc NON-INTRA table
16,17,18,19,20,21,22,23
17,18,19,20,21,22,23,24
18,19,20,21,22,23,24,25
19,20,21,22,23,24,26,27
20,21,22,23,25,26,27,28
21,22,23,24,26,27,28,30
22,23,24,26,27,28,30,31
23,24,25,27,28,30,31,33
MATRIX


rm -f $xmlf
# dvdauthor XML config head
cat - >> $xmlf << XMLHEAD
<dvdauthor>
<vmgm />
<titleset>
<titles>
<pgc>
XMLHEAD


for inp in `ls dv`; do
out=`basename $inp .avi`
transcode -i dv/$inp -x ffmpeg \
	-V -w $bitr \
	--encode_fields b \
	${asr} \
	-F 8,"${flags}" \
	-y mpeg2enc,raw -N 0x2000 -b 192 -m $out.ac3 \
	-o $out \
	--print_status 10
##################################################
# stuff to copy/paste in the transcode parameters
##################################################
# use this if DV sound is not sampled at 48kHz
# (it almost ALWAYS is 48kHz!)
#	-E 48000,16,2 -J resample \
#
# AC3 sound
#	-y mpeg2enc,raw -N 0x2000 -b 192 -m $out.ac3 \
#
# MP2 sound
#	-y mpeg2enc,mp2enc -b 224 -m $out \
##################################################


# use this with MP2
#mplex -r 10000 -f 8 -S 4400 $out.m2v $out.mpa -o $out.vob
# use this with AC3
mplex -r 10000 -f 8 -S 4400 $out.m2v $out.ac3 -o $out.vob
echo "<vob file=\"$out.vob\" />" >> $xmlf
done


# dvdauthor XML config tail
cat - >> $xmlf << XMLTAIL
</pgc>
</titles>
</titleset>
</dvdauthor>
XMLTAIL

dvdauthor -o $name -x $xmlf

chmod -R 0755 $name
chmod 0644 $name/*_TS/*
sync
popd
