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