Major feature: Added support for makemkv script
[rip_dvd/.git] / rip_dvd
1 #!/bin/bash
2 #
3 # Author: Alan J. Pippin (apippin@pippins.net)
4 # Date: 05/17/2009
5 #
6   REV=2.5
7 #
8 # Description: This script wraps a number of linux utilities to
9 # create a recipe for ripping protected DVDs, circumventing 
10 # ARcoSS and CRC checksum error protection schemes used on many
11 # newer DVDs. Edit as appropriate for your needs. I use this to
12 # backup DVDs I own, and do not condone any other activity it
13 # may be used for.
14 #
15 # Known Issues/Limitations:
16 # - Mirror mode is always done in ISO mode
17 #
18 # See the README file for information about the dependencies
19 # this script has.
20
21 ##############################################################################################
22 # Global Variables
23 ##############################################################################################
24 typeset cmd="$0 $*"
25 typeset dvdname=""
26 typeset debug=""
27 typeset dest=""
28 typeset isofile=""
29 typeset vobfile=""
30 typeset dvdpath=""
31 typeset aspect=""
32 typeset SCALE=""
33 typeset CROP=""
34 typeset profile="xvidhq"
35 typeset extension=""
36 typeset mailto=""
37 typeset encoder=""
38 typeset default_alang="en"
39 typeset track=""
40 typeset drc="0.0"
41 typeset handbrake_xvid=""
42 typeset handbrake_mp4=""
43 typeset makemkv=""
44 typeset makemkv_disc_id=""
45 typeset mkvextract=""
46 typeset mkvpropedit=""
47 typeset mkvmerge=""
48 typeset mp4box=""
49 typeset dvdxchap=""
50 typeset -i default_aid=128
51 typeset -i aid_override=-1
52 typeset -i force_onepass_mode=0
53 typeset -i eject_disk=1
54 typeset -i keep_isofile=0
55 typeset -i keep_vobfile=0
56 typeset -i keep_dvdfolder=0
57 typeset -i keep_intermediate_files=0
58 typeset -i make_final_dest_vob=0
59 typeset -i make_final_dest_iso=0
60 typeset -i make_final_dest_folder=0
61 typeset -i make_final_dest_comp=0
62 typeset -i errors=0
63 typeset -i show_usage=0
64 typeset -i mirror_mode=0
65 typeset -i target_video_bitrate=2000
66 typeset -i target_audio_bitrate=224
67 typeset -i target_size=0
68 typeset -i audio_2ch=0
69 typeset -i audio_6ch=0
70 typeset -i invalid_feature_title=0
71 typeset -i feature_title_override=0
72 typeset -i mplayer_dumpstream_incompatibility=0
73 typeset -i lsdvd_incompatibility=0
74 typeset -i custom_video_bitrate=0
75 typeset -i custom_audio_bitrate=0
76 typeset -i custom_audio_2ch=0
77 typeset -i custom_audio_6ch=0
78 typeset -i minimum_feature_title_length=60
79 typeset -i lsdvd_timeout=10
80 typeset -i real_isofile=0
81
82 ##############################################################################
83 # Local Machine Settings:
84 # Sources both the "default" conf file tracked by GIT (rip_dvd.conf.dist)
85 # and the local conf file created by each local machine (rip_dvd.conf)
86 # Copy the rip_dvd.conf.dist file to rip_dvd.conf and edit the later.
87 # This will allow you to override all the default values to meet your needs
88 # in a way that won't get clobbered when you pull updates from my GIT repo.
89 ##############################################################################
90 config="${0%/*}/rip_dvd.conf"
91
92 # The config file will be searched for in the following location order:
93 found_config=0
94
95 # 1) /path/to/rip_dvd/script/rip_dvd.conf.dist
96 [ -e "${config}.dist" ] && found_config=1 && . "${config}.dist"
97
98 # 2) /path/to/rip_dvd/script/rip_dvd.conf
99 [ -e "${config}" ] && found_config=1 && . "${config}"
100
101 # 3) /etc/rip_dvd.conf
102 [ -e "/etc/rip_dvd.conf" ] && found_config=1 && . "/etc/rip_dvd.conf"
103
104 # 4) $PWD/rip_dvd.conf
105 [ -e "$PWD/rip_dvd.conf" ] && found_config=1 && . "$PWD/rip_dvd.conf"
106
107 # Check to make sure we found the config file
108 if [ $found_config -eq 0 ]; then
109   echo "-E- Unable to find the rip_dvd.conf file: $config"
110   exit 1
111 fi
112
113 ##############################################################################################
114 # Command line processing
115 ##############################################################################################
116 while (($#)) && getopts 162wmvifkzx:ht:n:d:b:B:s:t:a:p:e:j:l:r: opt "$@"
117 do
118     case $opt in
119         (n)     dvdname=$OPTARG;;
120         (d)     dest=$OPTARG;;
121         (b)     target_video_bitrate=$OPTARG; custom_video_bitrate=1;;
122         (B)     target_audio_bitrate=$OPTARG; custom_audio_bitrate=1;;
123         (s)     target_size=$OPTARG;;
124         (2)     audio_2ch=1; custom_audio_2ch=1;;
125         (6)     audio_6ch=1; custom_audio_6ch=1;;
126         (1)     force_onepass_mode=1;;
127         (v)     make_final_dest_vob=1;;
128         (i)     make_final_dest_iso=1;;
129         (f)     make_final_dest_folder=1;; 
130         (z)     make_final_dest_comp=1;;
131         (e)     encoder=$OPTARG;;
132         (m)     mirror_mode=1;;
133         (k)     keep_intermediate_files=1;;
134         (t)     feature_title_override=$OPTARG;;
135         (a)     aspect=$OPTARG;;
136         (p)     profile=$OPTARG;;
137         (x)     extension=$OPTARG;;
138         (j)     eject_disk=$OPTARG;;
139         (l)     aid_override=$OPTARG;;
140         (r)     drc=$OPTARG;;
141         (w)     set -x;;
142         (h)     show_usage=1;;
143         (:)     echo >&2 "$0: $OPTARG requires a value"; errors=errors+1;;
144         (\?)    echo >&2 "$0: invalid option '$OPTARG'"; errors=errors+1;;
145     esac
146 done
147
148 shift $((OPTIND-1))
149
150 function usage() {
151     echo >&2 "Usage: ${0##*/} -d <destdir> [ <options> ]"
152     echo >&2 "Revision $REV"
153     echo >&2 "Options:"
154     echo >&2 "   -d <destdir>  Specify the destination directory to store the ripped DVD to"
155     echo >&2 "   -n <dvdname>  Specify a path to a DVD folder or file to process:"
156     echo >&2 "                 1) If this option is not specified, the DVD will be ripped from $dev"
157     echo >&2 "                 2) If dvdname is a full path to a DVD folder, it will be ripped as a DVD instead of $dev"
158     echo >&2 "                 3) If dvdname is a full path to an MPG2 file, it will be ripped as a DVD instead of $dev"
159     echo >&2 "                 4) If dvdname is a full path to an ISO file, it will be ripped as a DVD instead of $dev"
160     echo >&2 "                 5) If dvdname is a full path to a VOB file, it will be ripped as a DVD instead of $dev"
161     echo >&2 "   -p <profile>  Specify which encoding profile to use in -w mode as shown below:"
162     echo >&2 "                 Mencoder and Handbrake Encoder Profiles:"
163     echo >&2 "                 - xvidvhq = AVI, very high quality encoding, Xvid codec, 2 pass encoding"
164     echo >&2 "                 - xvidhq = AVI, high quality encoding, Xvid codec, 2 pass encoding (default)"
165     echo >&2 "                 - xvid = AVI, fast encoding, Xvid codec, 2 pass encoding"
166     echo >&2 "                 - iphone = MP4, x264 codec, 2 pass encoding, forced 480:320 scaling"
167     echo >&2 "                 - ipod = MP4, x264 codec, 2 pass encoding, forced 320:240 scaling"
168     echo >&2 "                 Handbrake Only Encoder Profiles:"
169     echo >&2 "                 - mkvvhq = MKV, very high quality encoding (0.90 quality) (requires makemkv encoder option)"
170     echo >&2 "                 - mkvhq = MKV, high quality encoding (0.85 quality) (requires makemkv encoder option)"
171     echo >&2 "                 - mp4vhq = MP4, very high quality encoding, x264 codec, 2 pass encoding"
172     echo >&2 "                 - mp4hq = MP4, high quality encoding, x264 codec, 2 pass encoding"
173     echo >&2 "                 - mp4 = MP4, fast encoding, x264 codec, 2 pass encoding"
174     echo >&2 "                 - hb_<profile> = Any predefined HandBrake profile (run HandBrakeCLI -z and replace spaces with underscores) "
175     echo >&2 "   -x <ext>      Specify a suffix extension to apply to the end of the final image filename (like .xvid, .ipod, etc)"
176     echo >&2 "                 If you run multiple instances of this script ripping the same DVD, you need to specify this option."
177     echo >&2 "   -m            Make a mirror image of the DVD and save it as a DVD ISO file"
178     echo >&2 "                 The default operation is non-mirror mode where only the main"
179     echo >&2 "                 feature title will be ripped."
180     echo >&2 "   -v            Make the final image a DVD VOB file"
181     echo >&2 "   -i            Make the final image a DVD ISO file"
182     echo >&2 "   -f            Make the final image a DVD folder"
183     echo >&2 "   -z            Make the final image a compressed file based on your profile selection and encoder"
184     echo >&2 "   -e <encoder>  Specify the encoder to use to make the compressed file (valid encoders=mencoder|handbrake|makemkv) (default=handbrake if found)"
185     echo >&2 "                 You must also specify the target size or bitrate using the '-s' or '-b' options with xvid profiles"
186     echo >&2 "   -s <size>     Set the target size of the compressed file in MB (ex: 700, 1000, etc)"
187     echo >&2 "   -b <bitrate>  Set the video bitrate desired in the compressed file in kbits/sec (ex: 1500, 2000 (default), etc)"    
188     echo >&2 "   -B <bitrate>  Set the audio bitrate desired in the compressed file in kbits/sec (ex: 96, 128, 160, 224 (default), 300, etc)"    
189     echo >&2 "   -a <W:H>      Specify the width x height aspect ratio to scale the DVD to (only used in -z mode)"
190     echo >&2 "      <W>        If only the width is given, it will autoset the height to a value which preserves the aspect ratio"
191     echo >&2 "                 The default behavior is autoaspect mode, which preserves the original aspect, with no scaling being done"
192     echo >&2 "   -j <n>        Eject the disk:"
193     echo >&2 "                 - 0 = do not eject the disk"
194     echo >&2 "                 - 1 = eject after the entire script is done (default)"
195     echo >&2 "                 - 2 = eject after the disk is no longer needed (prior to starting the encode process)"
196     echo >&2 "                 The last option will allow you to start ripping another disk while the encoding process is running on a previous"
197     echo >&2 "   -1            Force 1-pass encoding mode across all profiles"
198     echo >&2 "   -2            Use 2 channel MP3 audio encoding when making a compressed file (default is 6 channel AC3)"
199     echo >&2 "   -6            Use 6 channel AC3 audio encoding when making a compressed file (default)"
200     echo >&2 "   -r <x.x>      Apply extra dynamic range compression to the audio, making soft sounds louder. "
201     echo >&2 "                 Range is 1.0 to 4.0 with 1.5 - 2.5 being a useful range (HandBrake Only) (default value is 0.0)"
202     echo >&2 "   -k            Keep the intermediate files (good for debugging)"
203     echo >&2 "                 In -z mode, run with this option to keep the original .VOB file"
204     echo >&2 "                 By default, all intermediary files are deleted. Only the final image is kept"
205     echo >&2 "   -l <aid>      Specify the audio AID language ID to rip from the source DVD"
206     echo >&2 "   -t <title>    Specify the main feature title to pull from the DVD (only required if this script can't figure it out)"
207     echo >&2 "   -w            Set the sh Execute/Verbose flag (causes every command to be echoed)"
208     echo >&2 ""
209     exit 2
210 }
211
212 if (($errors)) || (($show_usage))
213 then
214   usage
215 fi
216
217 # Sanity Check - Command Line Options 
218 if [ "$dest" == "" ]; then
219   echo "-E- You must specify a destination directory with '-d'" | tee -a $logfile
220   usage
221 fi
222
223 if [ $make_final_dest_vob -eq 0 ] && [ $make_final_dest_iso -eq 0 ] && 
224    [ $make_final_dest_folder -eq 0 ] && [ $make_final_dest_comp -eq 0 ] && [ $mirror_mode -eq 0 ]; then
225     # Make our default dest type a compressed movie if the user didn't ask for anything else to be done
226     make_final_dest_comp=1
227 fi
228
229 if ([ $target_size -ne 0 ] || [ "$aspect" != "" ]) && [ $make_final_dest_comp -ne 1 ]; then
230   echo "-E- You can't specify a target_size, or aspect in non compressed file mode. You must specify '-z' when using '-b' or '-s' or '-a'" | tee -a $logfile
231   usage
232 fi
233
234 if [ $target_video_bitrate -eq 0 ] && [ $target_size -eq 0 ] && [ $make_final_dest_comp -eq 1 ]; then
235   echo "-E- You must specify a bitrate in compressed file mode. You must specify '-b' or '-s' when using '-z'" | tee -a $logfile
236   usage
237 fi
238
239 if [ $mirror_mode -eq 1 ]; then
240   if [ $make_final_dest_vob -eq 1 ] || [ $make_final_dest_iso -eq 1 ] || 
241      [ $make_final_dest_folder -eq 1 ] || [ $make_final_dest_comp -eq 1 ]; then
242     echo "-E- You can't specify '-v' or '-i' or '-f' or '-z' when operating in mirror mode with '-m'" | tee -a $logfile
243     usage
244   fi
245 fi
246
247 # If audio channel requirements weren't given, assume a default value of 6channel audio
248 if [ $audio_2ch -eq 0 ] && [ $audio_6ch -eq 0 ]; then
249   audio_6ch=1
250   custom_audio_6ch=1
251 fi
252
253 # Make handbrake the default encoder if not specified and we can find it
254 if [ -z "$encoder" ]; then
255   encoder="mencoder"; # If we can't find handbrake or makemkv, set mencoder as the default
256   [[ -x `which $handbrake_xvid` ]] && [[ "$profile" =~ "xvid" ]] && encoder="handbrake";
257   [[ -x `which $handbrake_mp4` ]] && [[ "$profile" =~ "mp4" ]] && encoder="handbrake";
258   [[ -x `which $handbrake_mp4` ]] && [[ "$profile" =~ "ip" ]] && encoder="handbrake";
259   [[ -x `which $handbrake_mp4` ]] && [[ "$profile" =~ "hb" ]] && encoder="handbrake";
260   [[ -x `which $makemkv` ]] && [[ "$profile" =~ "mkv" ]] && encoder="makemkv";
261 fi
262
263 # Sanity check the profile selection
264 if [[ "$encoder" == "mencoder" ]]; then
265   [[ "$profile" =~ "mp4" ]] && echo "-E- invalid encoder $encoder selected for mp4 profile: $profile" && exit
266   [[ "$profile" =~ "mkv" ]] && echo "-E- invalid encoder $encoder selected for mkv profile: $profile" && exit
267 fi
268 if [[ "$encoder" == "handbrake" ]]; then
269   [[ "$profile" =~ "mkv" ]] && echo "-E- invalid encoder $encoder selected for mkv profile: $profile" && exit
270 fi
271
272 if [[ "$encoder" != "mencoder" ]] && [[ "$encoder" != "handbrake" ]] && [[ "$encoder" != "makemkv" ]]; then
273   echo "-E- Invalid encoder specified: $encoder"
274   exit 1
275 fi
276
277 # If the aspect ratio option was specified, set the scale variable appropriately for mencoder
278 if [ "$aspect" != "" ]; then
279   echo "$aspect" | grep -q "x"
280   if [ $? == 0 ]; then
281     echo "-E- You must specify the aspect option with a value whose format is W:H"
282     exit 1
283   fi
284   echo "$aspect" | grep -q ":"
285   if [ $? != 0 ]; then
286     [ "$encoder" == "mencoder" ] && SCALE=",scale -zoom -sws 9 -xy $aspect"
287     [ "$encoder" == "handbrake" ] && SCALE="-w $aspect"
288   else
289     [ "$encoder" == "mencoder" ] && SCALE=",scale=$aspect"
290     if [ "$encoder" == "handbrake" ]; then
291        WIDTH=`echo "$aspect" | awk -F ':' '{ print $1; }'`
292        HEIGHT=`echo "$aspect" | awk -F ':' '{ print $2; }'`
293        SCALE="-w $WIDTH -l $HEIGHT"
294     fi
295   fi
296 fi
297
298 # Sanity Check - Key executables
299 [[ ! -x `which lsdvd` ]] && echo "-E- missing dependency: lsdvd" && exit
300 [[ ! -x `which volname` ]] && echo "-E- missing dependency: volname" && exit
301 [[ ! -x `which ddrescue` ]] && echo "-E- missing dependency: ddrescue" && exit
302 [[ ! -x `which dvdbackup` ]] && echo "-E- missing dependency: dvdbackup" && exit
303 [[ ! -x `which mencoder` ]] && echo "-E- missing dependency: mencoder" && exit
304 [[ ! -x `which makexml` ]] && echo "-E- missing dependency: makexml" && exit
305 [[ ! -x `which dvdauthor` ]] && echo "-E- missing dependency: dvdauthor" && exit
306 [[ ! -x `which mkisofs` ]] && echo "-E- missing dependency: mkisofs" && exit
307 [[ -n "$handbrake_xvid" ]] && [[ ! -x `which $handbrake_xvid` ]] && echo "-E- missing handbrake xvid encoder, set in rip_dvd.conf to: $handbrake_xvid" && exit
308 [[ -n "$handbrake_mp4" ]] && [[ ! -x `which $handbrake_mp4` ]] && echo "-E- missing handbrake mp4 encoder, set in rip_dvd.conf to: $handbrake_mp4" && exit
309 [[ -n "$makemkv" ]] && [[ ! -x `which $makemkv` ]] && echo "-E- missing makemkv encoder, set in rip_dvd.conf to: $makemkv" && exit
310 [[ "$encoder" == "handbrake" ]] && [[ "$profile" =~ "xvid" ]] && [[ ! -x `which $handbrake_xvid` ]] && echo "-E- missing HandBrake encoder: $handbrake_xvid" && exit
311 [[ "$encoder" == "handbrake" ]] && [[ "$profile" =~ "mp4" ]] && [[ ! -x `which $handbrake_mp4` ]] && echo "-E- missing HandBrake encoder: $handbrake_mp4" && exit
312 [[ "$encoder" == "handbrake" ]] && [[ "$profile" =~ "ip" ]] && [[ ! -x `which $handbrake_mp4` ]] && echo "-E- missing HandBrake encoder: $handbrake_mp4" && exit
313 [[ "$encoder" == "handbrake" ]] && [[ "$profile" =~ "hb" ]] && [[ ! -x `which $handbrake_mp4` ]] && echo "-E- missing HandBrake encoder: $handbrake_mp4" && exit
314 [[ "$encoder" == "makemkv"   ]] && [[ "$profile" =~ "mkv" ]] && [[ ! -x `which $makemkv` ]] && echo "-E- missing MakeMKV encoder: $makemkv" && exit
315 [[ "$encoder" == "makemkv"   ]] && [[ "$profile" =~ "mkv" ]] && [[ ! -x `which $mkvextract` ]] && echo "-E- missing mkvextract: $mkvextract" && exit
316 [[ "$encoder" == "makemkv"   ]] && [[ "$profile" =~ "mkv" ]] && [[ ! -x `which $mkvpropedit` ]] && echo "-E- missing mkvpropedit: $mkvpropedit" && exit
317 [[ "$encoder" == "makemkv"   ]] && [[ "$profile" =~ "mkv" ]] && [[ ! -x `which $mkvmerge` ]] && echo "-E- missing mkvmerge: $mkvmerge" && exit
318 [[ "$encoder" == "handbrake" ]] && [[ "$profile" =~ "mp4" ]] && [[ ! -x `which $mp4box` ]] && echo "-E- missing mp4box: $mp4box" && exit
319 [[ "$encoder" == "handbrake" ]] && [[ ! -x `which ffmpeg` ]] && echo "-E- missing dependency: ffmpeg" && exit
320
321 ##############################################################################################
322
323 typeset -i ripdvd
324 if [ -z "$dvdname" ]; then
325
326   # make sure the DVD device is accessible
327   volname $dev > /dev/null 2>&1
328   if [ $? != 0 ]; then
329     echo "-E- Can't access the DVD device $dev"
330     exit 1
331   fi
332   # now capture the volume name from the device
333   dvdname=`volname $dev | awk '{ print $1 }'`
334   ripdvd=1
335
336 else 
337
338   # check to see if dvdname is a full path to a real directory
339   # if it is, set dvdname and dvdpath appropriately
340   if [ -d "$dvdname" ]; then
341     dvdpath="$dvdname"
342     dvdname=`basename "$dvdname"`
343     keep_dvdfolder=1
344     if [ -z "$dvdname" ]; then
345      echo "-E- Unable to extract dvdname from path: $dvdpath"
346      exit 1
347     fi
348     if [ ! -d "$dvdpath/VIDEO_TS" ]; then
349       echo "-E- You must supply a full path to a valid DVD folder with this option"
350       exit 1
351     fi
352   fi
353
354   # Check to see if dvdname is a full path to a file
355   if [ -f "$dvdname" ]; then
356     valid_file=0
357
358     # check to see if dvdname is a full path to an MPG2 (VOB) file
359     # if it is, set dvdname and vobfile appropriately
360     file "$dvdname" | grep -q "MPEG"
361     if [ $? == 0 ]; then
362       # It is a valid MPEG2 file, now strip the extension off our dvdname
363       vobfile="$dvdname"
364       dvdname=`basename "$dvdname"`
365       dvdname=${dvdname%.[^.]*}
366       keep_vobfile=1
367       valid_file=1
368     fi
369
370     # check to see if dvdname is a full path to an ISO file
371     # if it is, set dvdname and isofile appropriately
372     file "$dvdname" | grep -q -e "ISO" -e "UDF"
373     if [ $? == 0 ]; then
374       # It is a valid ISO file, now strip the extension off our dvdname
375       isofile="$dvdname"
376       dvdname=`basename "$dvdname"`
377       dvdname=${dvdname%.[^.]*}
378       keep_isofile=1
379       valid_file=1
380       real_isofile=1
381     fi    
382
383     # check to see if dvdname is a full path to an ISO file
384     # if it is, set dvdname and isofile appropriately
385     file "$dvdname" | grep -q -e "VOB"
386     if [ $? == 0 ]; then
387       # It is a valid VOB file, now strip the extension off our dvdname
388       vobfile="$dvdname"
389       dvdname=`basename "$dvdname"`
390       dvdname=${dvdname%.[^.]*}
391       keep_vobfile=1
392       valid_file=1
393     fi  
394     
395     # check to see if dvdname is a full path to an ISO file
396     # if it is, set dvdname and isofile appropriately
397     file "$dvdname" | grep -q -e "mkv"
398     if [ $? == 0 ]; then
399       # It is a valid VOB file, now strip the extension off our dvdname
400       isofile="$dvdname"
401       dvdname=`basename "$dvdname"`
402       dvdname=${dvdname%.[^.]*}
403       keep_isofile=1
404       valid_file=1
405     fi    
406
407
408     # If we didn't find a handler for the file above, complain
409     if [ $valid_file -eq 0 ]; then
410       echo "-E- Unsupported file type: $vobfile"
411       exit 1
412     fi
413
414   # Throw an error if we can't find what the -n option is pointing to
415   else 
416     echo "-E- Unable to find the directory or file specified by the '-n $dvdname' option. Please make sure the path is valid."
417     exit 1
418   fi
419
420   # Set the ripdvd flag to false since we aren't ripping a DVD disk
421   ripdvd=0
422
423   # Since we aren't ripping a DVD disk, don't eject anything either
424   eject_disk=0
425
426 fi
427
428 # remove bad characters from the dvdname
429 dvdname=${dvdname%.} # remove trailing '.' character
430
431 # add the suffix extension to the end of the dvdname
432 dvdname=$dvdname$extension
433
434 # make a "safe" dvdname (remove special characters)
435 safedvdname=`basename "$dvdname" | sed 's/[ !&*\\$?]/_/g'`
436
437 # Make sure we have a non-empty dvdname
438 if [ -z "$dvdname" ]; then
439   echo "-E- unable to determine dvdname"
440   exit 1
441 fi
442
443 # make sure our vobfile value is set
444 if [ -z "$vobfile" ]; then
445   vobfile="$dest/$dvdname.VOB"
446 fi
447
448 # set up some variables to hold various logfiles
449 logfile="$logdir/$dvdname.log"
450 passlogfile="$tmpdir/$safedvdname.log"
451 ddrescuelog=`tempfile`
452 dvdauthorlog=`tempfile`
453 encodelog=`tempfile`
454 dumplog=`tempfile`
455
456 # create the tmpdir if it doesn't already exist
457 if [ ! -d "$tmpdir" ]; then
458   mkdir -p "$tmpdir"
459   if [ $? != 0 ]; then
460     echo "-E- Unable to create the tmpdir: $tmpdir"
461     exit 1
462   fi
463 fi
464
465 # create the logdir if it doesn't already exist
466 if [ ! -d "$logdir" ]; then
467   mkdir -p "$logdir"
468   if [ $? != 0 ]; then
469     echo "-E- Unable to create the logdir: $logdir"
470     exit 1
471   fi
472 fi
473
474 ##############################################################################################
475 # cleanup functions
476 ##############################################################################################
477 cleanup() { 
478   if [ $keep_intermediate_files -eq 0 ]; then
479     [[ -e "$dvdauthorlog" ]] && rm -f "$dvdauthorlog"
480     [[ -e "$ddrescuelog" ]] && rm -f "$ddrescuelog"
481     [[ -e "$encodelog" ]] && rm -f "$encodelog"
482     [[ -e "$dumplog" ]] && rm -f "$dumplog"
483   else
484     [[ -e "$dvdauthorlog" ]] && echo "-> Keeping dvdauthor log: $dvdauthorlog" | tee -a "$logfile"
485     [[ -e "$ddrescuelog" ]] && echo "-> Keeping ddrescue log: $ddrescuelog" | tee -a "$logfile"
486     [[ -e "$encodelog" ]] && echo "-> Keeping encode log: $encodelog" | tee -a "$logfile"
487     [[ -e "$dumplog" ]] && echo "-> Keeping dump log: $dumplog" | tee -a "$logfile"
488   fi
489   echo ""
490 }
491
492 fatal_and_exit() {
493   if [[ -z "$1" ]]; then
494     msg="-E- control-c killed us"
495   else
496     msg=$1
497   fi
498   echo -e 2>&1 "$msg" | tee -a "$logfile"
499   if [[ -n "$mailto" ]]; then
500     echo -e "$msg" | mailx -s "dvd rip of $dvdname FAILED" "$mailto"
501   fi
502   keep_intermediate_files=1
503   exit 1
504 }
505
506 # Call our cleanup functions on INT and EXIT signals
507 trap fatal_and_exit INT
508 trap cleanup EXIT
509
510 ##############################################################################################
511 # processing functions
512 ##############################################################################################
513
514 function alarm() { perl -e 'alarm shift; exec @ARGV' "$@"; }
515
516 function lsdvd_longest_title {
517   dev="$1"
518
519   # Only use lsdvd to extract the longest feature title if we didn't detect an incompatibility earlier
520   if [ $lsdvd_incompatibility -eq 1 ]; then
521     invalid_feature_title=1
522     return
523   fi
524
525   # Try the normal lsdvd command to see if it works
526   alarm $lsdvd_timeout lsdvd $dev >> "$logfile" 2>&1
527   if [ $? != 0 ]; then
528     # lsdvd didn't work
529     invalid_feature_title=1
530     lsdvd_incompatibility=1
531     return
532   fi
533  
534   # lsdvd is good to go, use it
535   feature_title=`lsdvd $dev 2>/dev/null | awk '/Longest/ { print $NF }'`
536 }
537
538 function lsdvd_css {
539   dev="$1"
540
541   # Try the normal lsdvd command to see if it works
542   alarm $lsdvd_timeout lsdvd $dev >> "$logfile" 2>&1
543
544   if [ $? != 0 ]; then
545     # lsdvd didn't work. Try VLC.
546     lsdvd_incompatibility=1
547     if [[ -x `which cvlc` ]]; then 
548       echo "-> lsdvd failed to DeCSS the DVD. Trying VLC: $dev" | tee -a "$logfile"
549       alarm $lsdvd_timeout cvlc --no-video --no-audio $dev  >> "$logfile" 2>&1
550       # Once you get a DVD that VLC can't handle, figure out how 
551       # to detect that here and abort.
552       #if [ $? != 1 ]; then
553       #  echo "-> VLC failed to decss the DVD."
554       #  return 1
555       #fi
556     else
557       fatal_and_exit "-E- lsdvd failed to DeCSS the DVD. VLC not found, but required to rip this DVD."
558     fi
559   fi
560   return 0
561 }
562
563 # reduce the size of the mkv src file using handbrake
564 function encode_mkv_file_makemkv {
565     src="$1"
566     dst="$2"
567     tmpdst=""
568
569     # Convert our ISO to a MKV if it is a real iso
570     if [[ $real_isofile -eq 1 ]]; then
571         tmpdst="$tmpdir/$dvdname.mkv"
572         make_dvd_mkv_image "$tmpdst" "iso" "$src"
573         src="$tmpdst"
574     fi
575
576     # Set a variable that we will use later to determine if we found a handler for $profile or not
577     typeset -i found_profile=0 
578   
579     # Globals
580     typeset quality=""
581     typeset handbrake_audio_opts=""
582     typeset handbrake_cli=""
583
584     # Predefined Handbrake Profile Handling
585     if [[ "$profile" =~ "mkvvhq" ]]; then
586         found_profile=1
587         handbrake_cli="$handbrake_mp4"
588         final_output_file="$dst"
589         quality="0.9"
590     fi
591     if [[ "$profile" =~ "mkvhq" ]]; then
592         found_profile=1
593         handbrake_cli="$handbrake_mp4"
594         final_output_file="$dst"
595         quality="0.85"
596     fi
597
598     # setup our audio option
599     if [ $audio_2ch -eq 1 ] && [ $audio_6ch -eq 1 ]; then
600         handbrake_audio_opts="-E faac,ac3 -6 dpl2,auto"
601     fi
602     if [ $audio_6ch -eq 1 ] && [ $audio_2ch -eq 0 ]; then
603         handbrake_audio_opts="-E ac3 -6 auto"
604     fi
605     if [ $audio_2ch -eq 1 ] && [ $audio_6ch -eq 0 ]; then
606         handbrake_audio_opts="-E faac -6 dpl2"
607     fi
608
609     # find out what our audio track is
610     get_audio_track_from_mkv "$src" "$handbrake_cli"
611     if [ -n "$track" ]; then
612         handbrake_audio_opts="$handbrake_audio_opts -a $track"
613         track="" 
614     fi
615     
616     # Execute the handbrake command to encode the video
617     echo -e "\n   Encoding: $handbrake_cli -i \"$src\" -o \"$dst\" --strict-anamorphic --crop 0:0:0:0 -q $quality $handbrake_audio_opts -v 1 -m"
618     $handbrake_cli -i "$src" -o "$dst" --strict-anamorphic --crop 0:0:0:0 -q $quality $handbrake_audio_opts -v 1 | tee -a $encodelog 2>&1
619     handbrake_retval=$?
620
621     if [ $handbrake_retval != 0 ]; then
622         fatal_and_exit "-E- Unhandled handbrake error"
623     fi
624
625     # Extract the chapters from the src and apply to the dst
626     chapter_tmpfile="$tmpdir/$dvdname.xml"
627     $mkvextract chapters "$src" > "$chapter_tmpfile"
628     $mkvpropedit -c "$chapter_tmpfile" "$dst"
629
630     # find out what our default_alang subtitle track is in the src
631     get_subtitle_track_from_mkv "$src" "$handbrake_cli"
632
633     # Extract the subtitles from the src and apply to the dst
634     srt_tmpfile="$tmpdir/$dvdname.srt"
635     sub_tmpfile="$tmpdir/$dvdname.sub"
636     idx_tmpfile="$tmpdir/$dvdname.idx"
637     $mkvextract tracks "$src" $track:$srt_tmpfile
638     $mkvmerge -o "$dst.subs" "$dst" $idx_tmpfile
639     mv "$dst.subs" "$dst"
640
641     # Set the default subtitle track to "no subtitles" in the dst
642     $mkvpropedit "$dst" --edit track:s1 --set flag-default=0
643
644     # Concatenate the encode log to our main log file, greping out unwanted lines
645     cat $encodelog | grep -v "Encoding:" | grep -v "hb_demux_ps" >> "$logfile" 
646     cat $encodelog | grep "Encoding:" | sed 's/\r/\n/g' | grep "Encoding:" | grep "ETA" | head -1 >> "$logfile"
647     cat $encodelog | grep "Encoding:" | sed 's/\r/\n/g' | grep "Encoding:" | grep "ETA" | tail -1 >> "$logfile"  
648
649     # Remove intermediary file if we created one   
650     if [ $keep_intermediate_files -eq 0 ]; then
651         [[ -e "$tmpdst" ]] && rm -f "$tmpdst"
652         rm "$chapter_tmpfile"
653         rm "$idx_tmpfile" "$sub_tmpfile"
654     else
655         echo "-> Keeping intermediate chapter file: $chapter_tmpfile" | tee -a "$logfile"
656         echo "-> Keeping intermediate subtitle files: $idx_tmpfile $sub_tmpfile" | tee -a "$logfile"
657         [[ -e "$tmpdst" ]] && echo "-> Keeping intermediate MKV file: $tmpdst" | tee -a "$logfile"
658     fi
659 }
660
661 # encode the vob file into a compressed file format using handbrake
662 function encode_vob_file_handbrake {
663   
664   # declare some globals
665   typeset handbrake_cli=""
666   typeset handbrake_video_encoder_opts=""
667   typeset filetype=""
668   typeset handbrake_audio_opts=""
669   typeset hb_profile=""
670   typeset SIZE=""
671   typeset AUDIO_BITRATE=""
672
673   # Set a variable that we will use later to determine if we found a handler for $profile or not
674   typeset -i found_profile=0    
675
676   # For a given profile, to override the 2 pass behavior to be single pass,
677   # simply set the PASSES variable below to "2" instead of "1 2" inside your profile handler. 
678   # It indicates which PASS numbers to loop over. PASSES="2" means just do pass 2 => single pass mode.
679   PASSES="-2"
680
681   # Set our DRC option
682   DRC="-D $drc"
683
684   if [ $target_size -ne 0 ]; then
685     SIZE="-S $target_size"
686   fi 
687
688   if [ $custom_audio_bitrate -eq 1 ]; then
689     AUDIO_BITRATE="-B $target_audio_bitrate"
690   fi
691
692   if [ $force_onepass_mode -eq 1 ]; then
693     PASSES=""
694   fi
695
696   # get our audio track from the VOB file (requires mp4 version of handbrake to extract)
697   get_audio_track_from_vob "$vobfile" "$handbrake_mp4"
698
699   # XVID profile
700   if [[ "$profile" =~ "xvid" ]]; then
701     found_profile=1
702     handbrake_cli="$handbrake_xvid"
703     final_output_file="$dest/$dvdname.avi"
704     filetype="avi"
705
706     # Very High Quality (16fps)
707     if [ "$profile" == "xvidvhq" ]; then
708       handbrake_opts[0]="-f avi"
709       handbrake_opts[1]="-b $target_video_bitrate"
710       handbrake_opts[2]="-e xvid"
711       handbrake_opts[3]="-T"
712       handbrake_opts[4]="-5"
713       handbrake_opts[5]="-8"
714     fi
715     # High Quality (20fps)
716     if [ "$profile" == "xvidhq" ]; then
717       handbrake_opts[0]="-f avi"
718       handbrake_opts[1]="-b $target_video_bitrate"
719       handbrake_opts[2]="-e ffmpeg"
720       handbrake_opts[3]="-T"
721       handbrake_opts[4]="-5"
722     fi
723     # Fast (28fps)
724     if [ "$profile" == "xvid" ]; then
725       handbrake_opts[0]="-f avi"
726       handbrake_opts[1]="-b $target_video_bitrate"
727       handbrake_opts[2]="-e ffmpeg"
728       handbrake_opts[3]="-T"
729     fi
730   fi
731
732   # MP4 profile
733   if [[ "$profile" =~ "mp4" ]]; then
734     found_profile=1
735     handbrake_cli="$handbrake_mp4"
736     final_output_file="$dest/$dvdname.mp4"
737     PASSES=""
738
739     # Handle custom parameter overrides
740     if [ $custom_video_bitrate == 1 ]; then
741       handbrake_opts[0]="-b $target_video_bitrate"
742     fi
743     if [ $custom_audio_2ch == 0 ]; then
744       audio_2ch=0
745     fi
746     if [ $custom_audio_6ch == 0 ]; then
747       audio_6ch=0
748     fi
749
750     # Very High Quality
751     if [ "$profile" == "mp4vhq" ]; then
752       profile="hb_High_Profile"
753     fi
754     # High Quality
755     if [ "$profile" == "mp4hq" ]; then
756       profile="hb_Normal"
757     fi
758     # Fast
759     if [ "$profile" == "mp4" ]; then
760       profile="hb_Classic"
761     fi
762   fi
763
764   # iphone and ipod MP4 profiles
765   if [ "$profile" == "iphone" ] || [ "$profile" == "ipod" ]; then
766     found_profile=1
767     handbrake_cli="$handbrake_mp4"
768     final_output_file="$dest/$dvdname.mp4"
769     PASSES=""
770
771     # Handle custom parameter overrides
772     if [ $custom_video_bitrate == 1 ]; then
773       handbrake_opts[0]="-b $target_video_bitrate"
774     fi
775     if [ $custom_audio_2ch == 0 ]; then
776       audio_2ch=0
777     fi
778     if [ $custom_audio_6ch == 0 ]; then
779       audio_6ch=0
780     fi
781
782     # iphone
783     if [ "$profile" == "iphone" ]; then
784       profile="hb_iPhone_&_iPod_Touch"
785     fi
786     # ipod
787     if [ "$profile" == "ipod" ]; then
788       profile="hb_iPod"
789     fi
790
791   fi
792   
793   # Predefined Handbrake Profile Handling
794   if [[ "$profile" =~ "hb" ]]; then
795     found_profile=1
796     handbrake_cli="$handbrake_mp4"
797     final_output_file="$dest/$dvdname.mp4"
798     PASSES=""
799
800     # Handle custom parameter overrides
801     if [ $custom_video_bitrate == 1 ]; then
802       handbrake_opts[0]="-b $target_video_bitrate"
803     fi
804     if [ $custom_audio_2ch == 0 ]; then
805       audio_2ch=0
806     fi
807     if [ $custom_audio_6ch == 0 ]; then
808       audio_6ch=0
809     fi
810     
811     # extract the HandBrake Profile name from $profile
812     hb_profile=`echo "$profile" | sed 's/hb_//g' | sed 's/_/ /g'`
813   fi
814
815   # Make sure we found a handler for the given profile
816   if [ $found_profile -eq 0 ]; then
817     fatal_and_exit "-E- Unable to find a profile handler for profile: $profile"
818   fi
819
820   # setup our audio option
821   if [ $audio_2ch -eq 1 ] && [ $audio_6ch -eq 1 ]; then
822     handbrake_audio_opts="-E faac,ac3 -6 dpl2,auto"
823   fi
824   if [ $audio_6ch -eq 1 ] && [ $audio_2ch -eq 0 ]; then
825     handbrake_audio_opts="-E ac3 -6 auto"
826   fi
827   if [ $audio_2ch -eq 1 ] && [ $audio_6ch -eq 0 ]; then
828     handbrake_audio_opts="-E faac -6 dpl2"
829   fi
830   if [ -n "$track" ]; then
831     handbrake_audio_opts="$handbrake_audio_opts -a $track"
832   fi
833
834   # Convert our array of opts into a string
835   for OPTS in "${video_encoder_opts[@]}"; do 
836     handbrake_video_encoder_opts="$handbrake_video_encoder_opts:$OPTS"
837   done
838   if [ -n "$handbrake_video_encoder_opts" ]; then
839     handbrake_video_encoder_opts="-x $handbrake_video_encoder_opts"
840   fi
841   for OPTS in "${handbrake_opts[@]}"; do 
842     handbrake_cmd_line_opts="$handbrake_cmd_line_opts $OPTS"
843   done
844
845   # Append "global" command line options
846   handbrake_cmd_line_opts="$handbrake_cmd_line_opts -v 1 -m"
847   handbrake_cmd_line_opts="$handbrake_cmd_line_opts $PASSES"
848   handbrake_cmd_line_opts="$handbrake_cmd_line_opts $DRC"
849   handbrake_cmd_line_opts="$handbrake_cmd_line_opts $SCALE"
850   handbrake_cmd_line_opts="$handbrake_cmd_line_opts $SIZE"
851   handbrake_cmd_line_opts="$handbrake_cmd_line_opts $AUDIO_BITRATE"
852
853   # Execute the handbrake command to encode the video
854   # I have to copy-n-paste the code below to handle the 2 conditions, 1) hb_profile (mp4) 2) no hb_profile (xvid)
855   # The problem is the -Z "$hb_profile" option. I have to quote the "$hb_profile" due to spaces in it, forcing me to call it out explicity.
856   if [ -n "$hb_profile" ]; then
857     echo -e "\n   Encoding: $handbrake_cli -i \"$vobfile\" -o \"$final_output_file\" -Z \"$hb_profile\" $handbrake_cmd_line_opts $handbrake_audio_opts $handbrake_video_encoder_opts >> $encodelog 2>&1" >> "$logfile"
858     $handbrake_cli -i "$vobfile" -o "$final_output_file" -Z "$hb_profile" $handbrake_cmd_line_opts $handbrake_audio_opts $handbrake_video_encoder_opts >> $encodelog 2>&1
859     handbrake_retval=$?
860   else 
861     echo -e "\n   Encoding: $handbrake_cli -i \"$vobfile\" -o \"$final_output_file\" $handbrake_cmd_line_opts $handbrake_audio_opts $handbrake_video_encoder_opts >> $encodelog 2>&1" >> "$logfile"
862     $handbrake_cli -i "$vobfile" -o "$final_output_file" $handbrake_cmd_line_opts $handbrake_audio_opts $handbrake_video_encoder_opts >> $encodelog 2>&1
863     handbrake_retval=$?
864   fi
865   if [ $handbrake_retval != 0 ]; then
866     fatal_and_exit "-E- Unhandled handbrake error"
867   fi
868
869   # Extract the chapters from the ISO/VOB so we can add them to the MP4 file. We can only do this if we have an ISO file and we made an MP4 file.
870   chapter_tmpfile="$tmpdir/$dvdname.chapters"
871   if [[ "$final_output_file" =~ "mp4" ]] && [[ -e "$isofile" ]]; then
872     $dvdxchap -t $feature_title "$isofile" > "$chapter_tmpfile"
873     $mp4box -chap "$chapter_tmpfile" "$final_output_file"
874   fi
875
876   # We could also add subtitles, but we would need to follow this guide to do it:
877   # http://ubuntuforums.org/showthread.php?t=1253635
878   # http://en.gentoo-wiki.com/wiki/Ripping_DVD_to_Matroska_and_H.264
879
880   # Remove intermediary file if we created one   
881   if [ $keep_intermediate_files -eq 0 ]; then
882       rm "$chapter_tmpfile"
883   else
884       echo "-> Keeping intermediate chapter file: $chapter_tmpfile" | tee -a "$logfile"
885   fi
886
887   # Concatenate the encode log to our main log file, greping out unwanted lines
888   cat $encodelog | grep -v "Encoding:" | grep -v "hb_demux_ps" >> "$logfile" 
889   cat $encodelog | grep "Encoding:" | sed 's/\r/\n/g' | grep "Encoding:" | grep "ETA" | head -1 >> "$logfile"
890   cat $encodelog | grep "Encoding:" | sed 's/\r/\n/g' | grep "Encoding:" | grep "ETA" | tail -1 >> "$logfile"
891 }
892
893 # encode the vob file into a compressed file format using mencoder
894 function encode_vob_file_mencoder {
895
896   # Set a variable that we will use later to determine if we found a handler for $profile or not
897   typeset -i found_profile=0
898
899   # For a given profile, to override the 2 pass behavior to be single pass,
900   # simply set the PASSES variable below to "2" instead of "1 2" inside your profile handler. 
901   # It indicates which PASS numbers to loop over. PASSES="2" means just do pass 2 => single pass mode.
902   PASSES="1 2"
903
904   # Declare our default 2 pass variables
905   passlogfile_opt="-passlogfile $passlogfile"
906   pass_opt="pass=%PASS"
907
908   # Check the global force_onepass_mode. If it is set, change our variables appropriately
909   # to force 1-pass encoding across all profiles.
910   if [ $force_onepass_mode -eq 1 ]; then
911     PASSES="2"
912     passlogfile_opt=""
913     pass_opt=""    
914   fi
915
916   # XVID profile
917   if [[ "$profile" =~ "xvid" ]]; then
918     found_profile=1
919     final_output_file="$dest/$dvdname.avi"
920     mencoder_general_opts="$lang_opts $passlogfile_opt"
921     mencoder_output_opts="-ofps 30000/1001 -ffourcc DIVX"
922     mencoder_video_filter_opts="-vf pullup,softskip,hqdn3d=2:1:2$CROP$SCALE"
923     mencoder_video_encoder_opts="-ovc xvid -xvidencopts $pass_opt"
924
925     # Very High Quality (16fps)
926     if [ "$profile" == "xvidvhq" ]; then
927       video_encoder_opts[0]="bitrate=$target_video_bitrate"
928       video_encoder_opts[1]="threads=$mencoder_threads"
929       video_encoder_opts[2]="chroma_opt"
930       video_encoder_opts[3]="vhq=4"
931       video_encoder_opts[4]="bvhq=1"
932       video_encoder_opts[5]="quant_type=mpeg"
933       video_encoder_opts[6]="autoaspect"
934     fi
935     # High Quality (20fps)
936     if [ "$profile" == "xvidhq" ]; then
937       video_encoder_opts[0]="bitrate=$target_video_bitrate"
938       video_encoder_opts[1]="threads=$mencoder_threads"
939       video_encoder_opts[2]="chroma_opt"
940       video_encoder_opts[3]="vhq=2"
941       video_encoder_opts[4]="bvhq=1"
942       video_encoder_opts[5]="quant_type=mpeg"
943       video_encoder_opts[6]="autoaspect"
944     fi
945     # Fast (28fps)
946     if [ "$profile" == "xvid" ]; then
947       video_encoder_opts[0]="bitrate=$target_video_bitrate"
948       video_encoder_opts[1]="threads=$mencoder_threads"
949       video_encoder_opts[2]="vhq=0"
950       video_encoder_opts[3]="turbo"
951       video_encoder_opts[4]="autoaspect"
952     fi
953
954     for OPTS in "${video_encoder_opts[@]}"; do 
955       mencoder_video_encoder_opts="$mencoder_video_encoder_opts:$OPTS"
956     done
957
958     if [ $audio_2ch -eq 0 ]; then
959       # These options produce good 6 channel audio for linux and windows
960       mencoder_audio_opts="-oac copy"
961       # There are 3 different ways to specify 6 channel encoding. We'll try the other ones in order if one of them fails.
962       mencoder_audioch_opts[0]="-channels 6 -af channels=6"
963       mencoder_audioch_opts[1]="-af channels=6"
964       mencoder_audioch_opts[2]=""
965     else
966       # These options produce good 2 channel audio for linux and windows (including the internal mythvideo player)
967       mencoder_audio_opts="-oac mp3lame -lameopts cbr:br=$target_audio_bitrate"
968       mencoder_audioch_opts[0]=""
969     fi
970  
971   fi
972
973   # iphone and ipod MP4 profiles
974   if [ "$profile" == "iphone" ] || [ "$profile" == "ipod" ]; then
975     found_profile=1
976     if [ "$profile" == "iphone" ]; then
977       # SCALE: 480x320
978       # scale width to 480, set height appropriately, but keep a multiple of 16
979       #SCALE=",scale=480:-10"
980       # scale the video down however far is necessary to fit in 480x320
981       SCALE=",dsize=480:320:0,scale=-8:-8"
982     else
983       # SCALE: 320x240
984       # scale width to 320, set height appropriately, but keep a multiple of 16
985       #SCALE=",scale=320:-10"
986       # scale the video down however far is necessary to fit in 320x240
987       SCALE=",dsize=320:240:0,scale=-8:-8"
988     fi
989     final_output_file="$dest/$dvdname.mp4"
990     mencoder_general_opts="$lang_opts $passlogfile_opt"
991     mencoder_output_opts="-ofps 30000/1001 -sws 9 -of lavf -lavfopts format=mp4"
992     mencoder_video_filter_opts="-vf harddup$CROP$SCALE";
993     mencoder_video_encoder_opts="-ovc x264 -x264encopts $pass_opt"
994     video_encoder_opts[0]="bitrate=$target_video_bitrate"
995     video_encoder_opts[1]="threads=$mencoder_threads"
996     video_encoder_opts[2]="vbv_maxrate=1500"
997     video_encoder_opts[3]="vbv_bufsize=2000"
998     video_encoder_opts[4]="nocabac"
999     video_encoder_opts[5]="me=umh"
1000     video_encoder_opts[6]="subq=6"
1001     video_encoder_opts[7]="frameref=6"
1002     video_encoder_opts[8]="trellis=1"
1003     video_encoder_opts[9]="level_idc=30"
1004     video_encoder_opts[10]="global_header"
1005     video_encoder_opts[11]="bframes=0"
1006     video_encoder_opts[12]="partitions=all"
1007     for OPTS in "${video_encoder_opts[@]}"; do 
1008       mencoder_video_encoder_opts="$mencoder_video_encoder_opts:$OPTS"
1009     done
1010
1011     mencoder_audio_opts="-oac faac -faacopts mpeg=4:object=2:br=$target_audio_bitrate:raw"
1012     mencoder_audioch_opts[0]="-channels 2 -srate 48000"
1013   fi
1014
1015   if [ $found_profile -eq 0 ]; then
1016     fatal_and_exit "-E- Unable to find a profile handler for profile: $profile"
1017   fi
1018
1019   # Do not edit this line. $mencoder_video_encoder_opts must be last
1020   mencoder_opts="$mencoder_general_opts $mencoder_output_opts $mencoder_audio_opts $mencoder_video_filter_opts $mencoder_video_encoder_opts"
1021   mencoder_retval=0
1022
1023   for PASS in $PASSES
1024   do 
1025     # Set some options based on which pass we are in
1026     mencoder_opts_for_pass=$(echo "$mencoder_opts" | sed "s,%PASS,$PASS,g")
1027     [ $PASS -eq 1 ] && mencoder_opts_for_pass="$mencoder_opts_for_pass:turbo"
1028     [ $PASS -eq 1 ] && output_file="/dev/null"
1029     [ $PASS -eq 2 ] && output_file="$final_output_file"
1030   
1031     # It's possible that the audio channel encoding may not work. Cycle through all our different audioch_opts until we find one that works.
1032     for CH_OPTS in "${mencoder_audioch_opts[@]}"; 
1033     do
1034       echo -e "   Encoding pass $PASS"
1035       echo -e "\n   Encoding pass $PASS: mencoder $CH_OPTS $mencoder_opts_for_pass \"$vobfile\" -o \"$output_file\" >> $encodelog 2>&1" >> "$logfile"
1036       mencoder $CH_OPTS $mencoder_opts_for_pass "$vobfile" -o "$output_file" > $encodelog 2>&1
1037       mencoder_retval=$? 
1038       grep -q "\[channels\] Invalid" $encodelog
1039       if [ $? != 0 ]; then          
1040         break;
1041       else
1042         echo -e "\n-W- Audio channel encoding error. Falling back to next audio channel encoding scheme." >> "$logfile"
1043       fi
1044     done
1045       
1046     if [ $mencoder_retval != 0 ]; then
1047       fatal_and_exit "-E- Unhandled mencoder error"
1048     fi
1049
1050     # Concatenate the encode log to our main log file, greping out unwanted lines
1051     cat $encodelog | grep -v "^Pos:" | grep -v "duplicate" >> "$logfile"
1052
1053   done
1054 }
1055
1056 function make_dvd_mkv_image {
1057     dstmkv="$1"
1058     srctype="$2"
1059     srcname="$3"
1060     dstdir=${dstmkv%.[^.]*}
1061     ((min_length = minimum_feature_title_length * 60))
1062
1063     echo -e "\n   Ripping: $makemkv --minlength=$min_length --decrypt --progress=-same $srctype:$srcname all $dstdir"
1064     mkdir -p "$dstdir"
1065     $makemkv mkv --minlength=$min_length --decrypt --progress=-same $srctype:$srcname all $dstdir
1066     makemkv_retval=$?
1067     
1068     if [ $makemkv_retval != 0 ]; then
1069         fatal_and_exit "-E- Unhandled makemkv error"
1070     fi
1071
1072     # Move the created MKV file into place
1073     echo -e "\n   Moving $dstdir/*.mkv -> $dstmkv"
1074     mv "$dstdir"/*.mkv "$dstmkv"
1075     if [ $? != 0 ]; then
1076         fatal_and_exit "-E- Unhandled mv error"
1077     fi
1078     if [ $keep_intermediate_files -eq 0 ]; then
1079         [[ -d "$dstdir" ]] && rm -rf "$dstdir"
1080     fi
1081
1082     # Concatenate the encode log to our main log file, greping out unwanted lines
1083     cat $encodelog | grep -v "Current progress:" >> "$logfile"    
1084 }
1085
1086 function make_dvd_mkv_image_from_folder {
1087     src="$1"
1088     dst="$2"
1089     handle_error=$3
1090     dstdir=${dst%.[^.]*}
1091     make_dvd_mkv_image "$dst" "file" "$src"
1092 }
1093
1094 function make_dvd_iso_image {
1095
1096   isofile="$1"
1097
1098   # check to see if we have a dvdpath to rip from instead of $dev
1099   if [ -z "$dvdpath" ]; then
1100     # load the CSS codes in the DVD drive 
1101     lsdvd_css "$dev"
1102     if [ $? != 0 ]; then
1103       fatal_and_exit "-E- lsdvd $dev failed" 
1104     fi
1105
1106     # read the DVD, ignoring/skipping CRC errors
1107     ddrescue -n -b 2048 $dev "$isofile" "$ddrescuelog"
1108     if [ $? != 0 ]; then
1109       fatal_and_exit "-E- ddrescue -n -b 2048 $dev \"$isofile\" failed"
1110     fi
1111     cat "$ddrescuelog" >> "$logfile"
1112   else
1113     # rip from a path instead
1114     make_dvd_iso_image_from_folder "$dvdpath" "$isofile" 1
1115   fi
1116 }
1117
1118 function make_dvd_iso_image_from_folder {
1119   
1120   src="$1"
1121   dst="$2"
1122   handle_error=$3
1123   
1124   echo "-> Creating ISO image of DVD video: $src -> $dst" | tee -a "$logfile"
1125
1126   # make an iso image out of our directory
1127   echo "   mkisofs -dvd-video \"$src\" 2>> \"$dumplog\" | dd of=\"$dst\" obs=32k seek=0 > /dev/null 2>> $dumplog" >> "$logfile"
1128   mkisofs -dvd-video "$src" 2>> "$dumplog" | dd of="$dst" obs=32k seek=0 > /dev/null 2>> "$dumplog"
1129
1130   # set the audio languages from the iso if it exists and is non-zero in size
1131   if [ -s "$dst" ]; then
1132     get_feature_title "$dst"
1133     get_audio_id_from_iso "$dst"
1134   fi
1135
1136   # make sure we were able to create the iso image from the folder given to us
1137   if [ ! -s "$dst" ] && [ $handle_error -eq 1 ]; then
1138     echo "-> Unable to make an iso image from the DVD folder: $dvdpath"
1139     echo "   Falling back to mplayer to create a main feature VOB from the folder instead: $dvdpath"
1140     # remove the bad iso file
1141     [[ -e "$dst" ]] && rm -f "$dst"
1142     # get the feature title from the DVD folder
1143     get_feature_title "$dvdpath"
1144     # create our main VOB file from the ISO
1145     create_main_vob_with_mplayer "$dvdpath" 
1146     # get our audio id from the VOB file
1147     get_audio_id_from_vob "$vobfile"
1148   fi
1149 }
1150
1151 function make_dvdbackup_folder_image {
1152   # extract the feature title from the DVD image
1153   echo "-> Extracting feature title using dvdbackup" | tee -a "$logfile"
1154   [[ -d "$tmpdir/$dvdname" ]] && rm -rf "$tmpdir/$dvdname"
1155   dvdbackup -F -i "$isofile" -o "$tmpdir" >> "$logfile"
1156   if [ $? != 0 ]; then
1157     fatal_and_exit '-E- dvdbackup -F -i "$isofile" -o "$tmpdir" failed'
1158   fi
1159 }
1160
1161 function make_dvdauthor_folder_image {
1162   # create a new DVD video of the feature title
1163   echo "-> Creating DVD video $dest/$dvdname" | tee -a "$logfile"
1164   [[ -d "$dest/$dvdname" ]] && rm -rf "$dest/$dvdname"
1165   dvdauthor -o "$dest/$dvdname" -x dvd.xml > $dvdauthorlog 2>&1
1166   cat $dvdauthorlog | grep -v "VOBU" >> "$logfile"
1167
1168   # There is a chance that dvdauthor won't like some of the VOBs.
1169   # We can't tell ahead of time which ones it will choke on. 
1170   # So, we need to run it over and over again until it can process
1171   # all the VOBs. If it can't handle one of them, run it through
1172   # mencoder to fix it and try again. These errors are typically
1173   # present due to the copy protection that ddrescue removed.
1174   grep -q "SCR moves" $dvdauthorlog
1175   while [ $? == 0 ]; do
1176     # fix bad vobs that get the "SCR moves backwards" error:
1177     #  STAT: Processing VTS_01_0.VOB...
1178     #  ERR:  SCR moves backwards, remultiplex input.
1179     badvob=`grep -v "^WARN:" $dvdauthorlog | grep -B 1 "SCR moves" | grep "Processing" | awk '{ print $3 }' | sed -e 's/\.\.\.//'`
1180     if [[ ! -f "$badvob" ]]; then
1181       fatal_and_exit "-E- Found a bad VOB, but could not extract it's name properly: $badvob"
1182     fi
1183     echo "-> Fixing SCR errors in DVD video file $badvob" | tee -a "$logfile"
1184     cat $badvob | mencoder $lang_opts -quiet -of mpeg -mpegopts format=dvd -oac copy -ovc copy - -o $badvob.fixed >> "$logfile" 2>&1
1185     mv -f $badvob.fixed $badvob
1186     echo "-> Creating DVD video $dest/$dvdname"
1187     dvdauthor -o "$dest/$dvdname" -x dvd.xml > $dvdauthorlog 2>&1
1188     cat $dvdauthorlog | grep -v "VOBU" >> "$logfile"
1189     grep -q "SCR moves" $dvdauthorlog
1190   done
1191 }
1192
1193 function get_feature_title {
1194   source="$1"
1195   # if a feature title was given on the command line, use it
1196   if [ $feature_title_override -ne 0 ]; then
1197     feature_title=$feature_title_override
1198     return 0
1199   fi
1200   # otherwise, use lsdvd to figure it out
1201   if [ $ripdvd -eq 1 ]; then
1202     lsdvd_longest_title "$dev" 
1203   else 
1204     lsdvd_longest_title "$source"
1205   fi
1206 }
1207
1208 function create_main_vob_with_cat {
1209   # cd to the feature title DVD folder
1210   pushd "$tmpdir/$dvdname/VIDEO_TS" > /dev/null 2>&1
1211   if [ $? != 0 ]; then
1212     fatal_and_exit "-E- Unable to cd to $tmpdir/$dvdname/VIDEO_TS"
1213   fi
1214
1215   # concatenate all the VOBs together into 1 giant VOB
1216   vobs=`/bin/ls -1 VTS*.VOB | grep -v "0.VOB" | tr '\n' ' '`
1217   cat $vobs > "$tmpdir/$dvdname.VOB"
1218
1219   # cd back to the dir we started from
1220   popd > /dev/null 2>&1
1221 }
1222
1223 function create_main_vob_with_mplayer {
1224
1225   # argument processing  
1226   source="$1"
1227   remove_dumplog=$2
1228
1229   # make sure we have a valid feature title
1230   if [ $invalid_feature_title -eq 1 ] && [ $feature_title_override -eq 0 ]; then
1231     fatal_and_exit "-E- You must have a valid feature title to get the VOB via mplayer dumpstream. We can't determine the feature title for this DVD."
1232   fi
1233
1234   # check to make sure we didn't detect an mplayer dumpstream incompatibility earlier
1235   if [ $mplayer_dumpstream_incompatibility -eq 1 ]; then
1236     msg="-E- We detected an mplayer dumpstream incompatibility earlier."
1237     msg="$msg We also detected a condition that may require you to use dumpstream. "
1238     msg="$msg\n    Unable to rip this DVD in the mode you requested."
1239     fatal_and_exit "$msg"
1240   fi
1241
1242   # use mplayer to create the main VOB file
1243   echo "-> Using mplayer to dump the DVD feature title $feature_title to a VOB file directly: $vobfile" | tee -a "$logfile"
1244   echo "   mplayer $lang_opts -dumpstream -dumpfile \"$vobfile\" -dvd-device \"$source\" dvd://$feature_title > $dumplog 2>&1" >> "$logfile"
1245   mplayer $lang_opts -dumpstream -dumpfile "$vobfile" -dvd-device "$source" dvd://$feature_title > $dumplog 2>&1
1246   if [ $? != 0 ]; then
1247     cat $dumplog | grep -v "^A:" >> "$logfile"
1248     fatal_and_exit "-E- Mplayer Failed"
1249   fi
1250   cat $dumplog | grep -v "^A:" >> "$logfile"
1251   [[ -e "$dumplog" ]] && [[ $remove_dumplog -eq 1 ]] && rm -f $dumplog
1252 }
1253
1254 function get_audio_id_from_iso {
1255   # Adjust our audio ID to find the english audio stream
1256   # This should be 128. However, if 128 is not there, pick the next one that incrementally is.
1257   iso="$1"
1258   aidcheck=`tempfile`
1259   aid=$default_aid
1260   alang=$default_alang
1261   if [ $aid_override -lt 0 ]; then 
1262     mplayer -v -endpos 0 -dvd-device "$iso" dvd://$feature_title > $aidcheck 2>&1
1263     grep -q "aid: $aid" $aidcheck
1264     while [ $? == 1 ] && [ $aid -lt 159 ]; do
1265       (( aid = aid + 1 ))
1266       grep -q "aid: $aid" $aidcheck
1267     done
1268     [[ -e "$aidcheck" ]] && rm -f "$aidcheck"
1269   else
1270     aid=$aid_override
1271   fi
1272   echo "-> Setting the audio stream ID to $aid" | tee -a "$logfile"
1273   # mencoder default DVD audio track language selection (english)
1274   lang_opts="-aid $aid -alang $alang"
1275 }
1276
1277 function get_crop_from_iso { 
1278   FRAMES=10000
1279   echo "-> Detecting black frame border crop value from ISO file"
1280   echo "   mplayer -vf cropdetect -frames $FRAMES -nosound -vo md5sum -benchmark -dvd-device \"$isofile\" dvd://$feature_title > $dumplog 2>&1" >> "$logfile"
1281   mplayer -vf cropdetect -frames $FRAMES -nosound -vo md5sum -benchmark -dvd-device "$isofile" dvd://$feature_title > $dumplog 2>&1
1282   [[ -e "md5sums" ]] && rm -f "md5sums"
1283   CROP=`cat $dumplog | grep CROP | tail -1`
1284   echo "   Found crop value of $CROP" >> "$logfile"
1285   CROP=${CROP#* crop=}
1286   CROP=${CROP%%\).*}
1287   typeset -i CROPCHECK
1288   CROPCHECK=`echo "$CROP" | awk -F ':' '{ print $1 }'`
1289   echo "   Final crop value of $CROP with cropcheck value of $CROPCHECK" >> "$logfile"
1290   if [ -z "$CROP" ]; then
1291     echo "-W- Unable to extract CROP value from iso: $isofile" | tee -a "$logfile"
1292     return
1293   fi
1294   if [ $CROPCHECK -lt 0 ]; then 
1295     CROP=""
1296   else 
1297     CROP=",crop=$CROP"
1298   fi
1299   echo "   Setting mencoder crop filter to: $CROP"
1300 }
1301
1302 function get_crop_from_vob { 
1303   FRAMES=10000
1304   echo "-> Detecting black frame border crop value from VOB file"
1305   echo "   mplayer -vf cropdetect -frames $FRAMES -nosound -vo md5sum -benchmark \"$vobfile\" > $dumplog 2>&1" >> "$logfile"
1306   mplayer -vf cropdetect -frames $FRAMES -nosound -vo md5sum -benchmark "$vobfile" > $dumplog 2>&1
1307   [[ -e "md5sums" ]] && rm -f "md5sums"
1308   CROP=`cat $dumplog | grep CROP | tail -1`
1309   echo "   Found crop value of $CROP" >> "$logfile"
1310   CROP=${CROP#* crop=}
1311   CROP=${CROP%%\).*}
1312   typeset -i CROPCHECK
1313   CROPCHECK=`echo "$CROP" | awk -F ':' '{ print $1 }'`
1314   echo "   Final crop value of $CROP with cropcheck value of $CROPCHECK" >> "$logfile"
1315   if [ -z "$CROP" ]; then
1316     echo "-W- Unable to extract CROP value from iso: $isofile" | tee -a "$logfile"
1317     return
1318   fi
1319   if [ $CROPCHECK -lt 0 ]; then 
1320     CROP=""
1321   else 
1322     CROP=",crop=$CROP"
1323   fi
1324   echo "   Setting mencoder crop filter to: $CROP"
1325 }
1326
1327 function get_audio_track_from_mkv { 
1328   mkv="$1"
1329   handbrake_cli="$2"
1330   aidcheck=`tempfile`
1331   alang=$default_alang
1332
1333   # Find out what audio track matches our alang
1334   $handbrake_cli --stop-at duration:1 -i "$mkv" -o /dev/null -v 100 > $aidcheck 2>&1
1335   stream=`grep "$alang" $aidcheck | grep "Audio:"`
1336
1337   # extract the track number that handbrake uses
1338   track=`echo "$stream" | awk '{ print $2; }' | awk -F '.' '{ print $2; }' | awk -F '(' '{ print $1; }'`
1339   
1340   if [ -n "$track" ]; then   
1341       echo "   Setting the audio track to $track." | tee -a "$logfile"
1342   fi
1343 }
1344
1345 function get_subtitle_track_from_mkv { 
1346   mkv="$1"
1347   handbrake_cli="$2"
1348   aidcheck=`tempfile`
1349   alang=$default_alang
1350
1351   # Find out what audio track matches our alang
1352   $handbrake_cli --stop-at duration:1 -i "$mkv" -o /dev/null -v 100 > $aidcheck 2>&1
1353   stream=`grep "$alang" $aidcheck | grep "Subtitle:" | head -n 1`
1354
1355   # extract the track number that handbrake uses
1356   track=`echo "$stream" | awk '{ print $2; }' | awk -F '.' '{ print $2; }' | awk -F '(' '{ print $1; }'`
1357
1358   # add 1 to the track number since mkv tools start at 1, and HandBrake starts at 0
1359   ((track = track + 1))
1360
1361   if [ -n "$track" ]; then   
1362       echo "   Setting the subtitle track to $track." | tee -a "$logfile"
1363   fi
1364 }
1365
1366 function get_audio_track_from_vob {
1367   # Adjust our audio ID to find the english audio stream
1368   # This should be 128. However, if 128 is not there, pick the next one that incrementally is.
1369   vob="$1"
1370   handbrake_cli="$2"
1371   aidcheck=`tempfile`
1372   aid=$default_aid
1373   alang=$default_alang
1374   if [ $aid_override -lt 0 ]; then 
1375     mplayer -v -endpos 0 "$vob" > $aidcheck 2>&1
1376     grep -q "Found audio stream: $aid" $aidcheck
1377     while [ $? == 1 ] && [ $aid -lt 159 ]; do
1378       (( aid = aid + 1 ))
1379       grep -q "Found audio stream: $aid" $aidcheck
1380     done
1381     [[ -e "$aidcheck" ]] && rm -f "$aidcheck"
1382   else 
1383     aid=$aid_override
1384   fi
1385   # Now that we've found the right audio id, find the corresponding audio track in HandBrake
1386
1387   # convert the aid we found into hex
1388   aid_hex=`echo "obase=16; $aid" | bc`
1389   
1390   # extract the audio streams in the vob
1391   #ffmpeg -i "$vob" > $aidcheck 2>&1
1392   $handbrake_cli --stop-at duration:1 -i "$vob" -o /dev/null -v 100 > $aidcheck 2>&1
1393   
1394   # find the stream that matches our aid
1395   #stream=`grep "Stream.*\[0x$aid_hex\]" $aidcheck`
1396   #stream=`grep "scan: audio" $aidcheck | grep -n "" | grep "scan: audio 0x$aid_hex"`
1397   stream=`grep "add_audio_to_title:" $aidcheck | grep -n "" | grep "add_audio_to_title:.* stream 0x$aid_hex"`
1398  
1399   # extract the track number that handbrake uses
1400   #track=`expr match "$stream" '.*#[0-9]\.\([0-9]*\)'`
1401   track=`expr match "$stream" '^\([0-9]*\):'`
1402
1403   if [ -n "$track" ]; then   
1404     echo "   Setting the audio ID to $aid. Setting the audio track to $track." | tee -a "$logfile"
1405   fi
1406 }
1407
1408 function get_audio_id_from_vob {
1409   # Adjust our audio ID to find the english audio stream
1410   # This should be 128. However, if 128 is not there, pick the next one that incrementally is.
1411   vob="$1"
1412   aidcheck=`tempfile`
1413   aid=$default_aid
1414   alang=$default_alang
1415   if [ $aid_override -lt 0 ]; then 
1416     mplayer -v -endpos 0 "$vob" > $aidcheck 2>&1
1417     grep -q "Found audio stream: $aid" $aidcheck
1418     while [ $? == 1 ] && [ $aid -lt 159 ]; do
1419       (( aid = aid + 1 ))
1420       grep -q "Found audio stream: $aid" $aidcheck
1421     done
1422     [[ -e "$aidcheck" ]] && rm -f "$aidcheck"
1423   else 
1424     aid=$aid_override
1425   fi
1426   echo "-> Setting the audio stream ID to $aid" | tee -a "$logfile"
1427   # mencoder default DVD audio track language selection (english)
1428   lang_opts="-aid $aid -alang $alang"
1429 }
1430
1431 function check_vob_for_corrupted_start {
1432   # check to see if the beginning of the DVD has a form of copy protection
1433   # where they have deliberately broken the first X number of frames of the DVD.
1434   # If we don't skip these, our resulting VOB file will not play.
1435   badvobcheck=`tempfile`
1436   endpos=360
1437   skip=0
1438   mencoder -ss $skip -endpos $endpos $lang_opts -of mpeg -mpegopts format=dvd:tsaf -oac copy -ovc copy "$tmpdir/$dvdname.VOB" -o /dev/null > $badvobcheck 2>&1
1439   if [ $? != 0 ]; then
1440     fatal_and_exit "-E- Mencoder Failed"
1441   fi
1442   grep "Writing header" -A `wc $badvobcheck | awk '{ print $1 }'` $badvobcheck | grep -q "Too many video packets in the buffer"
1443   while [ $? == 0 ] && [ $skip -lt $endpos ]; do
1444     (( skip = skip + 5 ))
1445     echo "-> Bad VOB copy protection detected. Trying new skip value of $skip" | tee -a "$logfile"
1446     mencoder -ss $skip -endpos $endpos $lang_opts -of mpeg -mpegopts format=dvd:tsaf -oac copy -ovc copy "$tmpdir/$dvdname.VOB" -o /dev/null > $badvobcheck 2>&1
1447     if [ $? != 0 ]; then
1448       fatal_and_exit "-E- Mencoder Failed"
1449     fi
1450     grep "Writing header" -A `wc $badvobcheck | awk '{ print $1 }'` $badvobcheck | grep -q "Too many video packets in the buffer"
1451   done
1452   [[ -e "$badvobcheck" ]] && rm -f "$badvobcheck";
1453
1454   # cat the giant VOB into mencoder to create a playable VOB file
1455   cat "$tmpdir/$dvdname.VOB" | mencoder -ss $skip -quiet $lang_opts -of mpeg -mpegopts format=dvd:tsaf -oac copy -ovc copy - -o "$vobfile" >> "$logfile" 2>&1
1456   if [ $? != 0 ]; then
1457     fatal_and_exit "-E- Mencoder Failed"
1458   fi
1459 }
1460
1461 function check_vob_for_completeness {
1462   # check to make sure we got out a complete VOB.
1463   # there is another kind of copy protection where the VOB's may
1464   # have "MPG EOF" frames in the middle of the stream. 
1465   # this causes mencoder to not process the entire VOB, and exit without any errors.
1466   # detect this by seeing how much smaller the dst vob is from the src vob.
1467   MAX_FILESIZE_DELTA_PERCENT=70
1468   SRC_VOB_FILESIZE=$(stat -c%s "$tmpdir/$dvdname.VOB")
1469   DST_VOB_FILESIZE=$(stat -c%s "$vobfile")
1470   FILESIZE_DELTA=`echo "scale=2; $DST_VOB_FILESIZE / $SRC_VOB_FILESIZE * 100" | bc | awk -F '.' '{ print $1 }'`
1471   if [ $FILESIZE_DELTA -lt $MAX_FILESIZE_DELTA_PERCENT ]; then
1472     # Try one other way to get the VOB using mplayer directly to rip the feature titleset.
1473     echo "-> Detected bad VOB size copy protection after processing concatenated VOB file." | tee -a "$logfile"
1474     create_main_vob_with_mplayer "$isofile"
1475     [[ -e "$dumplog" ]] && rm -f $dumplog
1476     DST_VOB_FILESIZE=$(stat -c%s "$vobfile")
1477     FILESIZE_DELTA=`echo "scale=2; $DST_VOB_FILESIZE / $SRC_VOB_FILESIZE * 100" | bc | awk -F '.' '{ print $1 }'`
1478     if [ $FILESIZE_DELTA -lt $MAX_FILESIZE_DELTA_PERCENT ]; then
1479       fatal_and_exit "-E- This DVD has a copy protection scheme we can't work around. Sorry.\n    I recommend using another ripping mode like '-m' or '-i'"
1480     fi
1481   fi
1482 }
1483
1484 function check_vob_for_too_many_video_packets {
1485   # If our earlier algorithm to work around this failed, throw an error.
1486   # check to see if this DVD has a protection scheme we don't know how to work around
1487   # when I tried to burn the CARS DVD for example, you can't play the resulting VOB file.
1488   # for some reason, the video is black, while the audio rolls, then the video finally comes
1489   # in, but it is WAY off the audio. This appears to be due to some bad frames at the beginning of 
1490   # the 1st VOB. Until I figure out how to work around this, detect it, and error out.
1491   # instead of pulling the image from the disk again, you can pull it directly from the iso: -dvd-device $iso_path
1492   grep -q "Too many video packets in the buffer:" "$logfile"
1493   if [ $? == 0 ]; then
1494     # Try one other way to get the VOB using mplayer directly to rip the feature titleset.
1495     echo "-> Detected corrupt audio stream copy protection after processing concatenated VOB file." | tee -a "$logfile"
1496     create_main_vob_with_mplayer "$isofile"
1497     grep -q "Too many video packets in the buffer:" $dumplog
1498     if [ $? == 0 ]; then
1499       [[ -e "$dumplog" ]] && rm -f $dumplog
1500       fatal_and_exit "-E- This DVD has a copy protection scheme we can't work around. Sorry.\n   I recommend using another ripping mode like '-m' or '-i'"
1501     fi
1502     [[ -e "$dumplog" ]] && rm -f $dumplog
1503   fi
1504 }
1505
1506 function check_vob_for_a52_crc_errors {
1507   # Let's see if we can playback our newly created VOB file without any errors.
1508   # if there are issues, let's detect them now, and try to recreate the VOB
1509   # there are some forms of copy protection that have missed above, that evidence
1510   # themselves when we try to playback the VOB file. This was added to deal with
1511   # the "a52: CRC check failed" copy protection scheme.
1512   MAX_ERRORS=10
1513   ENDPOS=120
1514   echo "-> Checking for a52 audio stream CRC errors" | tee -a "$logfile"
1515   mplayer -endpos $ENDPOS -ao null -vo null "$vobfile" > $dumplog 2>&1
1516   cat $dumplog | grep -v "^A:" >> "$logfile"
1517   errors=`grep "a52: CRC check failed" $dumplog | wc | awk '{ print $1 }'`
1518   if [ $errors -gt $MAX_ERRORS ]; then
1519     echo "-> Detected a52 audio stream CRC errors copy protection after processing concatenated VOB file." | tee -a "$logfile"
1520     create_main_vob_with_mplayer "$isofile"
1521     echo "-> Checking for a52 audio stream CRC errors" | tee -a "$logfile"
1522     mplayer -endpos $ENDPOS -ao null -vo null "$vobfile" > $dumplog 2>&1
1523     if [ $? != 0 ]; then
1524       cat $dumplog | grep -v "^A:" >> "$logfile"
1525       fatal_and_exit "-E- Mplayer Failed"
1526     fi
1527     cat $dumplog | grep -v "^A:" >> "$logfile"
1528     errors=`grep "a52: CRC check failed" $dumplog | wc | awk '{ print $1 }'`
1529     if [ $errors -gt $MAX_ERRORS ]; then
1530       fatal_and_exit "-E- This DVD has a copy protection scheme we can't work around. Sorry.\n   I recommend using another ripping mode like '-m' or '-i'"
1531     fi
1532   fi
1533   [[ -e "$dumplog" ]] && rm -f $dumplog
1534 }
1535
1536 function calculate_bitrate_from_target_size {
1537   # determine what our bitrate needs to be if a target size was specified instead
1538   if [ $target_size -ne 0 ] && [ $custom_video_bitrate -eq 0 ]; then
1539     vob_length=`mplayer -identify -v "$vobfile" -endpos 0 2>&1 | grep ID_LENGTH | awk -F '=' '{ print $2 }' | awk -F '.' '{ print $1 }'`
1540     ((min_length = minimum_feature_title_length * 60))
1541     if [[ $vob_length -gt $min_length ]]; then 
1542       ((target_video_bitrate = (target_size * 1024 * 8) / vob_length ))
1543       custom_video_bitrate=1
1544       echo "   With a given target size of $target_size MB, the estimated bit rate will need to be $target_video_bitrate kbits/sec" | tee -a "$logfile"
1545     else
1546       echo "-W- Unable to determine the real length of this DVD feature title." | tee -a "$logfile"
1547       echo "    A target bitrate from the target_size requested will not be set." | tee -a "$logfile"
1548       echo "    If using handbrake, only the target_size will be passed to the encoder." | tee -a "$logfile" 
1549       echo "    If using mencoder, the target_size will be entirely disregarded." | tee -a "$logfile"
1550       echo "    You may need to rerun with the -b option with a target bitrate to get the desired size." | tee -a "$logfile"
1551       if [[ $encoder -ne "handbrake" ]] || [[ "$profile" =~ "xvid" ]]; then
1552         fatal_and_exit "-E- You'll need rip this DVD with the handbrake or makemkv encoder and an MP4 type profile to get a good rip."
1553       fi
1554     fi
1555   fi
1556 }
1557
1558 function create_dvdauthor_dvd_xml_file {
1559   # make a dvdauthor xml menu file to create a valid DVD video from 
1560   # this script does a good job, but we'll still need to clean it up a bit after it runs
1561   echo "-> Creating dvdauthor XML menu file" | tee -a "$logfile"
1562   makexml -overwrite -dvd *.VOB -out dvd >> "$logfile" 2>&1
1563   if [ $? != 0 ]; then
1564     fatal_and_exit '-E- makexml -dvd *.VOB -out dvd failed'
1565   fi
1566
1567   # replace the first line of the xml file to remove the bad dest path
1568   awk -v line=1 -v new_content="<dvdauthor>" '{
1569     if (NR == line) {
1570       print new_content;
1571     } else {
1572       print $0;
1573     }
1574   }' dvd.xml > dvd.xml.new
1575   mv -f dvd.xml.new dvd.xml
1576   if [ $? != 0 ]; then
1577     fatal_and_exit '-E- mv dvd.xml.new dvd.xml failed'
1578   fi
1579
1580   # remove the "<video " property line from the xml file
1581   cat dvd.xml | grep -v "<video" > dvd.xml.new
1582   mv -f dvd.xml.new dvd.xml
1583   if [ $? != 0 ]; then
1584     fatal_and_exit '-E- mv dvd.xml.new dvd.xml failed'
1585   fi
1586   
1587   # remove the extra <pgc>..</pgc> pairs
1588   cat dvd.xml | awk 'BEGIN {x=1}
1589   {
1590     if ($0~"</pgc>") {x=0}
1591     if (x==1) {print $0}
1592     if ($0~"<pgc>") {x=1}
1593   }' > dvd.xml.new
1594   echo -e "</pgc>\n</titles>\n</titleset>\n</dvdauthor>" >> dvd.xml.new
1595   mv -f dvd.xml.new dvd.xml
1596   if [ $? != 0 ]; then
1597     fatal_and_exit '-E- mv dvd.xml.new dvd.xml failed'
1598   fi
1599
1600   # remove the VTS_*_0.VOB file as this is just the main menu video clip
1601   cat dvd.xml | grep -v "VTS_.*_0.VOB" > dvd.xml.new
1602   mv -f dvd.xml.new dvd.xml
1603   if [ $? != 0 ]; then
1604     fatal_and_exit '-E- mv dvd.xml.new dvd.xml failed'
1605   fi
1606 }
1607
1608 function check_for_mplayer_dumpstream_incompatibility {
1609
1610   echo "-> Checking for mplayer dumpstream incompatibilities" | tee -a "$logfile"
1611
1612   # Check to see if the DVD had any lsdvd incompatibilities
1613   if [ $lsdvd_incompatibility -eq 1 ]; then
1614     invalid_feature_title=1
1615     echo "-E- Unable to determine the feature title due to an lsdvd inability to DeCSS" | tee -a "$logfile"
1616     echo "    You will need to determine this yourself and rerun the script with the -t option" | tee -a "$logfile"
1617     echo "    You can google this DVD to find out what it's feature title is, or you can play it in a conventional DVD player to find it." | tee -a "$logfile"    
1618     return
1619   fi
1620
1621   if [ ! -e "$vobfile" ]; then
1622     # mplayer dumpstream does not work on DVDs that obscure the feature title.
1623     # A DVD that has 99 titles, where the longest title isn't the main feature
1624     # breaks mplayer dumpstream. We have to fallback to using dvdbackup to figure
1625     # out what the feature title is. This script will run through that flow if we
1626     # set use_mplayer_dumpstream to 0. Check for this here.
1627     if [ $ripdvd -eq 1 ]; then
1628       alarm $lsdvd_timeout lsdvd $dev | grep -q "Title: 99"
1629     else
1630       alarm $lsdvd_timeout lsdvd "$isofile" | grep -q "Title: 99"
1631     fi
1632     # If we have 99 titles and a feature title wasn't given on the command line, switch modes.
1633     if [ $? == 0 ] && [ $feature_title_override -eq 0 ]; then
1634       if [ $trust_feature_title_autodetect_when_uncertain -eq 0 ]; then
1635         echo "-E- Unable to determine the feature title due to the 99 title copy protection scheme" | tee -a "$logfile"
1636         echo "    You will need to determine this yourself and rerun the script with the -t option" | tee -a "$logfile"
1637         echo "    You can google this DVD to find out what it's feature title is, or you can play it in a conventional DVD player to find it." | tee -a "$logfile"
1638         invalid_feature_title=1
1639       else 
1640         echo "    Falling back to non mplayer dumpstream methods to copy the DVD" | tee -a "$logfile"
1641         echo "-W- We still may not be able to autodetect the right feature title" | tee -a "$logfile"
1642         echo "    You may need to determine this yourself and rerun the script with the -t option" | tee -a "$logfile"
1643         use_mplayer_dumpstream=0
1644         invalid_feature_title=1
1645       fi
1646       return
1647     fi
1648   fi
1649
1650   # There is another form of protection that causes the mplayer dumpstream to fail. 
1651   # This can be detected by telling mplayer to parse the VOB file by copying its audio
1652   # video streams to a dummy output file (/dev/null). Do that here to check for that 
1653   # problem before continuing.
1654   if [ -e "$vobfile" ]; then
1655     mplayer_opts="-quiet -ofps 30000/1001 -ffourcc DIVX -oac copy -ovc copy"
1656     mencoder $mplayer_opts "$vobfile" -o "/dev/null" > $dumplog 2>&1
1657     grep -q "Too many audio packets in the buffer" $dumplog
1658     if [ $? == 0 ]; then
1659       echo "-> The VOB dumped by mplayer is invalid. Falling back to non mplayer dumpstream to copy the DVD" | tee -a "$logfile"
1660       use_mplayer_dumpstream=0
1661       mplayer_dumpstream_incompatibility=1
1662     fi
1663     [[ -e "$dumplog" ]] && rm -f $dumplog
1664   fi
1665
1666   # There is another form of protection that causes the mplayer dumpstream to fail.
1667   # The resulting VOB file looks complete, but has something in it that causes mplayer/mencoder 
1668   # to be unable to encode it since it thinks the entire VOB is only a few minutes long in length.
1669   # Using HandBrake with an MP4 type profile can work around this, but mencoder or Handbrake with XVID profile won't.
1670   if [ -e "$vobfile" ]; then
1671     vob_length=`mplayer -identify -v "$vobfile" -endpos 0 2>&1 | grep ID_LENGTH | awk -F '=' '{ print $2 }' | awk -F '.' '{ print $1 }'`
1672     ((min_length = minimum_feature_title_length * 60))
1673     if [[ $vob_length -lt $min_length ]]; then 
1674       if [[ $encoder -ne "handbrake" ]] || [[ "$profile" =~ "xvid" ]]; then
1675         echo "-E- The main feature title that was ripped from the DVD has an invalid movie length." | tee -a "$logfile"
1676         echo "    You'll need rip this DVD with the handbrake encoder and an MP4 type or makemkv encoder and an MKV type profile instead." | tee -a "$logfile"
1677         mplayer_dumpstream_incompatibility=1
1678         fatal_and_exit "-E- Aborting encoding step due to invalid movie length."
1679       fi
1680     fi
1681   fi
1682 }
1683
1684 function fill_mythvideo_metadata {
1685
1686   # This function must be passed the filename as an argument
1687   # The filename must be a full path to the file
1688   filename="$1"
1689
1690   # Make sure the fill mythvideo metadata option has been set to 1
1691   if [ $fill_mythvideo_metadata -eq 0 ]; then
1692     echo "-> fill_mythvideo_metadata=0 therefore not updating mythvideo metadata for this rip" | tee -a "$logfile"
1693     return 0
1694   fi
1695
1696   # If the fill mythvideo metadata script is present, run it
1697   # fill_mythvideo_metadata.plThis will download the metadata for the DVD we ripped.
1698   if [[ -x `which fill_mythvideo_metadata.pl` ]]; then
1699     echo "-> Running fill_mythvideo_metadata.pl to lookup/add/update the metadata for this DVD: $filename" | tee -a "$logfile"
1700     fill_mythvideo_metadata.pl -N 0 -F "$filename" >> "$logfile" 2>&1
1701   else
1702     echo "-W- Unable to find the fill_mythvideo_metadata.pl script in your PATH. Unable to autofill the mythvideo DB for this rip." | tee -a "$logfile"
1703     echo "    Set the fill_mythvideo_metadata variable to 0 in the script to avoid running this step." | tee -a "$logfile"
1704   fi
1705 }
1706
1707 # remove the intermediate VOB file
1708 function remove_intermediate_vob_file {
1709   if [ $keep_intermediate_files -eq 0 ]; then
1710     [[ -e "$tmpdir/$dvdname.VOB" ]] && rm -f "$tmpdir/$dvdname.VOB"
1711   else
1712     echo "-> Keeping intermediate concatenated VOB file: $tmpdir/$dvdname.VOB" | tee -a "$logfile"
1713   fi
1714 }
1715
1716 # remove the original DVD image 
1717 function remove_intermediate_iso_file {
1718   [[ $keep_isofile -eq 1 ]] && return 1
1719   if [ $keep_intermediate_files -eq 0 ]; then
1720     [[ -e "$isofile" ]] && rm "$isofile"
1721   else
1722     echo "-> Keeping ddrescue intermediate iso file: $isofile" | tee -a "$logfile"
1723   fi
1724 }
1725
1726 # remove the intermediate dvdbackup folder
1727 function remove_intermediate_dvdbackup_folder {
1728   if [ $keep_intermediate_files -eq 0 ]; then
1729     [[ -d "$tmpdir/$dvdname" ]] && rm -rf "$tmpdir/$dvdname"
1730   else
1731     echo "-> Keeping intermediate dvdbackup folder: $tmpdir/$dvdname" | tee -a "$logfile"
1732   fi
1733 }
1734
1735 ##############################################################################################
1736 # MAIN
1737 ##############################################################################################
1738
1739 # Make a note of when this DVD rip started
1740 date=`date`
1741 echo -e "\n$date DVD rip started" >> "$logfile"
1742 echo "$cmd" >> "$logfile"
1743
1744 # Rip the DVD - Mirror Mode
1745 if [ $mirror_mode -eq 1 ]; then
1746   echo "-> Ripping DVD $dvdname to $dest"
1747
1748   if [[ "$encoder" == "makemkv" ]]; then
1749       # use makemkv to make an MKV file of the disk
1750       make_dvd_mkv_image "$dest/$dvdname.mkv" "disc" "$makemkv_disc_id"
1751       # add this video data to the mythtv DB
1752       fill_mythvideo_metadata "$dest_filename"
1753   else       
1754       # use ddrescue to make an ISO image of the disk
1755       make_dvd_iso_image "$dest/$dvdname.iso"
1756       # add this video data to the mythtv DB
1757       fill_mythvideo_metadata "$dest_filename"
1758   fi
1759
1760   # eject the disk upon completion
1761   if [ $eject_disk -ne 0 ]; then
1762     eject -T $dev
1763   fi
1764
1765   date=`date`
1766   echo "$date DVD rip completed" | tee -a "$logfile"
1767
1768   if [[ -n "$mailto" ]]; then
1769     cat "$logfile" | mailx -s "dvd rip of $dvdname DONE" "$mailto"
1770   fi
1771
1772 fi
1773
1774 # Rip the DVD - Main Title Feature Only
1775 if [ $mirror_mode -eq 0 ]; then
1776
1777   # Rip image from DVD
1778   if [ $ripdvd -eq 1 ]; then
1779     echo "-> Ripping DVD $dvdname to $dest" | tee -a "$logfile"
1780     if [[ "$encoder" == "makemkv" ]]; then
1781         # use makemkv to make an MKV file of the disk
1782         make_dvd_mkv_image "$tmpdir/$dvdname.mkv" "disc" "$makemkv_disc_id"
1783     else 
1784         # use ddrescue to make an ISO image of the disk
1785         make_dvd_iso_image "$tmpdir/$dvdname.iso"
1786     fi
1787   fi
1788
1789   # Rip image from DVD path
1790   if [ -n "$dvdpath" ]; then
1791     echo "-> Ripping DVD $dvdpath to $dest" | tee -a "$logfile"
1792      if [[ "$encoder" == "makemkv" ]]; then
1793          make_dvd_mkv_image_from_folder "$dvdpath" "$tmpdir/$dvdname.mkv" 1
1794      else 
1795          make_dvd_iso_image_from_folder "$dvdpath" "$tmpdir/$dvdname.iso" 1      
1796      fi
1797   fi
1798
1799   # make sure our isofile value is set
1800   if [ -z "$isofile" ]; then
1801       if [[ "$encoder" == "makemkv" ]]; then
1802           isofile="$tmpdir/$dvdname.mkv"
1803       else 
1804           isofile="$tmpdir/$dvdname.iso"
1805       fi
1806   fi
1807
1808   # MakeMKV special case
1809   if [[ "$encoder" == "makemkv" ]] && [[ $make_final_dest_comp -eq 1 ]]; then 
1810       echo "-> Encoding the DVD video to a compressed file using $encoder" | tee -a "$logfile"
1811
1812       # eject the DVD disk since we are finished with it
1813       [ $eject_disk -eq 2 ] && eject -T $dev
1814
1815       # Encode the final MKV file
1816       encode_mkv_file_makemkv "$isofile" "$dest/$dvdname.mkv"
1817
1818       # remove the intermediate ISO file
1819       remove_intermediate_iso_file
1820
1821       # keep intermediate log files 
1822       if [ $keep_intermediate_files -eq 0 ]; then
1823         [[ -e "$passlogfile" ]] && rm -f "$passlogfile";
1824       else
1825         echo "-> Keeping mencoder 2pass logfile: $passlogfile"
1826       fi
1827
1828       # add this video data to the mythtv DB
1829       fill_mythvideo_metadata "$dest/$dvdname.mkv"
1830
1831       # All done!
1832       exit 0
1833   fi
1834  
1835   if [ $make_final_dest_vob -eq 1 ] || [ $make_final_dest_comp -eq 1 ]; then
1836
1837     if [ ! -e "$vobfile" ]; then
1838       echo "-> Creating DVD video $vobfile" | tee -a "$logfile"
1839       
1840       # get the feature title from the ISO
1841       get_feature_title "$isofile"
1842  
1843       # get the crop value from the ISO
1844       get_crop_from_iso
1845
1846       # check for mplayer dumpstream incompatibilities
1847       # if they exist, this method will set this mode to 0.
1848       check_for_mplayer_dumpstream_incompatibility
1849
1850       if [ $use_mplayer_dumpstream -eq 1 ]; then 
1851
1852         # get our audio id from the ISO file
1853         get_audio_id_from_iso "$isofile"
1854
1855         # create our main VOB file from the ISO
1856         create_main_vob_with_mplayer "$isofile"
1857      
1858         # remove the intermediate VOB file
1859         remove_intermediate_vob_file
1860
1861         # it's possible that our VOB is still corrupted in some manner
1862         # check to make sure it is still a good VOB before continuing.
1863         check_for_mplayer_dumpstream_incompatibility
1864
1865       fi
1866  
1867       if [ $use_mplayer_dumpstream -eq 0 ]; then 
1868
1869         # use dvdbackup to make a DVD folder of the feature title
1870         make_dvdbackup_folder_image
1871   
1872         # create our main VOB file
1873         create_main_vob_with_cat
1874
1875         # get our audio id from the VOB file
1876         get_audio_id_from_vob "$tmpdir/$dvdname.VOB"
1877   
1878         # check for corrupted VOB start
1879         check_vob_for_corrupted_start
1880  
1881         # check to make sure our VOB is complete
1882         check_vob_for_completeness
1883
1884         # check to make sure our VOB doesn't have too many video packets
1885         check_vob_for_too_many_video_packets
1886
1887         # check to make sure our VOB doesn't have a52 crc errors
1888         check_vob_for_a52_crc_errors
1889
1890         # remove the intermediate VOB file
1891         remove_intermediate_vob_file
1892
1893       fi
1894
1895       # remove the intermediate ISO file
1896       remove_intermediate_iso_file
1897
1898     else
1899       if [ "$encoder" != "handbrake" ]; then 
1900         echo "-> Skipping VOB creation. VOB DVD video already exists: $vobfile" | tee -a "$logfile"
1901         # get our audio id from the VOB file
1902         get_audio_id_from_vob "$vobfile"
1903         # get the crop value from the VOB
1904         get_crop_from_vob
1905       fi
1906     fi
1907
1908     # eject the DVD disk since we are finished with it
1909     [ $eject_disk -eq 2 ] && eject -T $dev
1910
1911     # encode the VOB file to a compressed file format
1912     if [ $make_final_dest_comp -eq 1 ]; then
1913       echo "-> Encoding the DVD video to a compressed file using $encoder" | tee -a "$logfile"
1914
1915       # determine what our bitrate needs to be if a target size was specified instead
1916       calculate_bitrate_from_target_size        
1917      
1918       # encode the vob file into a compressed file format
1919       if [[ "$encoder" == "mencoder" ]]; then 
1920         encode_vob_file_mencoder
1921       fi
1922       if [[ "$encoder" == "handbrake" ]]; then
1923         encode_vob_file_handbrake
1924       fi
1925
1926       if [ $keep_intermediate_files -eq 0 ] && [ $make_final_dest_vob -eq 0 ]; then
1927         [[ -e "$vobfile" ]] && [[ $keep_vobfile -eq 0 ]] && rm -f "$vobfile";
1928         [[ -e "$passlogfile" ]] && rm -f "$passlogfile";
1929       else
1930         echo "-> Keeping VOB file: $vobfile" | tee -a "$logfile"
1931         echo "-> Keeping mencoder 2pass logfile: $passlogfile"
1932       fi
1933     fi
1934
1935   # add this video data to the mythtv DB
1936   [ $make_final_dest_comp -eq 1 ] && fill_mythvideo_metadata "$final_output_file" 
1937   [ $make_final_dest_vob -eq 1 ] && fill_mythvideo_metadata "$vobfile" 
1938     
1939   else
1940
1941   # use dvdbackup to make a DVD folder of the feature title
1942   make_dvdbackup_folder_image
1943
1944   # cd to the feature title DVD folder
1945   pushd "$tmpdir/$dvdname/VIDEO_TS" > /dev/null 2>&1
1946   if [ $? != 0 ]; then
1947     fatal_and_exit "-E- Unable to cd to $tmpdir/$dvdname/VIDEO_TS"
1948   fi
1949   
1950   # create the dvd.xml file for dvdauthor
1951   create_dvdauthor_dvd_xml_file  
1952
1953   # make the final DVD folder image
1954   make_dvdauthor_folder_image
1955
1956   # add this video data to the mythtv DB
1957   fill_mythvideo_metadata "$dest/$dvdname/VIDEO_TS" 
1958  
1959   # cd back to the dir we started from
1960   popd > /dev/null 2>&1
1961
1962   if [ $make_final_dest_iso -eq 1 ]; then
1963
1964     # make an iso image out of our directory
1965     make_dvd_iso_image_from_folder "$dest/$dvdname" "$dest/$dvdname.iso" 0
1966    
1967     # If the mkisofs was unable to make a .iso file for us, don't remove the DVD directory 
1968     if [ -s "$dest/$dvdname.iso" ]; then
1969       if [ $make_final_dest_folder -eq 0 ]; then
1970         echo "-> Removing DVD folder since ISO was created: $dest/$dvdname" | tee -a "$logfile"
1971         # remove the folder of the DVD image now that we have a .iso version of it
1972         [[ -d "$dest/$dvdname" ]] && rm -rf "$dest/$dvdname"
1973       fi
1974     else
1975       # we created an empty iso file, remove it
1976       echo "-> Removing empty ISO image: $dest/$dvdname.iso" | tee -a "$logfile"
1977       echo "-> Keeping the DVD folder since the ISO image couldn't be created properly: $dest/$dvdname"
1978       [[ -e "$dest/$dvdname.iso" ]] && rm "$dest/$dvdname.iso"
1979     fi
1980  
1981     # add this video data to the mythtv DB
1982     fill_mythvideo_metadata "$dest/$dvdname.iso" 
1983
1984   fi
1985
1986   fi
1987
1988   # remove the ddrescue DVD ISO image
1989   remove_intermediate_iso_file
1990
1991   # remove the tmp dvdbackup folder of the DVD image
1992   remove_intermediate_dvdbackup_folder
1993
1994   # eject the DVD disk upon completion
1995   [ $eject_disk -eq 1 ] && eject -T $dev
1996
1997   date=`date`
1998   echo "$date DVD rip completed" | tee -a "$logfile"
1999
2000   if [[ -n "$mailto" ]]; then
2001     cat "$logfile" | mailx -s "dvd rip of $dvdname DONE" "$mailto"
2002   fi
2003
2004 fi
2005
2006 ##############################################################################################