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