Added libdvdcss2 install info to README
[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 created MKV file into place
1168     dstfile=${dstmkv%.[^.]*}
1169     typeset -i num=0
1170     for i in `/bin/ls -1 "$dstdir"/*.mkv`; do
1171         echo -e "\n   Moving $i -> $dstfile.$num.mkv" | tee -a "$ddrescuelog"
1172         mv "$i" "$dstfile.$num.mkv"
1173         ((num = num + 1 ))
1174     done
1175     if [ $? != 0 ]; then
1176         fatal_and_exit "-E- Unhandled mv error"
1177     fi
1178     if [ $keep_intermediate_files -eq 0 ]; then
1179         [[ -d "$dstdir" ]] && rm -rf "$dstdir"
1180     fi
1181
1182     # Concatenate the encode log to our main log file, greping out unwanted lines
1183     cat "$ddrescuelog" | grep -v "Current progress:" >> "$logfile"    
1184 }
1185
1186 function make_dvd_mkv_image_from_folder {
1187     src="$1"
1188     dst="$2"
1189     handle_error=$3
1190     dstdir=${dst%.[^.]*}
1191     make_dvd_mkv_image "$dst" "file" "$src"
1192 }
1193
1194 function make_dvd_iso_image {
1195
1196   isofile="$1"
1197
1198   # check to see if we have a dvdpath to rip from instead of $dev
1199   if [ -z "$dvdpath" ]; then
1200     # load the CSS codes in the DVD drive 
1201     lsdvd_css "$dev"
1202     if [ $? != 0 ]; then
1203       fatal_and_exit "-E- lsdvd $dev failed" 
1204     fi
1205
1206     # read the DVD, ignoring/skipping CRC errors
1207     ddrescue -n -b 2048 $dev "$isofile" "$ddrescuelog"
1208     if [ $? != 0 ]; then
1209       fatal_and_exit "-E- ddrescue -n -b 2048 $dev \"$isofile\" failed"
1210     fi
1211     cat "$ddrescuelog" >> "$logfile"
1212   else
1213     # rip from a path instead
1214     make_dvd_iso_image_from_folder "$dvdpath" "$isofile" 1
1215   fi
1216 }
1217
1218 function make_dvd_iso_image_from_folder {
1219   
1220   src="$1"
1221   dst="$2"
1222   handle_error=$3
1223   
1224   echo "-> Creating ISO image of DVD video: $src -> $dst" | tee -a "$logfile"
1225
1226   # make an iso image out of our directory
1227   echo "   mkisofs -dvd-video \"$src\" 2>> \"$dumplog\" | dd of=\"$dst\" obs=32k seek=0 > /dev/null 2>> $dumplog" >> "$logfile"
1228   mkisofs -dvd-video "$src" 2>> "$dumplog" | dd of="$dst" obs=32k seek=0 > /dev/null 2>> "$dumplog"
1229
1230   # set the audio languages from the iso if it exists and is non-zero in size
1231   if [ -s "$dst" ]; then
1232     get_feature_title "$dst"
1233     get_audio_id_from_iso "$dst"
1234   fi
1235
1236   # make sure we were able to create the iso image from the folder given to us
1237   if [ ! -s "$dst" ] && [ $handle_error -eq 1 ]; then
1238     echo "-> Unable to make an iso image from the DVD folder: $dvdpath"
1239     echo "   Falling back to mplayer to create a main feature VOB from the folder instead: $dvdpath"
1240     # remove the bad iso file
1241     [[ -e "$dst" ]] && rm -f "$dst"
1242     # get the feature title from the DVD folder
1243     get_feature_title "$dvdpath"
1244     # create our main VOB file from the ISO
1245     create_main_vob_with_mplayer "$dvdpath" 
1246     # get our audio id from the VOB file
1247     get_audio_id_from_vob "$vobfile"
1248   fi
1249 }
1250
1251 function make_dvdbackup_folder_image {
1252   # extract the feature title from the DVD image
1253   echo "-> Extracting feature title using dvdbackup" | tee -a "$logfile"
1254   [[ -d "$tmpdir/$dvdname" ]] && rm -rf "$tmpdir/$dvdname"
1255   dvdbackup -F -i "$isofile" -o "$tmpdir" >> "$logfile"
1256   if [ $? != 0 ]; then
1257     fatal_and_exit '-E- dvdbackup -F -i "$isofile" -o "$tmpdir" failed'
1258   fi
1259 }
1260
1261 function make_dvdauthor_folder_image {
1262   # create a new DVD video of the feature title
1263   echo "-> Creating DVD video $dest/$dvdname" | tee -a "$logfile"
1264   [[ -d "$dest/$dvdname" ]] && rm -rf "$dest/$dvdname"
1265   dvdauthor -o "$dest/$dvdname" -x dvd.xml > $dvdauthorlog 2>&1
1266   cat $dvdauthorlog | grep -v "VOBU" >> "$logfile"
1267
1268   # There is a chance that dvdauthor won't like some of the VOBs.
1269   # We can't tell ahead of time which ones it will choke on. 
1270   # So, we need to run it over and over again until it can process
1271   # all the VOBs. If it can't handle one of them, run it through
1272   # mencoder to fix it and try again. These errors are typically
1273   # present due to the copy protection that ddrescue removed.
1274   grep -q "SCR moves" $dvdauthorlog
1275   while [ $? == 0 ]; do
1276     # fix bad vobs that get the "SCR moves backwards" error:
1277     #  STAT: Processing VTS_01_0.VOB...
1278     #  ERR:  SCR moves backwards, remultiplex input.
1279     badvob=`grep -v "^WARN:" $dvdauthorlog | grep -B 1 "SCR moves" | grep "Processing" | awk '{ print $3 }' | sed -e 's/\.\.\.//'`
1280     if [[ ! -f "$badvob" ]]; then
1281       fatal_and_exit "-E- Found a bad VOB, but could not extract it's name properly: $badvob"
1282     fi
1283     echo "-> Fixing SCR errors in DVD video file $badvob" | tee -a "$logfile"
1284     cat $badvob | mencoder $lang_opts -quiet -of mpeg -mpegopts format=dvd -oac copy -ovc copy - -o $badvob.fixed >> "$logfile" 2>&1
1285     mv -f $badvob.fixed $badvob
1286     echo "-> Creating DVD video $dest/$dvdname"
1287     dvdauthor -o "$dest/$dvdname" -x dvd.xml > $dvdauthorlog 2>&1
1288     cat $dvdauthorlog | grep -v "VOBU" >> "$logfile"
1289     grep -q "SCR moves" $dvdauthorlog
1290   done
1291 }
1292
1293 function get_feature_title {
1294   source="$1"
1295   # if a feature title was given on the command line, use it
1296   if [ $feature_title_override -ne 0 ]; then
1297     feature_title=$feature_title_override
1298     return 0
1299   fi
1300   # otherwise, use lsdvd to figure it out
1301   if [ $ripdvd -eq 1 ]; then
1302     lsdvd_longest_title "$dev" 
1303   else 
1304     lsdvd_longest_title "$source"
1305   fi
1306 }
1307
1308 function create_main_vob_with_cat {
1309   # cd to the feature title DVD folder
1310   pushd "$tmpdir/$dvdname/VIDEO_TS" > /dev/null 2>&1
1311   if [ $? != 0 ]; then
1312     fatal_and_exit "-E- Unable to cd to $tmpdir/$dvdname/VIDEO_TS"
1313   fi
1314
1315   # concatenate all the VOBs together into 1 giant VOB
1316   vobs=`/bin/ls -1 VTS*.VOB | grep -v "0.VOB" | tr '\n' ' '`
1317   cat $vobs > "$tmpdir/$dvdname.VOB"
1318
1319   # cd back to the dir we started from
1320   popd > /dev/null 2>&1
1321 }
1322
1323 function create_main_vob_with_mplayer {
1324
1325   # argument processing  
1326   source="$1"
1327   remove_dumplog=$2
1328
1329   # make sure we have a valid feature title
1330   if [ $invalid_feature_title -eq 1 ] && [ $feature_title_override -eq 0 ]; then
1331     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."
1332   fi
1333
1334   # check to make sure we didn't detect an mplayer dumpstream incompatibility earlier
1335   if [ $mplayer_dumpstream_incompatibility -eq 1 ]; then
1336     msg="-E- We detected an mplayer dumpstream incompatibility earlier."
1337     msg="$msg We also detected a condition that may require you to use dumpstream. "
1338     msg="$msg\n    Unable to rip this DVD in the mode you requested."
1339     fatal_and_exit "$msg"
1340   fi
1341
1342   # use mplayer to create the main VOB file
1343   echo "-> Using mplayer to dump the DVD feature title $feature_title to a VOB file directly: $vobfile" | tee -a "$logfile"
1344   echo "   mplayer $lang_opts -dumpstream -dumpfile \"$vobfile\" -dvd-device \"$source\" dvd://$feature_title > $dumplog 2>&1" >> "$logfile"
1345   mplayer $lang_opts -dumpstream -dumpfile "$vobfile" -dvd-device "$source" dvd://$feature_title > $dumplog 2>&1
1346   if [ $? != 0 ]; then
1347     cat $dumplog | grep -v "^A:" >> "$logfile"
1348     fatal_and_exit "-E- Mplayer Failed"
1349   fi
1350   cat $dumplog | grep -v "^A:" >> "$logfile"
1351   [[ -e "$dumplog" ]] && [[ $remove_dumplog -eq 1 ]] && rm -f $dumplog
1352 }
1353
1354 function get_audio_id_from_iso {
1355   # Adjust our audio ID to find the english audio stream
1356   # This should be 128. However, if 128 is not there, pick the next one that incrementally is.
1357   iso="$1"
1358   aidcheck=`tempfile`
1359   aid=$default_aid
1360   alang=$default_alang
1361   if [ $aid_override -lt 0 ]; then 
1362     mplayer -v -endpos 0 -dvd-device "$iso" dvd://$feature_title > $aidcheck 2>&1
1363     grep -q "aid: $aid" $aidcheck
1364     while [ $? == 1 ] && [ $aid -lt 159 ]; do
1365       (( aid = aid + 1 ))
1366       grep -q "aid: $aid" $aidcheck
1367     done
1368     [[ -e "$aidcheck" ]] && rm -f "$aidcheck"
1369   else
1370     aid=$aid_override
1371   fi
1372   echo "-> Setting the audio stream ID to $aid" | tee -a "$logfile"
1373   # mencoder default DVD audio track language selection (english)
1374   lang_opts="-aid $aid -alang $alang"
1375 }
1376
1377 function get_crop_from_iso { 
1378   FRAMES=10000
1379   echo "-> Detecting black frame border crop value from ISO file"
1380   echo "   mplayer -vf cropdetect -frames $FRAMES -nosound -vo md5sum -benchmark -dvd-device \"$isofile\" dvd://$feature_title > $dumplog 2>&1" >> "$logfile"
1381   mplayer -vf cropdetect -frames $FRAMES -nosound -vo md5sum -benchmark -dvd-device "$isofile" dvd://$feature_title > $dumplog 2>&1
1382   [[ -e "md5sums" ]] && rm -f "md5sums"
1383   CROP=`cat $dumplog | grep CROP | tail -1`
1384   echo "   Found crop value of $CROP" >> "$logfile"
1385   CROP=${CROP#* crop=}
1386   CROP=${CROP%%\).*}
1387   typeset -i CROPCHECK
1388   CROPCHECK=`echo "$CROP" | awk -F ':' '{ print $1 }'`
1389   echo "   Final crop value of $CROP with cropcheck value of $CROPCHECK" >> "$logfile"
1390   if [ -z "$CROP" ]; then
1391     echo "-W- Unable to extract CROP value from iso: $isofile" | tee -a "$logfile"
1392     return
1393   fi
1394   if [ $CROPCHECK -lt 0 ]; then 
1395     CROP=""
1396   else 
1397     CROP=",crop=$CROP"
1398   fi
1399   echo "   Setting mencoder crop filter to: $CROP"
1400 }
1401
1402 function get_crop_from_vob { 
1403   FRAMES=10000
1404   echo "-> Detecting black frame border crop value from VOB file"
1405   echo "   mplayer -vf cropdetect -frames $FRAMES -nosound -vo md5sum -benchmark \"$vobfile\" > $dumplog 2>&1" >> "$logfile"
1406   mplayer -vf cropdetect -frames $FRAMES -nosound -vo md5sum -benchmark "$vobfile" > $dumplog 2>&1
1407   [[ -e "md5sums" ]] && rm -f "md5sums"
1408   CROP=`cat $dumplog | grep CROP | tail -1`
1409   echo "   Found crop value of $CROP" >> "$logfile"
1410   CROP=${CROP#* crop=}
1411   CROP=${CROP%%\).*}
1412   typeset -i CROPCHECK
1413   CROPCHECK=`echo "$CROP" | awk -F ':' '{ print $1 }'`
1414   echo "   Final crop value of $CROP with cropcheck value of $CROPCHECK" >> "$logfile"
1415   if [ -z "$CROP" ]; then
1416     echo "-W- Unable to extract CROP value from iso: $isofile" | tee -a "$logfile"
1417     return
1418   fi
1419   if [ $CROPCHECK -lt 0 ]; then 
1420     CROP=""
1421   else 
1422     CROP=",crop=$CROP"
1423   fi
1424   echo "   Setting mencoder crop filter to: $CROP"
1425 }
1426
1427 function get_audio_track_from_mkv { 
1428   mkv="$1"
1429   handbrake_cli="$2"
1430   aidcheck=`tempfile`
1431   alang=$default_alang
1432
1433   # Find out what audio track matches our alang
1434   $handbrake_cli --stop-at duration:1 -i "$mkv" -o /dev/null -v 100 > $aidcheck 2>&1
1435   stream=`grep "$alang" $aidcheck | grep "Audio:"`
1436
1437   # extract the track number that handbrake uses
1438   track=`echo "$stream" | awk '{ print $2; }' | awk -F '.' '{ print $2; }' | awk -F '(' '{ print $1; }'`
1439   
1440   if [ -n "$track" ]; then   
1441       echo "   Setting the audio track to $track." | tee -a "$logfile"
1442   fi
1443 }
1444
1445 function get_subtitle_track_from_mkv { 
1446   mkv="$1"
1447   handbrake_cli="$2"
1448   aidcheck=`tempfile`
1449   alang=$default_alang
1450
1451   # Find out what audio track matches our alang
1452   $handbrake_cli --stop-at duration:1 -i "$mkv" -o /dev/null -v 100 > $aidcheck 2>&1
1453   stream=`grep "$alang" $aidcheck | grep "Subtitle:" | head -n 1`
1454
1455   # extract the track number that handbrake uses
1456   track=`echo "$stream" | awk '{ print $2; }' | awk -F '.' '{ print $2; }' | awk -F '(' '{ print $1; }'`
1457
1458   # add 1 to the track number since mkv tools start at 1, and HandBrake starts at 0
1459   ((track = track + 1))
1460
1461   if [ -n "$track" ]; then   
1462       echo "   Setting the subtitle track to $track." | tee -a "$logfile"
1463   fi
1464 }
1465
1466 function get_audio_track_from_vob {
1467   # Adjust our audio ID to find the english audio stream
1468   # This should be 128. However, if 128 is not there, pick the next one that incrementally is.
1469   vob="$1"
1470   handbrake_cli="$2"
1471   aidcheck=`tempfile`
1472   aid=$default_aid
1473   alang=$default_alang
1474   if [ $aid_override -lt 0 ]; then 
1475     mplayer -v -endpos 0 "$vob" > $aidcheck 2>&1
1476     grep -q "Found audio stream: $aid" $aidcheck
1477     while [ $? == 1 ] && [ $aid -lt 159 ]; do
1478       (( aid = aid + 1 ))
1479       grep -q "Found audio stream: $aid" $aidcheck
1480     done
1481     [[ -e "$aidcheck" ]] && rm -f "$aidcheck"
1482   else 
1483     aid=$aid_override
1484   fi
1485   # Now that we've found the right audio id, find the corresponding audio track in HandBrake
1486
1487   # convert the aid we found into hex
1488   aid_hex=`echo "obase=16; $aid" | bc`
1489   
1490   # extract the audio streams in the vob
1491   #ffmpeg -i "$vob" > $aidcheck 2>&1
1492   $handbrake_cli --stop-at duration:1 -i "$vob" -o /dev/null -v 100 > $aidcheck 2>&1
1493   
1494   # find the stream that matches our aid
1495   #stream=`grep "Stream.*\[0x$aid_hex\]" $aidcheck`
1496   #stream=`grep "scan: audio" $aidcheck | grep -n "" | grep "scan: audio 0x$aid_hex"`
1497   stream=`grep "add_audio_to_title:" $aidcheck | grep -n "" | grep "add_audio_to_title:.* stream 0x$aid_hex"`
1498  
1499   # extract the track number that handbrake uses
1500   #track=`expr match "$stream" '.*#[0-9]\.\([0-9]*\)'`
1501   track=`expr match "$stream" '^\([0-9]*\):'`
1502
1503   if [ -n "$track" ]; then   
1504     echo "   Setting the audio ID to $aid. Setting the audio track to $track." | tee -a "$logfile"
1505   fi
1506 }
1507
1508 function get_audio_id_from_vob {
1509   # Adjust our audio ID to find the english audio stream
1510   # This should be 128. However, if 128 is not there, pick the next one that incrementally is.
1511   vob="$1"
1512   aidcheck=`tempfile`
1513   aid=$default_aid
1514   alang=$default_alang
1515   if [ $aid_override -lt 0 ]; then 
1516     mplayer -v -endpos 0 "$vob" > $aidcheck 2>&1
1517     grep -q "Found audio stream: $aid" $aidcheck
1518     while [ $? == 1 ] && [ $aid -lt 159 ]; do
1519       (( aid = aid + 1 ))
1520       grep -q "Found audio stream: $aid" $aidcheck
1521     done
1522     [[ -e "$aidcheck" ]] && rm -f "$aidcheck"
1523   else 
1524     aid=$aid_override
1525   fi
1526   echo "-> Setting the audio stream ID to $aid" | tee -a "$logfile"
1527   # mencoder default DVD audio track language selection (english)
1528   lang_opts="-aid $aid -alang $alang"
1529 }
1530
1531 function check_vob_for_corrupted_start {
1532   # check to see if the beginning of the DVD has a form of copy protection
1533   # where they have deliberately broken the first X number of frames of the DVD.
1534   # If we don't skip these, our resulting VOB file will not play.
1535   badvobcheck=`tempfile`
1536   endpos=360
1537   skip=0
1538   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
1539   if [ $? != 0 ]; then
1540     fatal_and_exit "-E- Mencoder Failed"
1541   fi
1542   grep "Writing header" -A `wc $badvobcheck | awk '{ print $1 }'` $badvobcheck | grep -q "Too many video packets in the buffer"
1543   while [ $? == 0 ] && [ $skip -lt $endpos ]; do
1544     (( skip = skip + 5 ))
1545     echo "-> Bad VOB copy protection detected. Trying new skip value of $skip" | tee -a "$logfile"
1546     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
1547     if [ $? != 0 ]; then
1548       fatal_and_exit "-E- Mencoder Failed"
1549     fi
1550     grep "Writing header" -A `wc $badvobcheck | awk '{ print $1 }'` $badvobcheck | grep -q "Too many video packets in the buffer"
1551   done
1552   [[ -e "$badvobcheck" ]] && rm -f "$badvobcheck";
1553
1554   # cat the giant VOB into mencoder to create a playable VOB file
1555   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
1556   if [ $? != 0 ]; then
1557     fatal_and_exit "-E- Mencoder Failed"
1558   fi
1559 }
1560
1561 function check_vob_for_completeness {
1562   # check to make sure we got out a complete VOB.
1563   # there is another kind of copy protection where the VOB's may
1564   # have "MPG EOF" frames in the middle of the stream. 
1565   # this causes mencoder to not process the entire VOB, and exit without any errors.
1566   # detect this by seeing how much smaller the dst vob is from the src vob.
1567   MAX_FILESIZE_DELTA_PERCENT=70
1568   SRC_VOB_FILESIZE=$(stat -c%s "$tmpdir/$dvdname.VOB")
1569   DST_VOB_FILESIZE=$(stat -c%s "$vobfile")
1570   FILESIZE_DELTA=`echo "scale=2; $DST_VOB_FILESIZE / $SRC_VOB_FILESIZE * 100" | bc | awk -F '.' '{ print $1 }'`
1571   if [ $FILESIZE_DELTA -lt $MAX_FILESIZE_DELTA_PERCENT ]; then
1572     # Try one other way to get the VOB using mplayer directly to rip the feature titleset.
1573     echo "-> Detected bad VOB size copy protection after processing concatenated VOB file." | tee -a "$logfile"
1574     create_main_vob_with_mplayer "$isofile"
1575     [[ -e "$dumplog" ]] && rm -f $dumplog
1576     DST_VOB_FILESIZE=$(stat -c%s "$vobfile")
1577     FILESIZE_DELTA=`echo "scale=2; $DST_VOB_FILESIZE / $SRC_VOB_FILESIZE * 100" | bc | awk -F '.' '{ print $1 }'`
1578     if [ $FILESIZE_DELTA -lt $MAX_FILESIZE_DELTA_PERCENT ]; then
1579       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'"
1580     fi
1581   fi
1582 }
1583
1584 function check_vob_for_too_many_video_packets {
1585   # If our earlier algorithm to work around this failed, throw an error.
1586   # check to see if this DVD has a protection scheme we don't know how to work around
1587   # when I tried to burn the CARS DVD for example, you can't play the resulting VOB file.
1588   # for some reason, the video is black, while the audio rolls, then the video finally comes
1589   # in, but it is WAY off the audio. This appears to be due to some bad frames at the beginning of 
1590   # the 1st VOB. Until I figure out how to work around this, detect it, and error out.
1591   # instead of pulling the image from the disk again, you can pull it directly from the iso: -dvd-device $iso_path
1592   grep -q "Too many video packets in the buffer:" "$logfile"
1593   if [ $? == 0 ]; then
1594     # Try one other way to get the VOB using mplayer directly to rip the feature titleset.
1595     echo "-> Detected corrupt audio stream copy protection after processing concatenated VOB file." | tee -a "$logfile"
1596     create_main_vob_with_mplayer "$isofile"
1597     grep -q "Too many video packets in the buffer:" $dumplog
1598     if [ $? == 0 ]; then
1599       [[ -e "$dumplog" ]] && rm -f $dumplog
1600       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'"
1601     fi
1602     [[ -e "$dumplog" ]] && rm -f $dumplog
1603   fi
1604 }
1605
1606 function check_vob_for_a52_crc_errors {
1607   # Let's see if we can playback our newly created VOB file without any errors.
1608   # if there are issues, let's detect them now, and try to recreate the VOB
1609   # there are some forms of copy protection that have missed above, that evidence
1610   # themselves when we try to playback the VOB file. This was added to deal with
1611   # the "a52: CRC check failed" copy protection scheme.
1612   MAX_ERRORS=10
1613   ENDPOS=120
1614   echo "-> Checking for a52 audio stream CRC errors" | tee -a "$logfile"
1615   mplayer -endpos $ENDPOS -ao null -vo null "$vobfile" > $dumplog 2>&1
1616   cat $dumplog | grep -v "^A:" >> "$logfile"
1617   errors=`grep "a52: CRC check failed" $dumplog | wc | awk '{ print $1 }'`
1618   if [ $errors -gt $MAX_ERRORS ]; then
1619     echo "-> Detected a52 audio stream CRC errors copy protection after processing concatenated VOB file." | tee -a "$logfile"
1620     create_main_vob_with_mplayer "$isofile"
1621     echo "-> Checking for a52 audio stream CRC errors" | tee -a "$logfile"
1622     mplayer -endpos $ENDPOS -ao null -vo null "$vobfile" > $dumplog 2>&1
1623     if [ $? != 0 ]; then
1624       cat $dumplog | grep -v "^A:" >> "$logfile"
1625       fatal_and_exit "-E- Mplayer Failed"
1626     fi
1627     cat $dumplog | grep -v "^A:" >> "$logfile"
1628     errors=`grep "a52: CRC check failed" $dumplog | wc | awk '{ print $1 }'`
1629     if [ $errors -gt $MAX_ERRORS ]; then
1630       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'"
1631     fi
1632   fi
1633   [[ -e "$dumplog" ]] && rm -f $dumplog
1634 }
1635
1636 function calculate_bitrate_from_target_size {
1637   # determine what our bitrate needs to be if a target size was specified instead
1638   if [ $target_size -ne 0 ] && [ $custom_video_bitrate -eq 0 ]; then
1639     vob_length=`mplayer -identify -v "$vobfile" -endpos 0 2>&1 | grep ID_LENGTH | awk -F '=' '{ print $2 }' | awk -F '.' '{ print $1 }'`
1640     ((min_length = minimum_feature_title_length * 60))
1641     if [[ $vob_length -gt $min_length ]]; then 
1642       ((target_video_bitrate = (target_size * 1024 * 8) / vob_length ))
1643       custom_video_bitrate=1
1644       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"
1645     else
1646       echo "-W- Unable to determine the real length of this DVD feature title." | tee -a "$logfile"
1647       echo "    A target bitrate from the target_size requested will not be set." | tee -a "$logfile"
1648       echo "    If using handbrake, only the target_size will be passed to the encoder." | tee -a "$logfile" 
1649       echo "    If using mencoder, the target_size will be entirely disregarded." | tee -a "$logfile"
1650       echo "    You may need to rerun with the -b option with a target bitrate to get the desired size." | tee -a "$logfile"
1651       if [[ $encoder -ne "handbrake" ]] || [[ "$profile" =~ "xvid" ]]; then
1652         fatal_and_exit "-E- You'll need rip this DVD with the handbrake encoder and an MP4 type profile to get a good rip."
1653       fi
1654     fi
1655   fi
1656 }
1657
1658 function create_dvdauthor_dvd_xml_file {
1659   # make a dvdauthor xml menu file to create a valid DVD video from 
1660   # this script does a good job, but we'll still need to clean it up a bit after it runs
1661   echo "-> Creating dvdauthor XML menu file" | tee -a "$logfile"
1662   makexml -overwrite -dvd *.VOB -out dvd >> "$logfile" 2>&1
1663   if [ $? != 0 ]; then
1664     fatal_and_exit '-E- makexml -dvd *.VOB -out dvd failed'
1665   fi
1666
1667   # replace the first line of the xml file to remove the bad dest path
1668   awk -v line=1 -v new_content="<dvdauthor>" '{
1669     if (NR == line) {
1670       print new_content;
1671     } else {
1672       print $0;
1673     }
1674   }' dvd.xml > dvd.xml.new
1675   mv -f dvd.xml.new dvd.xml
1676   if [ $? != 0 ]; then
1677     fatal_and_exit '-E- mv dvd.xml.new dvd.xml failed'
1678   fi
1679
1680   # remove the "<video " property line from the xml file
1681   cat dvd.xml | grep -v "<video" > dvd.xml.new
1682   mv -f dvd.xml.new dvd.xml
1683   if [ $? != 0 ]; then
1684     fatal_and_exit '-E- mv dvd.xml.new dvd.xml failed'
1685   fi
1686   
1687   # remove the extra <pgc>..</pgc> pairs
1688   cat dvd.xml | awk 'BEGIN {x=1}
1689   {
1690     if ($0~"</pgc>") {x=0}
1691     if (x==1) {print $0}
1692     if ($0~"<pgc>") {x=1}
1693   }' > dvd.xml.new
1694   echo -e "</pgc>\n</titles>\n</titleset>\n</dvdauthor>" >> dvd.xml.new
1695   mv -f dvd.xml.new dvd.xml
1696   if [ $? != 0 ]; then
1697     fatal_and_exit '-E- mv dvd.xml.new dvd.xml failed'
1698   fi
1699
1700   # remove the VTS_*_0.VOB file as this is just the main menu video clip
1701   cat dvd.xml | grep -v "VTS_.*_0.VOB" > dvd.xml.new
1702   mv -f dvd.xml.new dvd.xml
1703   if [ $? != 0 ]; then
1704     fatal_and_exit '-E- mv dvd.xml.new dvd.xml failed'
1705   fi
1706 }
1707
1708 function check_for_mplayer_dumpstream_incompatibility {
1709
1710   echo "-> Checking for mplayer dumpstream incompatibilities" | tee -a "$logfile"
1711
1712   # Check to see if the DVD had any lsdvd incompatibilities
1713   if [ $lsdvd_incompatibility -eq 1 ]; then
1714     invalid_feature_title=1
1715     echo "-E- Unable to determine the feature title due to an lsdvd inability to DeCSS" | tee -a "$logfile"
1716     echo "    You will need to determine this yourself and rerun the script with the -t option" | tee -a "$logfile"
1717     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"    
1718     return
1719   fi
1720
1721   if [ ! -e "$vobfile" ]; then
1722     # mplayer dumpstream does not work on DVDs that obscure the feature title.
1723     # A DVD that has 99 titles, where the longest title isn't the main feature
1724     # breaks mplayer dumpstream. We have to fallback to using dvdbackup to figure
1725     # out what the feature title is. This script will run through that flow if we
1726     # set use_mplayer_dumpstream to 0. Check for this here.
1727     if [ $ripdvd -eq 1 ]; then
1728       alarm $lsdvd_timeout lsdvd $dev | grep -q "Title: 99"
1729     else
1730       alarm $lsdvd_timeout lsdvd "$isofile" | grep -q "Title: 99"
1731     fi
1732     # If we have 99 titles and a feature title wasn't given on the command line, switch modes.
1733     if [ $? == 0 ] && [ $feature_title_override -eq 0 ]; then
1734       if [ $trust_feature_title_autodetect_when_uncertain -eq 0 ]; then
1735         echo "-E- Unable to determine the feature title due to the 99 title copy protection scheme" | tee -a "$logfile"
1736         echo "    You will need to determine this yourself and rerun the script with the -t option" | tee -a "$logfile"
1737         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"
1738         invalid_feature_title=1
1739       else 
1740         echo "    Falling back to non mplayer dumpstream methods to copy the DVD" | tee -a "$logfile"
1741         echo "-W- We still may not be able to autodetect the right feature title" | tee -a "$logfile"
1742         echo "    You may need to determine this yourself and rerun the script with the -t option" | tee -a "$logfile"
1743         use_mplayer_dumpstream=0
1744         invalid_feature_title=1
1745       fi
1746       return
1747     fi
1748   fi
1749
1750   # There is another form of protection that causes the mplayer dumpstream to fail. 
1751   # This can be detected by telling mplayer to parse the VOB file by copying its audio
1752   # video streams to a dummy output file (/dev/null). Do that here to check for that 
1753   # problem before continuing.
1754   if [ -e "$vobfile" ]; then
1755     mplayer_opts="-quiet -ofps 30000/1001 -ffourcc DIVX -oac copy -ovc copy"
1756     mencoder $mplayer_opts "$vobfile" -o "/dev/null" > $dumplog 2>&1
1757     grep -q "Too many audio packets in the buffer" $dumplog
1758     if [ $? == 0 ]; then
1759       echo "-> The VOB dumped by mplayer is invalid. Falling back to non mplayer dumpstream to copy the DVD" | tee -a "$logfile"
1760       use_mplayer_dumpstream=0
1761       mplayer_dumpstream_incompatibility=1
1762     fi
1763     [[ -e "$dumplog" ]] && rm -f $dumplog
1764   fi
1765
1766   # There is another form of protection that causes the mplayer dumpstream to fail.
1767   # The resulting VOB file looks complete, but has something in it that causes mplayer/mencoder 
1768   # to be unable to encode it since it thinks the entire VOB is only a few minutes long in length.
1769   # Using HandBrake with an MP4 type profile can work around this, but mencoder or Handbrake with XVID profile won't.
1770   if [ -e "$vobfile" ]; then
1771     vob_length=`mplayer -identify -v "$vobfile" -endpos 0 2>&1 | grep ID_LENGTH | awk -F '=' '{ print $2 }' | awk -F '.' '{ print $1 }'`
1772     ((min_length = minimum_feature_title_length * 60))
1773     if [[ $vob_length -lt $min_length ]]; then 
1774       if [[ $encoder -ne "handbrake" ]] || [[ "$profile" =~ "xvid" ]]; then
1775         echo "-E- The main feature title that was ripped from the DVD has an invalid movie length." | tee -a "$logfile"
1776         echo "    You'll need rip this DVD with the handbrake encoder and an MP4 or MKV type profile instead." | tee -a "$logfile"
1777         mplayer_dumpstream_incompatibility=1
1778         fatal_and_exit "-E- Aborting encoding step due to invalid movie length."
1779       fi
1780     fi
1781   fi
1782 }
1783
1784 function fill_mythvideo_metadata {
1785
1786   # This function must be passed the filename as an argument
1787   # The filename must be a full path to the file
1788   filename="$1"
1789
1790   # Make sure the fill mythvideo metadata option has been set to 1
1791   if [ $fill_mythvideo_metadata -eq 0 ]; then
1792     echo "-> fill_mythvideo_metadata=0 therefore not updating mythvideo metadata for this rip" | tee -a "$logfile"
1793     return 0
1794   fi
1795
1796   # If the fill mythvideo metadata script is present, run it
1797   # fill_mythvideo_metadata.plThis will download the metadata for the DVD we ripped.
1798   if [[ -x `which fill_mythvideo_metadata.pl` ]]; then
1799     echo "-> Running fill_mythvideo_metadata.pl to lookup/add/update the metadata for this DVD: $filename" | tee -a "$logfile"
1800     fill_mythvideo_metadata.pl -N 0 -F "$filename" >> "$logfile" 2>&1
1801   else
1802     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"
1803     echo "    Set the fill_mythvideo_metadata variable to 0 in the script to avoid running this step." | tee -a "$logfile"
1804   fi
1805 }
1806
1807 # remove the intermediate VOB file
1808 function remove_intermediate_vob_file {
1809   if [ $keep_intermediate_files -eq 0 ]; then
1810     [[ -e "$tmpdir/$dvdname.VOB" ]] && rm -f "$tmpdir/$dvdname.VOB"
1811   else
1812     echo "-> Keeping intermediate concatenated VOB file: $tmpdir/$dvdname.VOB" | tee -a "$logfile"
1813   fi
1814 }
1815
1816 # remove the original DVD image 
1817 function remove_intermediate_iso_file {
1818   [[ $keep_isofile -eq 1 ]] && return 1
1819   if [ $keep_intermediate_files -eq 0 ]; then
1820     [[ -e "$isofile" ]] && rm "$isofile"
1821   else
1822     echo "-> Keeping ddrescue intermediate iso file: $isofile" | tee -a "$logfile"
1823   fi
1824 }
1825
1826 # remove the intermediate dvdbackup folder
1827 function remove_intermediate_dvdbackup_folder {
1828   if [ $keep_intermediate_files -eq 0 ]; then
1829     [[ -d "$tmpdir/$dvdname" ]] && rm -rf "$tmpdir/$dvdname"
1830   else
1831     echo "-> Keeping intermediate dvdbackup folder: $tmpdir/$dvdname" | tee -a "$logfile"
1832   fi
1833 }
1834
1835 ##############################################################################################
1836 # MAIN
1837 ##############################################################################################
1838
1839 # Make a note of when this DVD rip started
1840 date=`date`
1841 echo -e "\n$date DVD rip started" >> "$logfile"
1842 echo "$cmd" >> "$logfile"
1843
1844 # Rip the DVD - Mirror Mode
1845 if [ $mirror_mode -eq 1 ]; then
1846   echo "-> Ripping DVD $dvdname to $dest"
1847
1848   if [[ "$ripper" == "makemkv" ]]; then
1849       # use makemkv to make an MKV file of the disk
1850       make_dvd_mkv_image "$tmpdir/$dvdname.mkv" "disc" "$makemkv_disc_id"
1851       echo "   Moving $tmpdir/$dvdname.mkv -> $dest/$dvdname.mkv"
1852       mv "$tmpdir/$dvdname.mkv" "$dest/$dvdname.mkv"
1853       # add this video data to the mythtv DB
1854       fill_mythvideo_metadata "$dest_filename"
1855   else       
1856       # use ddrescue to make an ISO image of the disk
1857       make_dvd_iso_image "$tmpdir/$dvdname.iso"
1858       echo "   Moving $tmpdir/$dvdname.mkv -> $dest/$dvdname.mkv"
1859       mv "$tmpdir/$dvdname.iso" "$dest/$dvdname.iso"
1860       # add this video data to the mythtv DB
1861       fill_mythvideo_metadata "$dest_filename"
1862   fi
1863
1864   # eject the disk upon completion
1865   if [ $eject_disk -ne 0 ]; then
1866     eject -T $dev
1867   fi
1868
1869   date=`date`
1870   echo "$date DVD rip completed" | tee -a "$logfile"
1871
1872   if [[ -n "$mailto" ]]; then
1873     cat "$logfile" | mailx -s "dvd rip of $dvdname DONE" "$mailto"
1874   fi
1875
1876 fi
1877
1878 # Rip the DVD - Main Title Feature Only
1879 if [ $mirror_mode -eq 0 ]; then
1880
1881   # Rip image from DVD
1882   if [ $ripdvd -eq 1 ]; then
1883     echo "-> Ripping DVD $dvdname to $dest" | tee -a "$logfile"
1884     if [[ "$ripper" == "makemkv" ]]; then
1885         # use makemkv to make an MKV file of the disk
1886         make_dvd_mkv_image "$tmpdir/$dvdname.mkv" "disc" "$makemkv_disc_id"
1887         vobfile="$tmpdir/$dvdname.mkv"
1888     else 
1889         # use ddrescue to make an ISO image of the disk
1890         make_dvd_iso_image "$tmpdir/$dvdname.iso"
1891         isofile="$tmpdir/$dvdname.iso"
1892     fi
1893   fi
1894
1895   # Rip image from DVD path
1896   if [ -n "$dvdpath" ]; then
1897     echo "-> Ripping DVD $dvdpath to $dest" | tee -a "$logfile"
1898     make_dvd_iso_image_from_folder "$dvdpath" "$tmpdir/$dvdname.iso" 1   
1899     isofile="$tmpdir/$dvdname.iso"
1900   fi
1901  
1902   if [ $make_final_dest_vob -eq 1 ] || [ $make_final_dest_comp -eq 1 ]; then
1903
1904     # Create our "vobfile" using makemkv if told to do so
1905     if [[ "$isofile" =~ "iso" ]] && [[ "$ripper" == "makemkv" ]]; then
1906         vobfile="$tmpdir/$dvdname.mkv"
1907         make_dvd_mkv_image "$vobfile" "iso" "$isofile"
1908     fi
1909
1910     # get the feature title from the ISO
1911     if [[ "$isofile" =~ "iso" ]]; then
1912         get_feature_title "$isofile"
1913     fi
1914
1915     # Create our "vobfile" using mplayer if needed
1916     if [[ ! -e "$vobfile" ]] && [[ "$isofile" =~ "iso" ]]; then
1917       echo "-> Creating DVD video $vobfile from $isofile" | tee -a "$logfile"
1918        
1919       # get the crop value from the ISO
1920       get_crop_from_iso
1921
1922       # check for mplayer dumpstream incompatibilities
1923       # if they exist, this method will set this mode to 0.
1924       check_for_mplayer_dumpstream_incompatibility
1925
1926       if [ $use_mplayer_dumpstream -eq 1 ]; then 
1927
1928         # get our audio id from the ISO file
1929         get_audio_id_from_iso "$isofile"
1930
1931         # create our main VOB file from the ISO
1932         create_main_vob_with_mplayer "$isofile"
1933      
1934         # remove the intermediate VOB file
1935         remove_intermediate_vob_file
1936
1937         # it's possible that our VOB is still corrupted in some manner
1938         # check to make sure it is still a good VOB before continuing.
1939         check_for_mplayer_dumpstream_incompatibility
1940
1941       fi
1942  
1943       if [ $use_mplayer_dumpstream -eq 0 ]; then 
1944
1945         # use dvdbackup to make a DVD folder of the feature title
1946         make_dvdbackup_folder_image
1947   
1948         # create our main VOB file
1949         create_main_vob_with_cat
1950
1951         # get our audio id from the VOB file
1952         get_audio_id_from_vob "$tmpdir/$dvdname.VOB"
1953   
1954         # check for corrupted VOB start
1955         check_vob_for_corrupted_start
1956  
1957         # check to make sure our VOB is complete
1958         check_vob_for_completeness
1959
1960         # check to make sure our VOB doesn't have too many video packets
1961         check_vob_for_too_many_video_packets
1962
1963         # check to make sure our VOB doesn't have a52 crc errors
1964         check_vob_for_a52_crc_errors
1965
1966         # remove the intermediate VOB file
1967         remove_intermediate_vob_file
1968
1969       fi
1970
1971       # remove the intermediate ISO file
1972       remove_intermediate_iso_file
1973
1974     else
1975       if [[ -e "$vobfile" ]] && [[ "$encoder" != "handbrake" ]]; then 
1976         echo "-> Skipping VOB creation. VOB DVD video already exists: $vobfile" | tee -a "$logfile"
1977         # get our audio id from the VOB file
1978         get_audio_id_from_vob "$vobfile"
1979         # get the crop value from the VOB
1980         get_crop_from_vob
1981       fi
1982     fi
1983
1984     # eject the DVD disk since we are finished with it
1985     [ $eject_disk -eq 2 ] && eject -T $dev
1986
1987     # encode the VOB file to a compressed file format
1988     if [ $make_final_dest_comp -eq 1 ]; then
1989       echo "-> Encoding the DVD video to a compressed file using $encoder" | tee -a "$logfile"
1990
1991       # determine what our bitrate needs to be if a target size was specified instead
1992       calculate_bitrate_from_target_size        
1993      
1994       # encode the vob file into a compressed file format
1995       if [[ "$encoder" == "mencoder" ]]; then 
1996         encode_vob_file_mencoder
1997       fi
1998       if [[ "$encoder" == "handbrake" ]]; then
1999         encode_vob_file_handbrake
2000       fi
2001
2002       if [ $keep_intermediate_files -eq 0 ] && [ $make_final_dest_vob -eq 0 ]; then
2003         [[ -e "$vobfile" ]] && [[ $keep_vobfile -eq 0 ]] && rm -f "$vobfile";
2004         [[ -e "$passlogfile" ]] && rm -f "$passlogfile";
2005       else
2006         echo "-> Keeping VOB file: $vobfile" | tee -a "$logfile"
2007         echo "-> Keeping mencoder 2pass logfile: $passlogfile"
2008       fi
2009     fi
2010
2011   # add this video data to the mythtv DB
2012   [ $make_final_dest_comp -eq 1 ] && fill_mythvideo_metadata "$final_output_file" 
2013   [ $make_final_dest_vob -eq 1 ] && fill_mythvideo_metadata "$vobfile" 
2014     
2015   else
2016
2017   # use dvdbackup to make a DVD folder of the feature title
2018   make_dvdbackup_folder_image
2019
2020   # cd to the feature title DVD folder
2021   pushd "$tmpdir/$dvdname/VIDEO_TS" > /dev/null 2>&1
2022   if [ $? != 0 ]; then
2023     fatal_and_exit "-E- Unable to cd to $tmpdir/$dvdname/VIDEO_TS"
2024   fi
2025   
2026   # create the dvd.xml file for dvdauthor
2027   create_dvdauthor_dvd_xml_file  
2028
2029   # make the final DVD folder image
2030   make_dvdauthor_folder_image
2031
2032   # add this video data to the mythtv DB
2033   fill_mythvideo_metadata "$dest/$dvdname/VIDEO_TS" 
2034  
2035   # cd back to the dir we started from
2036   popd > /dev/null 2>&1
2037
2038   if [ $make_final_dest_iso -eq 1 ]; then
2039
2040     # make an iso image out of our directory
2041     make_dvd_iso_image_from_folder "$dest/$dvdname" "$dest/$dvdname.iso" 0
2042    
2043     # If the mkisofs was unable to make a .iso file for us, don't remove the DVD directory 
2044     if [ -s "$dest/$dvdname.iso" ]; then
2045       if [ $make_final_dest_folder -eq 0 ]; then
2046         echo "-> Removing DVD folder since ISO was created: $dest/$dvdname" | tee -a "$logfile"
2047         # remove the folder of the DVD image now that we have a .iso version of it
2048         [[ -d "$dest/$dvdname" ]] && rm -rf "$dest/$dvdname"
2049       fi
2050     else
2051       # we created an empty iso file, remove it
2052       echo "-> Removing empty ISO image: $dest/$dvdname.iso" | tee -a "$logfile"
2053       echo "-> Keeping the DVD folder since the ISO image couldn't be created properly: $dest/$dvdname"
2054       [[ -e "$dest/$dvdname.iso" ]] && rm "$dest/$dvdname.iso"
2055     fi
2056  
2057     # add this video data to the mythtv DB
2058     fill_mythvideo_metadata "$dest/$dvdname.iso" 
2059
2060   fi
2061
2062   fi
2063
2064   # remove the ddrescue DVD ISO image
2065   remove_intermediate_iso_file
2066
2067   # remove the tmp dvdbackup folder of the DVD image
2068   remove_intermediate_dvdbackup_folder
2069
2070   # eject the DVD disk upon completion
2071   [ $eject_disk -eq 1 ] && eject -T $dev
2072
2073   date=`date`
2074   echo "$date DVD rip completed" | tee -a "$logfile"
2075
2076   if [[ -n "$mailto" ]]; then
2077     cat "$logfile" | mailx -s "dvd rip of $dvdname DONE" "$mailto"
2078   fi
2079
2080 fi
2081
2082 ##############################################################################################