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