How-To: Automate DVD Backup w/ FairMount & HandBrake

HandBrake for Mac support
Forum rules
An Activity Log is required for support requests. Please read How-to get an activity log? for details on how and why this should be provided.
mrsteveman1
Posts: 1
Joined: Mon Dec 29, 2008 9:22 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mrsteveman1 »

It appears as if the applescript routine for grabbing the number and name of the dvds in the system drives:

Code: Select all

tell application "System Events" to set DVDs to name of disks whose capacity is less than 8.589934592E+9


fails when a fuse volume or in my case a truecrypt volume is mounted. I am not sure what is causing it, but it consistently fails when a TC volume is mounted. I tried changing the line that detects the dvd name to use filesystem detection (udf), and ejectable status, neither one causes it to work. Running the countDisks routine in another applescript by itself throws out some kind of applescript error, so it isn't a matter of getting the wrong volume name back, applescript just can't get anything for some reason because the TC volume is mounted.
ShellyFM
Posts: 3
Joined: Sat Jan 03, 2009 9:24 am

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by ShellyFM »

mnbearfan wrote:Cool!

You can download it from my website (I don't think we can post files here. If we can I'm happy to post it here.) When I'm happier with it and the code, I'll be happy to provide the xcode project files to anyone who is interested. At this point the code is fairly (and embarrassingly) messy and lacking in useful comments :-)

I'd appreciate any and all feedback. I'm just crossing my fingers hoping it actually works for you! If you have ideas, suggestions or anything please let me know! Just some things to know. You need the newest versions of VLC, HandbrakeCLI and Fairmount installed. Try running it before you install any or all of them and you should get an error message. Also, if anything fails, make sure it created the folders BatchRip and BatchEncode in your movies folder. I think I have that working right... Other than that I'm not sure what problems you might encounter - I guess we'll see! :-)

Oh and it requires 10.5 - I didn't try compiling for 10.4.

http://web.mac.com/ijohn/iWeb/BackupandEncode.zip
I love the idea of your application. However, on the "Preparing for encoding" step, I always get this error:

AppleScript Error
Can't made "d" into type integer. (-1700)

Any suggestions on how to make it work for me? Have you decided to release the source code yet?

Thanks!
theng
Posts: 1
Joined: Tue Jan 06, 2009 3:04 am

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by theng »

mnbearfan wrote:So I have things working until the encode step. I'm using your newest Handbreak CLI script. But when I try running it, I'm getting the following errors. I'm looking at the script but am not understanding why it would throw up errors on these lines in the script. For the most part, these lines appear to be setting variables, so I don't quite understand why it's bombing out with command not found. More worrisome are the last two errors. Any ideas what might be causing me problems? This is otherwise excellent! I'm actually thinking about a way to combine all of this into one script/Applescript Studio app for full automation. I've got the backup part working automatically as soon as a DVD is inserted (but without having to set this app as the default action for a DVD insertion, which I don't want to have to change every time I might want to watch a movie.) This way I can just launch the app and it will recognize when the DVD is inserted. Now I'm thinking through how to connect that action to the encoding action. I haven't thought that all the way through yet since I don't have the manual process working yet :-)

/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 105:   : command not found
/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 106:  : command not found
/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 107:  : command not found
/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 111:   : command not found
/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 114:   : command not found
/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 117:   : command not found
/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 118:   : command not found
/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 125: syntax error near unexpected token `then'
/path_to/BatchScripts/HandBrakeCLI-batch.sh: line 125: `   if [ -z "$1" ]; then'
This is due to the browser inserting windows line breaks at the end of the lines. To fix this save the file as plain text as mentioned in the tutorial then do this:
1. Open up terminal
2. Open up vim: "vim HandBrakeCLI-batch.sh"
3. Type in: ":set fileformat=mac" <enter>
4. Save the file ":w" <enter>
5. Reload the file ":e" <enter>
6. You should see thes cript with no line breaks and a whole bunch of ^M between lines. We want to replace these so:
7. ":%s/[^M]$//" <enter> Nothing will appear to change
8. Reset the file format ":set fileformat=mac" <enter>
9. Save and reload it again. ":w" <enter> ":e" <enter> The text should look normal again.
10. Exit vim ":q"

Continue with the other instructions, the script should now work (don't forget chmod 777)

Hope this helps.
Northy
Enlightened
Posts: 134
Joined: Fri May 16, 2008 1:06 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by Northy »

Wow very good guide I'll try it tomorrow :D
mrklaw
Posts: 8
Joined: Mon Jan 12, 2009 2:22 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mrklaw »

A lot to digest, but sounds fantastic.

I already have the ripping up and running and seeming to work fine so far, and have added the encoding but haven't tested yet. Couple of questions if I may:

1) how easy is it to change the ripping and encoding folders? I only have a mini with 120GB HDD so would only be able to rip about 7-8 discs before it was full. The media will end up on an iomega minimax firewire drive anyway, so how would I change that? Ideally I'd rip and encode there. eg to the same folder names but in the root of 'iomega minimax:' Plus then moving it to the final location (on the same drive) would be very quick.

2) I have quite a few Japanese DVDs that I'd want english subtitles including on. Should I just manually encode these with 'force subtitles'? Is the CLI script smart enough to know not to kick off encoding if there is already a job happening? I'd probably use handbrake GUI to do those though so it might not catch them. I suppose I could always make sure the rip folder is empty before the ical reminder kicks in.
iJoel
Enlightened
Posts: 124
Joined: Sat Dec 20, 2008 7:25 am

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by iJoel »

In the HandBrakeCLI-batch.sh, is there a way to have it encode the longest title?
Or a specific title? Instead of just the "minimum get time" option?

Is there any real benefit of using it beside the whole, processing one DVD TS_Video after another, and specifying
a minimum get title time?

Cause I don't think it's flexible enough for me, so I think I'm going to write my own,
what do you think? ;)
mrklaw
Posts: 8
Joined: Mon Jan 12, 2009 2:22 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mrklaw »

I'd like to know if there is anyway to get handbrake CLI to select audio by language. For my specific needs, I've set up two copies of the rip script to rip the DVDs to two different locations - one for normal DVDs, and one for anime. These are then assigned in remote buddy to my PS3 remote control. So I put a DVD in and press L1 to rip an English DVD, and R1 to rip a Japanese DVD.

I'd like to match that up with two batchencode scripts - one as it stands for the normal DVDs, and the other to use the universal preset, but selecting Japanese audio and english subs (and maybe adding deinterlace/decomb). Then I can set alternating ical reminders so it does english rips on eg mon/wed/fri and Japanese DVDs on Tues/Thurs.

I just need the string to put in the batchencode script to replace the universal preset one. How should it look if I want eg the first audio track and english subs? I can check the DVDs and see if they all have Japanese as the first audio track.
mac.jedi
Enlightened
Posts: 108
Joined: Thu Apr 24, 2008 11:17 pm

Updated Scripts.

Post by mac.jedi »

ANNOUNCEMENT!
The tutorial instructions and scripts have been updated.

Changes:
BatchRip, BatchEncode and the HandBrakeCLI-batch.sh have been updated to correctly parse spaces in the directory tree
BatchEncode now displays progress through Terminal and saves output to a text file.

Thx.

batchRip.scpt

Code: Select all

---------- BatchRip.scpt ----------
---------- Updated: 01-22-2009 ----------

(* This script opens DVDs with FairMount and copies them to a destination folder with a ditto shell script. This script includes support for dual DVD drives installed in a Mac Pro, if two disks are inserted. This script also uses Growl to notify you when completed *)

global diskCount, dvd1Src, dvd1copy, dvd2src, dvd2copy

---------- Properties ----------

-- The output directory for all DVD files. Default is ~/Movies/BatchRip. This folder will be automatically created on first run.
property outputPath1 : "~/Movies/BatchRip"

-- Set ejectDisk to yes if you want your disk(s) to eject when completed. Default is no.
property ejectDisk : no

---------- Optional Properties ----------

-- Dual-Drive: If you have two DVD Drives, you can set a second output directory below to rip two disks at once. The default is ~/Movies/BatchRip2. This folder will be automatically created if 2 disks are mounted and the script is executed.
property outputPath2 : "~/Movies/BatchRip2"

-- Setup Growl Support: Set useGrowl to yes and set the path to the GrowlNotifyLib.scpt.
property useGrowl : no -- If you have growl, set to yes. Default is no.
property growlTitle : "Batch Rip"
property growlLibraryPath : POSIX file "Users/userloginname/Movies/BatchScripts/GrowlNotifyLib.scpt" -- Set the path to the GrowlNotifyLib.scpt.

---------- Batch Script ----------

try
	tell application "FairMount.app" to launch
	delay 20
	countDisks()
	copyDisks()
	tell application "FairMount.app" to quit
end try

---------- Sub-routines ----------

on countDisks()
	try
		if useGrowl is yes then setGrowl(growlTitle) of (load script growlLibraryPath)
	end try
	try
		tell application "System Events" to set DVDs to name of disks whose capacity is less than 8.589934592E+9
		set diskCount to count of DVDs
		set dvd1Src to quoted form of (POSIX path of item 1 of DVDs)
		set dvd1copy to escapePath(outputPath1 & "/" & item 1 of DVDs)
		set dvd2src to quoted form of (POSIX path of item 2 of DVDs)
		set dvd2copy to escapePath(outputPath2 & "/" & item 2 of DVDs)
	end try
end countDisks

on escapePath(outputPath)
	set the search_string to " "
	set the replacement_string to "\\ "
	set AppleScript's text item delimiters to the " "
	set the text_item_list to every text item of the outputPath
	set AppleScript's text item delimiters to the replacement_string
	set the new_item_name to the text_item_list as string
	set AppleScript's text item delimiters to ""
	set the outputPath to new_item_name
end escapePath

on copyDisks()
	if diskCount is less than 2 then
		mkDir(outputPath1)
		do shell script "ditto " & dvd1Src & " " & dvd1copy
		cleanUp(dvd1Src, dvd1copy)
	else
		mkDir(outputPath1)
		mkDir(outputPath2)
		do shell script "ditto " & dvd1Src & " " & dvd1copy & " &> /dev/null & " & "ditto " & dvd2src & " " & dvd2copy
		cleanUp(dvd1Src, dvd1copy)
		cleanUp(dvd2src, dvd2copy)
	end if
end copyDisks

on mkDir(outputPath)
	do shell script "mkdir -p " & escapePath(outputPath)
end mkDir

on cleanUp(dvd, dvdcopy)
	try
		do shell script "chmod -R 755 " & dvdcopy
		if useGrowl is yes then set growlMessage to (characters (10 + 1) thru -2 of the dvd as string) & " has been copied."
		if ejectDisk is yes then do shell script "diskutil eject " & dvd
		if useGrowl is yes then growlMe(growlTitle, growlMessage) of (load script growlLibraryPath)
	end try
end cleanUp

---------- End Script ----------

HandBrakeCLI-batch.sh

Code: Select all

#!/bin/sh

#  UPDATED: 01-22-2009

#  HandBrakeCLI-batch.sh is a script to batch execute the HandBrakeCLI.
#  This script is based upon the MediaForkCLI-batch.sh.
#  Original Copyright (C) 2007  Brian Beardmore

#  Since MediaForkCLI has been replaced by HandBrakeCLI, some edits were required
#  to make it compatible with HandBrakeCLI. The changes are listed below:
#  - Changed toolName="HandBrakeCLI" to allow it to execute the HandBrakeCLI
#  - Added fileType=".mp4" to allow user to set output container from an external script
#  - Updated some of the introductory text to include references to HandBrakeCLI
#  - Updated script to correctly parse paths with spaces in the directory tree
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# This script requires HandBrakeCLI.sh tool.  The HandBrakeCLI.sh tool can
# be obtained from http://handbrake.fr

# This script searches the entire input directory directory tree looking
# for TS_VIDEO directories looking for DVDs to encode.  The output m4v
# filename is the DVD volume name.  When multiple tracks are to encoded 
# from a DVD, the output filename is appended with the track number.
# For example, 'Monsters, Inc.' DVD has both standard and wide screen tracks
# so there are 'Monsters, Inc.1.m4v' & 'Monsters, Inc.10.m4v' files created.
# For addition information on this script contact the scripts author,
# Brian Beardmore at medfk(at)realisticsoftware(dot)com or
# http://www.realisticsoftware.com

# Examples
# $ ./HandBrakeCLI-batch.sh
#   [ encodes all DVDs mounted and encodes any tracks longer then 60min ]
#   [ to the mp4 folder in the users Movies folder ]
# $ HandBrakeCLI-batch.sh -i ~/Movies -o toPod -b 1000 -w 576 --minGetTime 50
#   [ encodes all DVDs found in the users Movies folder and encodes any ]
#   [ tracks longer then 50min, with a 1000kb/s bitrate and scales the output ]
#   [ movie to a width of 576 pixels and puts the resulting mp4 files in the ]
#   [ toPod folder in the current directory that the command was executed from ]

# Usage: HandBrakeCLI-batch.sh [options]
#
#  arg1:   inputSearchDir=<string>   Set input directory to process all DVDs in it (example: ~/Movies/Batch Rip) "
#  arg2:   outputDir=<string>        Set output directory for all output files (example: ~/Movies/Batch Encode) "
#  arg3:   fileType=<string>         Set the file type: .mp4, .avi, .omg, .mkv, .m4v (example: .m4v) "
#  arg4:   minTrackTime=<number>     Set the minimum time (mins) of the track/s to encode (example: 30) "
#  arg5:   toolArgs=<string>         Set the HandBrakeCLI encode settings (example: -2 -w 640) "

#   HandBrakeCLI possible options
#  -u, --update            Check for updates and exit
#  -v, --verbose           Be verbose
#  -C, --cpu               Set CPU count (default: autodetected)
#  -f, --format <string>   Set output format (avi/mp4/ogm, default:
#                          autodetected from file name)
#  -t, --title <number>    Select a title to encode (0 to scan only,
#                          default: 1)
#  -c, --chapters <string> Select chapters (e.g. "1-3" for chapters
#                          1 to 3, or "3" for chapter 3 only,
#                          default: all chapters)
#  -a, --audio <string>    Select audio channel(s) ("none" for no 
#                          audio, default: first one)
#  -s, --subtitle <number> Select subtitle (default: none)
#  -e, --encoder <string>  Set video library encoder (ffmpeg,xvid,
#                          x264,x264b13,x264b30 default: ffmpeg)
#  -E, --aencoder <string> Set audio encoder (faac/lame/vorbis/ac3, ac3
#                          meaning passthrough, default: guessed)
#  -2, --two-pass          Use two-pass mode
#  -d, --deinterlace       Deinterlace video
#  -g, --grayscale         Grayscale encoding
#  -p, --pixelratio        Store pixel aspect ratio in video stream
#  -r, --rate              Set video framerate (5/10/12/15/23.976/24/25/29.97)
#  -R, --arate             Set audio samplerate (22.05/24/32/44.1/48 kHz)
#  -b, --vb <kb/s>         Set video bitrate (default: 1000)
#  -q, --quality <float>   Set video quality (0.0..1.0)
#  -Q, --crf               Use with -q for CRF instead of CQP
#  -S, --size <MB>         Set target size
#  -B, --ab <kb/s>         Set audio bitrate (default: 128)
#  -w, --width <number>    Set picture width
#  -l, --height <number>   Set picture height
#      --crop <T:B:L:R>    Set cropping values (default: autocrop)

# Revision history:
# 0.20070329.0 - initial release
# 0.20081125.0 - revised for HandBrakeCLI
# 0.20090122.0 - fixed problem with spaces in the directory tree


#############################################################################
# globals

# const global variables
scriptName=`basename "$0"`
scriptVers="2.0"
scriptPID=$$
saveDVDinfo=1       # the dvd track info is also saved as txt file when on
skipDuplicates=1    # if this option is off (-0),
                    # the new output files will overwrite existing files
E_BADARGS=65

# set the global variables to default
toolName="HandBrakeCLI"
toolPath="/Applications/$toolName"
toolTrackArgs="-t 0" # scans dvd title list for all tracks
inputSearchDir=$1    # set input search directory: "~/Movies/Batch Rip"
outputDir="$2"       # set output directory: "~/Movies/Batch Encode"
fileType="$3"        # set output container: .m4v, .mp4, .avi, .omg, .mkv
minTrackTime="$4"    # this is in minutes: "30"
toolArgs="$5"        # set handbrakecli encode settings: "-2 -w 640"

#############################################################################
# functions

verifyFindCLTool()
{
	# attempt to find the HandBrakeCLI if the script toolPath is not good
	if [ ! -x "$toolPath" ];
	then
		toolPathTMP=`PATH=.:/Applications:/:/usr/bin:/usr/local/bin:$HOME:$PATH which $toolName | sed '/^[^\/]/d' | sed 's/\S//g'`
		
		if [ ! -z $toolPathTMP ]; then 
			toolPath=$toolPathTMP
		fi
	fi	
}

displayUsageExit()
{
	echo "Usage: $scriptName [options]"
	echo ""
	echo "    -h, --help   Print help"
	echo "    arg1:   inputSearchDir=<string>   Set input directory to process all DVDs in it (example: ~/Movies/Batch Rip) "
	echo "    arg2:   outputDir=<string>        Set output directory for all output files (example: ~/Movies/Batch Encode) "
	echo "    arg3:   fileType=<string>         Set the file type: .mp4, .avi, .omg, .mkv, .m4v (example: .m4v) "
	echo "    arg4:   minTrackTime=<number>     Set the minimum time (mins) of the track/s to encode (example: 30) "
	echo "    arg5:   toolArgs=<string>         Set the HandBrakeCLI encode settings (example: -2 -w 640) "
	
	
	if [ -x "$toolPath" ];
	then
		echo "   $toolName possible options"
		mForkHelp=`$toolPath --help 2>&1`
		mForkHelpPt=`printf "$mForkHelp" | egrep -v '( --input| --output| --help|Syntax: |^$)'`
		printf "$mForkHelpPt\n"
	else
		echo "    The options available to HandBrakeCLI except -o  and -i"
		if [ -e "$toolPath" ];
		then
			echo "    ERROR: $toolName command tool is not setup to execute"
			echo "    ERROR: attempting to use tool at $toolPath"
		else
			echo "    ERROR: $toolName command tool could not be found"
			echo "    ERROR: $toolName can be install in ./ /usr/local/bin/ /usr/bin/ ~/ or /Applications/"
		fi
	fi
	
	echo ""
	
	exit $E_BADARGS
}

getTrackListLongerThan()
{
	# Two input arguments are are need. 
	#   arg1 is the time in minutes selector
	#   arg2 is the raw text stream from the track 0 call to HandBrake
	#   returns: a list of track numbers of tracks longer then the selector
	
	if [ $# -lt 2 ]; then
		return ""
	fi
	
	minTime="$1"
	shift
	allTrackText="$*"
	aReturn=""

	trackList=`eval "echo \"$allTrackText\" | egrep '(^\+ title |\+ duration\:)' | sed -e 's/^[^+]*+ //'g -e 's/title \([0-9]*\):/\1-/'g -e 's/duration: //'g"`
	
	trackNumber=""
	for aline in $trackList
	do
		trackLineFlag=`echo $aline | sed 's/[0-9]*-$/-/'`
		if [ $trackLineFlag = "-" ];
		then
			trackNumber=`echo $aline | sed 's/\([0-9]*\)-/\1/'`
		else
			set -- `echo $aline | sed -e 's/(^[:0-9])//g' -e 's/:/ /g'`
			if [ $3 -gt 29 ];
			then let trackTime=($1*60)+$2+1
			else let trackTime=($1*60)+$2
			fi

			if [ $trackTime -gt $minTime ];
			then aReturn="$aReturn $trackNumber"
			fi
		fi
	done
	
	echo "$aReturn"
}

makeFullPath()
{
   aReturn=""
   currentPath=`pwd`
   
   if [ $# -gt 0 ]; then
      inPath="$*"
      
      # put full path in front of path if needed
      aReturn=`echo "$inPath" | sed -e "s!~!$currentPath/!" -e "s!^./!$currentPath/!" -e "s!^\([^/]\)!$currentPath/\1!" -e "s!^../!$currentPath/../!"`
      
      # remove ../ from path - only goes 4 deep
      aReturn=`echo "$aReturn" | sed -e 's!/[^\.^/]*/\.\./!/!g' | sed -e 's!/[^\.^/]*/\.\./!/!g' | sed -e 's!/[^\.^/]*/\.\./!/!g' | sed -e 's!/[^\.^/]*/\.\./!/!g'`
      
      # cleanup by removing //
      aReturn=`echo "$aReturn" | sed -e 's!//!/!g'`
   fi
   
   echo "$aReturn"
}

isPIDRunning()
{
	aResult=0
	
	if [ $# -gt 0 ]; then
		txtResult="`ps ax | egrep \"^[ \t]*$1\" | sed -e 's/.*/1/'`"
		if [ -z "$txtResult" ];
		then aResult=0
		else aResult=1
		fi
	fi
	
	echo $aResult
}

#############################################################################
# MAIN SCRIPT

# initialization functions
verifyFindCLTool

# fix input and output paths to be full paths
inputSearchDir=`makeFullPath "$inputSearchDir"`
outputDir=`makeFullPath "$outputDir"`

# see if the output directory needs to be created
if [ ! -e $outputDir ]; then
	mkdir -p "$outputDir"
fi

# sanity checks
if [[ ! -x $toolPath || ! -d $inputSearchDir || ! -d $outputDir || -z "$toolArgs" ]]; then
	displayUsageExit
fi

# display the basic setup information
echo "$scriptName $scriptVers"
echo "  Start: `date`"
echo "  Input directory: $inputSearchDir"
echo "  Output directory: $outputDir"
echo "  File type: $fileType"
echo "  Minimum get track time: $minTrackTime mins"
echo "  Tool path: $toolPath"
echo "  Tool args: $toolArgs"
echo "  - - - - - - - - - - - - - - - -"

# find all the DVD videos in the input search directory tree
# spaces in file path temporarily become /008 and paths are separ with spaces
dvdTSVidList=`find "$inputSearchDir" -name VIDEO_TS -print0 | tr ' ' '\007' | tr '\000' ' '`

# process each DVD video found
for dvdTSDir in $dvdTSVidList
do
	# correct the tmp char back to spaces in the DVD file paths
	dvdTSDir=`echo $dvdTSDir | tr '\007' ' '`
	
	# get the DVD's name and path to root of the DVD
	dvdVolPath=`dirname "$dvdTSDir"`
	dvdName=`basename "$dvdVolPath"`
	dvdNameALNUM=`basename "$dvdVolPath" | sed 's/[^[:alnum:]^-^_]//g'`
	
	# display information
	echo "  * Processing DVD '$dvdName'"
	
	# create tmp link to the dvdVolPath to workaround a problem that the
	# HandBrakeCLI tool has a problem with the input file paths with space
	# when in a script
	tmpNoSpacePath="/tmp/dvdVol-$dvdNameALNUM-$scriptPID"
	ln -s "$dvdVolPath" $tmpNoSpacePath
	
	# get the track list information from the DVD
	cmd="$toolPath -i $tmpNoSpacePath $toolTrackArgs /dev/null 2>&1"
	dvdTrackInfo=`eval $cmd`
	# save the DVD info
	outputFilePath="$outputDir/${dvdName}_Info.txt"
	if [ $saveDVDinfo -eq 1 ]; then
		if [[ ! -e  $outputFilePath || skipDuplicates -eq 0 ]]; then
			echo "$dvdTrackInfo" | egrep '[ \t]*\+' > "$outputFilePath"
		fi
	fi
	# get the track number of tracks which are longer then the time desired
	trackFetchList=`getTrackListLongerThan $minTrackTime "$dvdTrackInfo"`
	if [ ! -z "$trackFetchList" ];
	then
		echo "   Will encode the following tracks: `echo $trackFetchList | sed 's/ /, /g'` "
	else
		echo "   No tracks on this DVD are longer then the minimum track time setting"
	fi
				
	trackCount=`echo $trackFetchList | wc -w`
	for aTrack in $trackFetchList
	do
		if [ $trackCount -gt 1 ]
			then outputFilePath="$outputDir/${dvdName}${aTrack}$fileType"
			else outputFilePath="$outputDir/${dvdName}$fileType"
		fi
		cmd="$toolPath -i $tmpNoSpacePath $toolArgs -t $aTrack -o \"$outputFilePath\" > /tmp/${dvdNameALNUM}Results.txt 2>&1"
		
		if [[ ! -e  $outputFilePath || skipDuplicates -eq 0 ]];
		then
			# simple command execution
			#ripResult=`eval $cmd`
			
			# background command execution with some status
			eval $cmd &
			cmdPID=$!
			while [ `isPIDRunning $cmdPID` -eq 1 ]; do
				cmdStatusTxt="`tail -n 1 /tmp/${dvdNameALNUM}Results.txt | grep 'Encoding: '`"
				if [ ! -z "$cmdStatusTxt" ]; then
					echo -n "$cmdStatusTxt"
				fi
				sleep 1s
			done
			echo ""
			wait $cmdPID
			
		else
			echo "   Output file SKIPPED because it ALREADY EXISTS"
		fi
		
		if [ -e /tmp/${dvdNameALNUM}Results.txt ]; then
			rm /tmp/${dvdNameALNUM}Results.txt
		fi
	done

	rm $tmpNoSpacePath
done

echo "  - - - - - - - - - - - - - - - -"
echo "  End: `date`"

exit 0


# End Script

batchEncode.scpt

Code: Select all

---------- BatchEncode.scpt ----------
---------- Updated: 01-22-2009 ----------


global batchScript1, batchScript2

---------- Properties ----------

-- The input directory to process all DVDs (TS Folders) in it. Default is: ~/Movies/BatchRip. This folder will be automatically created on first run, but the script will fail since there isn't anything in the folder.
property inputPath1 : "~/Movies/BatchRip"

-- The output directory for all output files. Default is: ~/Movies/BatchEncode. This folder will be automatically created on first run.
property outputPath : "~/Movies/BatchEncode"

-- The path to your HandBrakeCLI-batch.sh script. Default is: ~/Movies/BatchScripts/HandBrakeCLI-batch.sh
property scriptPath : "~/Movies/BatchScripts/HandBrakeCLI-batch.sh" -- Insert the path to HandBrakeCLI-batch.sh.

-- Set your HandBrakeCLI encode settings.  Default is the Universal preset, HandBrake's universally compatible, full resolution settings for all current Apple devices: iPod, iPhone, AppleTV, and Macs). For more info in setting parameters, visit http://handbrake.fr and read the CLI Guide Wiki. 
property encodeSettings : "--preset=\"Universal\"" -- Note: you must escape quotes for presets. 

-- Set the minimum time (minutes) of the track/s to encode (default: 20)
property minGetTime : "20"

---------- Optional Properties ----------

-- Dual-Encode: If you have a fast multi-core processor and hard disk, you can setup two batch folders to encode two RIPs at once. 
property batchFolders : 1 -- If adding a second input directory, change number of batch folders to 2. 
property inputPath2 : "~/Movies/BatchRip2" -- Set second input directory to process all DVDs in it. Default is: ~/Movies/BatchRip2. This folder will be automatically created if the batchFolders property is set to 2.

-- Output Container: This script's default output container is .m4v(mp4). HandBrake can also save files in: .mkv, .avi, and .ogm.
property fileType : ".m4v"

-- Setup Growl Support: Set useGrowl to yes and set the path to the GrowlNotifyLib.scpt.
property useGrowl : no -- If you have growl, set to yes.
property growlTitle : "Batch Encode"
property growlMessage : "Your HandBrake Encodes Are Done!"
property growlLibraryPath : POSIX file "Users/userloginname/Movies/BatchScripts/GrowlNotifyLib.scpt" -- Set the path to the GrowlNotifyLib.scpt.

---------- Encode Script ----------

try
	if useGrowl is yes then setGrowl(growlTitle) of (load script growlLibraryPath)
end try
try
	createBatchScript()
	mkDir(inputPath1) & mkDir(outputPath)
	if batchFolders is 2 then mkDir(inputPath2)
	with timeout of 36000 seconds
		doScript()
		growlMe(growlTitle, growlMessage) of (load script growlLibraryPath)
	end timeout
end try

---------- Sub-routines ----------
to doScript()
	tell application "Terminal"
		activate
		tell application "System Events" to keystroke "n" using {command down}
		if batchFolders is 2 then repeat 1 times
			tell application "System Events" to keystroke "t" using {command down}
		end repeat
		do script batchScript1 in tab 1 of window 1
		if batchFolders is 2 then do script batchScript2 in tab 2 of window 1
		repeat until tab 1 of window 1 is not busy
			delay 4
		end repeat
		if batchFolders is 2 then repeat until tab 2 of window 1 is not busy
			delay 4
		end repeat
	end tell
end doScript

to setInput(batchFolder)
	set inputDir to quoted form of batchFolder
end setInput

to createBatchScript()
	set spc to " "
	set inputDir1 to setInput(inputPath1)
	set inputDir2 to setInput(inputPath2)
	set logFile to " | tee " & escapePath(outputPath)
	set outputDir to quoted form of outputPath
	set batchScript1 to escapePath(scriptPath) & spc & inputDir1 & spc & outputDir & spc & quoted form of fileType & spc & quoted form of minGetTime & spc & quoted form of encodeSettings & logFile & "/BatchEncode.log"
	set batchScript2 to escapePath(scriptPath) & spc & inputDir2 & spc & outputDir & spc & quoted form of fileType & spc & quoted form of minGetTime & spc & quoted form of encodeSettings & logFile & "/BatchEncode2.log"
end createBatchScript

on escapePath(outputPath)
	set the search_string to " "
	set the replacement_string to "\\ "
	set AppleScript's text item delimiters to the " "
	set the text_item_list to every text item of the outputPath
	set AppleScript's text item delimiters to the replacement_string
	set the new_item_name to the text_item_list as string
	set AppleScript's text item delimiters to ""
	set the outputPath to new_item_name
end escapePath

on mkDir(somepath)
	do shell script "mkdir -p " & escapePath(somepath)
end mkDir

---------- End Script ---------
Last edited by mac.jedi on Sun Jan 25, 2009 9:01 pm, edited 2 times in total.
mac.jedi
Enlightened
Posts: 108
Joined: Thu Apr 24, 2008 11:17 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mac.jedi »

iJoel wrote:In the HandBrakeCLI-batch.sh, is there a way to have it encode the longest title?
Or a specific title? Instead of just the "minimum get time" option?

Is there any real benefit of using it beside the whole, processing one DVD TS_Video after another, and specifying
a minimum get title time?

Cause I don't think it's flexible enough for me, so I think I'm going to write my own,
what do you think? ;)
You can set any encoding parameter HandBrakeCLI can do in the encodeSetting property, including a specific title (-t 1), to just scan the titles (-t 0). Here is a link to the CLI wiki that shows all the options: http://trac.handbrake.fr/wiki/CLIGuide#options
iJoel
Enlightened
Posts: 124
Joined: Sat Dec 20, 2008 7:25 am

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by iJoel »

mac.jedi wrote:
iJoel wrote:In the HandBrakeCLI-batch.sh, is there a way to have it encode the longest title?
Or a specific title? Instead of just the "minimum get time" option?

Is there any real benefit of using it beside the whole, processing one DVD TS_Video after another, and specifying
a minimum get title time?

Cause I don't think it's flexible enough for me, so I think I'm going to write my own,
what do you think? ;)
You can set any encoding parameter HandBrakeCLI can do in the encodeSetting property, including a specific title (-t 1), to just scan the titles (-t 0). Here is a link to the CLI wiki that shows all the options: http://trac.handbrake.fr/wiki/CLIGuide#options

Thanks ^__^.
I was just wondering if the HandBrakeCLI-batch.sh overwrote the -L option of the CLI since it seemed to want to check all the titles and their lengths, but looks like it won't ha ^__^.
mrklaw
Posts: 8
Joined: Mon Jan 12, 2009 2:22 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mrklaw »

the encode script uses the first audio track, so if I want a version with English burnt subs, and the first language track is Japanese (should be but I'll check), then can I just add "-N eng" somewhere in the parameters? Then it won't match the language of the audio track (Japanese) and so will select english subs? Does it matter where in the parameters I put it?

And does the script set the decomb flag? I'd like to include that as most of the Japanese stuff is animation so might have issues.
mac.jedi
Enlightened
Posts: 108
Joined: Thu Apr 24, 2008 11:17 pm

How to: Automate Blu-Ray Backup with tsMuxeR and HandBrakeCL

Post by mac.jedi »

How to: Automate Blu-Ray Backup with tsMuxeR and HandBrakeCLI

Thought this might be deserving of it's own thread:

http://forum.handbrake.fr/viewtopic.php?f=5&t=9083
mrklaw
Posts: 8
Joined: Mon Jan 12, 2009 2:22 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mrklaw »

trying the latest script, and I've added a couple of additional options to the batch encode script, so it reads

"--preset=\"Universal\" -2 -T -N eng --decomb"

so for my Japanese anime it should select english subs and decomb. I'm testing on one DVD to check it all works before automating it with iCal, and so far its taken nearly 3 hours, with an ETA of over an hour more - approx 4hrs in total! The original movie (kiki's delivery service) is 103mins, and I'm using a mac mini 2.0GHz with 2GB ram, nothing else of any substance running on it. This seems unusually long - is there anything in the parameters I'm passing that will slow it down significantly compared to a standard preset? does the -2 mean its doing a 2 pass now? (the old script didn't have that I don't think)

If its going to take 4 hours per movie then there is almost no point automating the ripping, as I can't have more than 2 DVDs queued up to process or it'll be encoding during the evening when I will want to watch things (use the mini for plex to view the rips). (don't do it overnight as that is set aside for newsgroups downloads as its unmetered by my ISP)
mac.jedi
Enlightened
Posts: 108
Joined: Thu Apr 24, 2008 11:17 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mac.jedi »

Sorry, I must have include this on accident. The -2 is two-pass, and -T is turbo first pass. You can delete them from your args if you don't want it. I always use it because I encode on an 8-core Mac Pro and it doesn't really seem to matter for me.
mrklaw
Posts: 8
Joined: Mon Jan 12, 2009 2:22 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mrklaw »

thanks.

does your script with the terminal output create an 'sh' process? checking my activity monitor there is an 'sh' process whose parent is 'bash' which is taking 30+ CPU, which is quite a chunk, leaving handbrake with only 150 compared to the 190ish it usually has at its disposal. Nothing else obvious running at the moment.
mac.jedi
Enlightened
Posts: 108
Joined: Thu Apr 24, 2008 11:17 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mac.jedi »

The "sh" is the shell script that's doing the automation and sending the info to hbcli.
coggsburn
Posts: 5
Joined: Wed Feb 04, 2009 5:04 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by coggsburn »

Dunno what I'm doing wrong...

Annie Hall encoded using the above method returns an image size of 561x304 using the AppleTV preset. Using the Handbrake GUI, it says the output image will be 720x352 with the same AppleTV preset.

Any thoughts as to why this would happen?
sdblair
Posts: 1
Joined: Thu Feb 05, 2009 8:02 am

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by sdblair »

Great work!

I set this up and it worked on the first try, except that my MBP would be locked up every morning!

I updated all the scripts to the latest versions and looked through them. I noticed this line:

Code: Select all

property growlLibraryPath : POSIX file "Users/userloginname/Movies/BatchScripts/GrowlNotifyLib.scpt" -- Set the path to the GrowlNotifyLib.scpt.
in the batchEncode.scpt, which I edited to contain my user name instead of "userloginname" (duh). Now it works AND my MBP is fine in the morning!

I also added the folder action script for adding new movies to iTunes. I guess this script is set to add programs as TV shows (?) because it added my movie to the TV playlist. I did a "get Info" in iTunes on it and I don't see where this property can be changed. I tried to drag it to the Movie playlist, but it won't take it.
sonicisblue
Posts: 1
Joined: Sat Feb 07, 2009 6:05 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by sonicisblue »

I'm curious... Is it possible to set a maximum time limit to encode? Some of my dvds of tv series have individual episodes (around 25 minutes), but then they also have one longer track (around 2.5 hours) of all the episodes put together... Obviously when I set this to encode automatically I want it to encode the smaller files, but I don't want it to waste time encoding the large file as well. So back to my original question, is it possible to set a maximum time to encode?
Omne666
Posts: 1
Joined: Tue Feb 10, 2009 10:55 am

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by Omne666 »

Ok people...need some help.

Not used to using terminal and am having trouble using the chmod 777 command to modify the HandBrakeCLI-batch.sh file...strangely getting a "no such file or directory" result. I tried to drag the file to the window but it wouldn't 'stick' so I have no idea what to do here. I have check and rechecked my path to ensure that wasn't the error butt it all seems fine to me. I even cd to the directory and just ran chmod 777 on the file name. Still no go. Changed the filename to test.sh for simplicity sake...same error.

One thing I do not have is the "HandBrakeCLI-batch.sh tool". What is this and where EXACTLY can I find it? Did a search on the Handbrake site to no avail! And is this the cause of it?
Mr.Becks
Posts: 1
Joined: Sun Feb 22, 2009 5:06 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by Mr.Becks »

Hi all,
I have got three questions. After reading all of this thread it worked! I made some mistakes but right now I am able to rip my dvds and moreover I can encode them. But there are three things I can't explain. Hopefully someone here can help me.

1. While encoding, the terminal jumps between diffenrent conditions. It says "Terminal -sleep- 80x24" or "Terminal -HandBrakeCLI- 80x24". What does that mean?
2. I've got a dual core imac. Because of that fact I decided to chose bathfolders:2. But it still encodes only one DVD at a time. Any ideas?
3. Growl doesn't work. No messages, nothing. I installed it like you explained it. Do i need a special version?

Would be really great if someone could help me.

Mr.Becks
rockrabbit
Posts: 5
Joined: Tue Feb 24, 2009 3:55 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by rockrabbit »

First off, this is absolutely fantastic! Bravo to everyone involved in creating not only HB, but this wonderful how-to!

The question I have is as follows, I'm trying to encode all my nephews Spongebob SquarePants DVD's.

When I use the GUI I can select each chapter (episode) and encode accordingly, but when I try the CLI I get one file of all the chapters.

Being somewhat new to all of this, is there a setting in the encode script that I need to change to get individual episodes?

Being able to automate the entire collection manually would be insanity.. just like Spongebob!

Many thanks!

RR
mac.jedi
Enlightened
Posts: 108
Joined: Thu Apr 24, 2008 11:17 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by mac.jedi »

rockrabbit wrote: Being somewhat new to all of this, is there a setting in the encode script that I need to change to get individual episodes?
Hi rockrabbit,

I'm not familiar with the way the spongebob dvd's are set up, but most tv show dvd's have each episode as a separate Title, not Chapter. The encode script is designed to encode each Title over a specified length. You can change the minimum length in the script and it'll encode each Title longer than what you set. I set it to 20 minutes, if I'm doing half-hour comedies, but change it 40 minutes for drama's and movies (to avoid encoding special features).

If you need to encode specific chapters, you can add the -c or --chapters option to your encode settings and set the chapters you want to encode. I know it will encode a specific chapter and a range of chapters, but I don't know if it'll encode more than one chapter, each as a separate file. More info on CLI options can be found in the wiki http://trac.handbrake.fr/wiki/CLIGuide

I hope this helps. Thanks!
crmarvi42
Posts: 2
Joined: Sun Mar 01, 2009 4:15 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by crmarvi42 »

I seem to have run into a roadblock in getting the BatchEncoding to work. I've gone so far as to trash the files from my first attempt and create them again changing only the "username" to "josh" and the encoding preset from "Universal" to "AppleTV" (and i remembered to escape the quotes for presets) with no luck. I keep getting this series of errors on the terminal:
  • Ender:~ josh$ ~/Movies/BatchScripts/HandBrakeCLI-batch.sh '~/Movies/BatchRip' '~/Movies/BatchEncode' '.m4v' '20' '--preset="AppleTV"' | tee ~/Movies/BatchEncode/BatchEncode.log
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 107:  : command not found
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 108:  : command not found
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 109:  : command not found
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 116:  : command not found
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 117:  : command not found
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 118:  : command not found
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 119:  : command not found
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 120:  : command not found
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 132: syntax error near unexpected token `then'
    /Users/josh/Movies/BatchScripts/HandBrakeCLI-batch.sh: line 132: `      if [ ! -z $toolPathTMP ]; then '
Since these appear similar to the errors seen previously I took the advice of Theng and used VIM to try and replace the windows line breaks, but that hasn't helped at all. According to the line numbering in TextWrangler, the offending lines are (not familiar with shell scripts so I may be providing the wrong information):
  • 107 saveDVDinfo=1       # the dvd track info is also saved as txt file when on
    108 skipDuplicates=1    # if this option is off (-0),
    109                     # the new output files will overwrite existing files

    116 inputSearchDir=$1    # set input search directory: "~/Movies/Batch Rip"
    117 outputDir="$2"       # set output directory: "~/Movies/Batch Encode"
    118 fileType="$3"        # set output container: .m4v, .mp4, .avi, .omg, .mkv
    119 minTrackTime="$4"    # this is in minutes: "30"
    120 toolArgs="$5"        # set handbrakecli encode settings: "-2 -w 640"

    132 if [ ! -z $toolPathTMP ]; then
The Applescript to rip the DVD's worked fine. All of my problems seem to stem from the shell script which I do not understand in the least.
junkmail
Posts: 2
Joined: Mon Mar 02, 2009 4:03 pm

Re: How-To: Automate DVD Backup w/ FairMount & HandBrake

Post by junkmail »

Quick question regarding TV series...

I'm trying to rip the Xena series using the BatchRip script, but every DVD in the series has the same Title. The script is dumping EVERYTHING into the same Xena folder. Is there an easy way to make the BatchRip script put the separate DVDs into separate folders? I've currently altered the script to put a date/time stamp in the folder name so I can keep things in order, but think there must be a better way. Unfortunately, my Applescript is pretty weak.

Thanks...
Post Reply