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