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