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