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.
mac.jedi
Enlightened
Posts: 108
Joined: Thu Apr 24, 2008 11:17 pm

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

Post by mac.jedi »

Announcement

I've posted a new tutorial thread in the Mac forum:
How-To: Automate DVD & Blu-Ray (Backup, Encoding & Tagging)

I hoping this one will die a graceful death. :D

Enjoy!


How-To: Automating DVD Backup with FairMount, HandBrake and iTunes (Mac OS X 10.5.5)



Introduction

Backing up a DVD library can be an arduous, time consuming task. Using a GUI tool is a simple task if you do one occasionally, but a lot of us have been collecting DVD’s for over a decade and have amassed large collections that would take days, weeks, months or even years to complete.

In addition, if you’ve ever tried to encode an entire season of TV episodes you know how laborious a project this can be as well: Insert a disk, rip the disk, choose your encode settings, select and add each title to the queue, process the file, rinse and repeat for each of the disks in the season.

The good news is that most of these tasks can be easily scripted to remove the manual intervention required. You could rip and encode an entire series very easily with the help of automation. Just insert a disk and it will rip automatically. When done, pop in another. If you’ve got Mac Pro with dual DVD drives, pop in two and you’ll save yourself a trip. Set an iCal alarm, and at midnight HandBrakeCLI will encode each title over 20 minutes long to an universally compatible format. All you need to do now is the tagging, and you can script some that as well. You can even enable a folder action that would add the finished files to an iTunes Library on a remote mac mini. Virtually anything is possible with automation.

This tutorial follows the recommended approach of ripping your DVD media into VIDEO_TS files located on your hard drive. Then, encoding them to an iTunes compatible MP4 format. Next, tagging the files with metadata iTunes, FrontRow, AppleTV or other devices can manage. The workflow is broken up into components that can be used individually or together to create one simple batch workflow.

Image


Workflow Components
  • Batch Ripping with FairMount
  • Batch Encoding with HandBrakeCLI
  • Scripting TV Episode File Renaming for Automatic Tagging
  • Folder Actions for Adding to iTunes Libraries with Automatic Tagging


Managing Your Workflow Files

A well planned folder structure will make your workflow much easier to manage. Most of these scripts rely on consistent paths to the source and destination folders, as well as the scripts themselves. For most users, your files should be processed on your local hard disk. External drives can be used, but in some cases they may slow down the speed of your encoding.

For these tutorials, we'll use your ~/Movies folder as the container for our workflow files and folders. Keeping your workflow under this one directory will make this process much easier. You can then move your finished rips and encoded files to another drive after they are done.


Your Batch Folders
  1. Navigate to your ~/Movies folder.
  2. Create a New Folder and rename it BatchScripts. This folder will help keep your batch scripts organized and easy to access if called from another script.
  3. On first run, the BatchRip.scpt will create a folder named BatchRip. This folder will be used as the destination folder for your Video_TS files when copied from DVDs. This folder will also be the source folder for HandBrakeCLI.
  4. On first run, the BatchEncode.scpt will create a folder named BatchEncode. This folder will be the destination folder for your MP4/M4v files encoded with HandBrakeCLI.

About Growl Support

Growl v1.1.4
Growl is a free notification system for Mac OS X: it allows applications and scripts that support Growl to send you notifications.

The batchRip and batchEncode scripts both contain Growl support. The GrowlNotifyLib.scpt below is needed by these scripts to notify the Growl application. The script contains notifications for display, email and speech, but only display is enabled by default. To activate notification by email or speech, navigate to the Growl System Preferences and click enable in the script's application notification settings.
  1. Download and Install Growl. Then restart your computer.
  2. Select, Copy and Paste the GrowlNotifyLib script into a new Script Editor document.

    Code: Select all

    -- Growl Notify Script Library
    
    
    -- Setup Growl Notification: Adds script to Growl's application list 
    on setGrowl(growlTitle)
    	tell application "GrowlHelperApp"
    		set the allNotificationsList to ¬
    			{growlTitle & " Notification", growlTitle & " Email", growlTitle & " Speech"}
    		
    		set the enabledNotificationsList to ¬
    			{growlTitle & " Notification"}
    		
    		register as application ¬
    			growlTitle all notifications allNotificationsList ¬
    			default notifications enabledNotificationsList ¬
    			icon of application "Script Editor"
    	end tell
    end setGrowl
    
    
    -- Tells Growl to notify you when script is completed
    on growlMe(growlTitle, growlMessage)
    	tell application "GrowlHelperApp"
    		notify with name ¬
    			growlTitle & " Notification" title ¬
    			growlTitle & " Notification" description ¬
    			growlMessage application name growlTitle
    		
    		notify with name ¬
    			growlTitle & " Email" title ¬
    			growlTitle & " Email" description ¬
    			growlMessage application name growlTitle
    		
    		notify with name ¬
    			growlTitle & " Speech" title ¬
    			growlTitle & " Speech" description ¬
    			growlMessage application name growlTitle
    	end tell
    end growlMe
    ----------  End Script ----------
    
  3. Save the script in your "~/Movies/BatchScripts" folder as "GrowlNotifyLib.scpt"


Using AppleScript to Automate Ripping

This workflow uses several technologies to automate the ripping process. An AppleScript is triggered whenever a DVD is mounted (setup via the DVD preference pane). The script uses FairMount and VLC to decrypt and mount DVDs on your system. A ditto shell script copies the entire DVD to your hard drive. Optionally, if your have dual DVD drives, this script will allow two DVDs to copy at the same time into different folders. The script also includes Growl notification support.

What you need to get started
To complete this tutorial you will need to download and install the following applications:

FairMount v1.02
FairMount is a free tool that allows decryption of DVD content on the fly for a convenient access. FairMount does not perform the actual decryption, it simply forwards the data to VLC Media Player which is used for decryption - thus, VLC Media Player must be installed for FairMount to work.
Note: (there is no need to install DVDRemaster that comes with the package)

VLC Media Player v0.9.6
VLC media player is a free, open source multimedia player for various audio and video formats (MPEG-1, MPEG-2, MPEG-4, DivX, mp3, ogg, ...) as well as DVDs, VCDs, and various streaming protocols. VLC Media Player must be installed for FairMount to work.

Script Editor
The Script Editor is an application included with Mac OS X that allows editing and creating scripts using AppleScript. Scripts can be saved as plain text, scripts that open in Script Editor, or standalone applications (including droplets). Script Editor is located at /Applications/AppleScript/Script Editor.


Creating Your Batch Rip Script
  1. Select, Copy and Paste the batchRip script into a new Script Editor document.

    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 ----------
    
  2. Choose Script > Compile (Command-K)
  3. Follow the steps in the script to set the properties, if needed.
  4. Save the script in your ~Movies/BatchScripts folder as "batchRip.scpt"

Making Your Script the Default Action When a DVD is Inserted:
  1. Open System Preferences and click CDs & DVDs.
  2. Choose the action "Run Script…" from the DVD pop-up menu.

    Image
  3. Navigate and Choose your batchRip script.

    Image
  4. Close the window to save your settings.

Testing Your Batch Rip Automation
  1. Insert a DVD (or DVDs if you have a dual-drive system)

    Image
  2. The script will activate and automatically launch FairMount after a 20 second delay, then you'll see a graphic of cream cheese being spread on a bagel).

    Image
  3. The DVD will unmount and re-mount as a disk image.

    Image
  4. After a short delay, the DVD will start copying to your ~/Movies/BatchRip/ folder.

    Image
  5. FairMount will display the progress as well as any bad sectors it encounters.

    Note: Some DVD's may contain copy protection measures that will result in bad sectors and a failed rip using FairMount. For these situations, it may be necessary to rip the DVD with other software such as DVD2One where you can adjust the settings manually.
  6. If you've set up growl support, you will be notified by display, speech or email when completed.

    Image


Using a Batch Script to Automate HandBrake

What you need to get started
To complete this tutorial you will need to download and install the following applications:

HandBrakeCLI
HandBrake is an open-source, GPL-licensed, multiplatform, multithreaded DVD to MPEG-4 converter, available for MacOS X, Linux and Windows. The Command Line Interface version of HandBrake is a lot faster and more flexible than the MacGui. Using scripting you can automate HandBrakeCLI to encode your files as a background process using the same parameters you'd set in the GUI.

Script Editor
The Script Editor is an application included with Mac OS X that allows editing and creating scripts using AppleScript. Scripts can be saved as plain text, scripts that open in Script Editor, or standalone applications (including droplets). Script Editor is located at /Applications/AppleScript/Script Editor.


Install HandBrakeCLI
  1. Download and open the HandBrakeCLI disk image.

    Image
  2. Next, drag the HandBrakeCLI application from the disk image to your applications folder.
Creating the HandBrakeCLI Batch Script:

Originally developed by realisticsoftware.com, the MediaForkCLI-batch.sh is a script created to batch execute the MediaForkCLI tool. Since MediaForkCLI has been replaced by HandBrakeCLI, a few changes were needed to make it compatible. This shell script will batch encode an entire directory full of TS_Video source media to any desired output HandBrakeCLI can handle, including presets. It will also encode every track that is longer than the length you specify in the batch encode script, which is a great time saver for batch encoding TV Shows.
  1. Open TextEdit and create a new PLAIN TEXT document.
  2. Next, select, copy and paste the shell script below into your text file.

    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
    
  3. Save the file in your ~/Movies/BatchScripts folder as: HandBrakeCLI-batch.sh. If you're prompted, save using the .sh extension.
  4. Next we need to set the file permissions, open Terminal.app, type: chmod 777 ~/Movies/BatchScripts/HandBrakeCLI-batch.sh
  5. Hit enter. Alternatively, you can just drag the file to the terminal window after the chmod 777 with a space before the path.


Creating Your Batch Encode Script:

This AppleScript can be triggered by an iCal Alarm to run the HandBrakeCLI-batch.sh file with defined encoding parameters for HandBrakeCLI. Optionally, it allows for encoding two TS Folders simultaneously and has Growl support.
  1. Select, copy and paste the script below into a new Script Editor document.

    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 ---------
    
  2. Choose Script > Compile (CMD-K)
  3. Follow the steps in the script to set the properties, if needed.
  4. Save the script in your ~/Movies/BatchScripts folder as "batchEncode.scpt"

Setting An iCal Batch Encode Alarm
  1. Create a Calendar and name it (ex. Scripts)
  2. Select your new calender, create a New Event and name it (ex. Encode Alarm)
  3. Set the Start Time to the time you'd like your encodes to begin (ex. 12:00AM)
  4. Set the End Time to the Start Time + 1 minute (ex. 12:01AM)
  5. Set Repeat to "Every Day" (if you want it to run every night)
  6. Set End to "Never"
  7. Set Alarm to "Run Script"
  8. Below "Run Script", change "None" to "Other" and navigate to select your batchEncode.scpt
  9. Set Notification to "0 minutes before"

    Image
  10. Click Done.


    Note: If you sync your iCal calendars with other Macs, you will get an error message if the script is not installed on the other machines. To fix this, you will need to select the calendar containing your Batch Encode Alarm on the other Macs and choose File > Get Info > and check the box next to "Ignore Alarms".


TV Show Renamer Droplet

This script gets data from a plain text file you've named: show name_season#.txt (example: The Office_01.txt). This text file should contain only the episode names (one on each paragraph line) for this season only. This droplet will rename a sequential series of m4v files dropped on to it, so it is important your files are already named in order, they are usually already in order by the title number. The script will parse the file name and contents of the plain text file and rename the video files with the following file naming convention: Season#_Episode#(sequential)_Show Name_Episode Title.ext. The companion "Add to iTunes and auto-tag" script will parse these file names and insert the correct meta data automatically upon import to iTunes. You must save this file as an application in Script Editor in order to run the script when files are dropped on to it.


Creating Your TV Show Renamer Droplet:
  1. Create a plain text file for each season you've encoded and want to rename.
    1. a. Copy and paste an entire season of episode names into a txt file (one on each paragraph line). Only include the episode name.
      b. Save this as a plain text file and name it with the show name and season number (season three as shown in the following example): Show Name_03.txt

      Image
  2. Create the droplet
    1. Select, copy and paste the script below into a new Script Editor document.

      Code: Select all

      -- TV SHOW RENAMER SCRIPT
      (* This script gets data from a plain text file you've named: show name_season#.txt (example: The Office_01.txt). This text file should contain only the episode names (one on each paragraph line) for this season only. This droplet will rename a sequential series of m4v files dropped on to it, so it is important your files are already named in order, they are usually already in order by the title number. The script will parse the file name and contents of the plain text file and rename the video files with the following file naming convention: Season#_Episode#(sequential)_Show Name_Episode Title.ext. The companion "Add to iTunes and auto-tag" script will parse these file names and insert the correct meta data automatically upon import to iTunes. You must save this file as an application in Script Editor in order to run the script when files are dropped on to it. *)
      
      
      on open dropped_items
      	-- If you want to go directly to a certain folder every time, change the "default location alias" to the path to your episode list folder ("Macintosh HD:Users:Your Name:Documents:Episode Lists:)
      	set textInfo to choose file default location alias "Macintosh HD:Users:" with prompt "Choose file which contains the title list" without invisibles
      	set titleList to paragraphs of (read textInfo)
      	tell application "Finder" to set {name:txNm, name extension:txEx} to info for textInfo
      	set AppleScript's text item delimiters to "_"
      	
      	set txNm to text 1 thru ((count txNm) - (count txEx) - 1) of txNm
      	set showInfo to every text item of txNm
      	set txEx to "." & txEx
      	set AppleScript's text item delimiters to ""
      	set idx to 1
      	
      	repeat with i from 1 to count dropped_items
      		set {name:Nm, name extension:Ex} to info for (item i of dropped_items) as alias
      		if Ex is missing value then set Ex to ""
      		if Ex is not "" then
      			set Nm to text 1 thru ((count Nm) - (count Ex) - 1) of Nm
      			set Ex to "." & Ex
      		end if
      		tell application "Finder" to set name of item i of dropped_items to item 2 of showInfo & "_" & text -2 thru -1 of ("00" & (idx as string)) & "_" & item 1 of showInfo & "_" & item i of titleList & Ex
      		set idx to idx + 1
      	end repeat
      end open
      

      Optional: Change the default location path to the path to your "Episode Lists" folder if you'd like the prompt to automatically open to that folder.
    2. Save the script as an application: Choose File > Save As... > select Application from the File Format popup menu.
    3. Verify that no options are checked.

      Image
    4. Click Save.
  3. Rename your episode files
    1. Select the files you want to rename. Note: It is important your files are already named in order, they are usually already in order by the title number.
    2. Drag and drop the selected files onto the TV Show Renamer droplet.
    3. Navigate and select the text file you created in Step 1 from the dialog box.

      Image
    4. The episodes should automatically be renamed with the following file naming convention: Season#_Episode#(sequential)_Show Name_Episode Title.ext

      Image


Add to iTunes and Auto-tag Script

This AppleScript parses the video files' filenames, creates a playlist named AutoAdd on a remote machine, adds the file to the new iTunes playlist, tells iTunes to set the Episode or Movie name, season#, episode#, episodeID, Video Kind and Show Name. It then deletes the playlist leaving the files in their respective TV or Movie playlists.

This was created to be a folder action attached to a TV Shows and/or Movies Folder. The script is executed whenever new files are added to these folders.

Optional: If you keep your files on one machine and your iTunes Library is located on a remote machine (like a Mac Mini), you could edit this script to add the files the remote machine's iTunes Library. See the optional steps listed below.


Creating Your Script:
  1. Select, copy and paste the script below into a new Script Editor document.

    Code: Select all

    -- ADD TO ITUNES AND AUTO-TAG SCRIPT
    
    (* This AppleScript parses the video files' filenames, creates a playlist named AutoAdd on a remote machine, adds the file to the new iTunes playlist, tells iTunes to set the Episode or Movie name, season#, episode#, episodeID, Video Kind and Show Name. It then deletes the playlist leaving the files in their respective TV or Movie playlists.
    
    This was created to be a folder action attached to a TV Shows and/or Movies Folder. The script is executed whenever new files are added to these folders.
    
    OPTIONAL: If you are adding to remote computer's iTunes Library, you will need to make a couple edits to this script: 
    	1. Add the remMachine variable below. 
    	2. On the line: Tell application "iTunes", delete the "--" before "of machine remMachine" so it reads: tell application "iTunes" of machine remMachine.
    	3. Enable "Remote Apple Events" in the Sharing Preference Pane on the remote machine. For more info visit http://dougscripts.com/ *)
    
    on adding folder items to my_folder after receiving the_files
    	
    	global allRemPlaylists, remMachine
    	-- OPTIONAL: If you are adding to remote computer's iTunes Library
    	-- Change the remMachine to your remote machine's info:
    	set remMachine to "eppc://username:userpass@remote_ip.local"
    	(*
    where username is something like "doug",
    userpass is the password, 
    remote_ip is the IP address see in the remote
    machine's Sharing Pane, something
    like "192.168.2.1" or "your-remote-machine.local"
    Note: On some configurations an administrator username and password are needed.
    *)
    	
    	using terms from application "iTunes"
    		try
    			
    			-- OPTIONAL: If you are adding to remote computer's iTunes Library-
    			-- Edit the line below and delete the "--" before "of machine remMachine". It should read: tell application "iTunes" of machine remMachine
    			tell application "iTunes" --of machine remMachine
    				launch
    				
    				make new user playlist with properties {name:"AutoAdd"}
    				repeat with i from 1 to number of items in the_files
    					set this_file to (item i of the_files)
    					add this_file to playlist "AutoAdd"
    				end repeat
    				
    				(*
    				-- if you have iTunes set to 
    				--"Copy files to iTunes Music folder when adding to library"
    				-- then you might want to delete the original file...
    				-- if so, remove comments from this block and 
    				-- use the UNIX commands below to delete the file
    				
    				set the file_path to the quoted form of the POSIX path of this_file
    				do shell script ("rm -f " & file_path)
    				
    				*)
    				set userPlaylist to user playlist "AutoAdd"
    				set movieTracks to (tracks of userPlaylist)
    				repeat with movieTrack in movieTracks
    					set movieTrackName to name of movieTrack as string
    					set AppleScript's text item delimiters to "_"
    					set tokens to (every text item of movieTrackName) as list
    					
    					if the (count of items in tokens) > 1 then
    						set video kind of movieTrack to TV show
    						set season number of movieTrack to item 1 of tokens
    						set episode number of movieTrack to item 2 of tokens
    						set name of movieTrack to item 4 of tokens
    						set disc number of movieTrack to item 1 of tokens
    						set show of movieTrack to item 3 of tokens
    						set episode ID of movieTrack to ((item 1 of tokens as integer) * 100 + (item 2 of tokens)) as integer
    					end if
    					set comment of movieTrack to "original track name: " & movieTrackName
    				end repeat
    				delete user playlist "AutoAdd"
    			end tell
    		end try
    	end using terms from
    end adding folder items to
    
  2. Choose Script > Compile (CMD-K)


    Optional: If you are adding to are remote machine:
    1. Change the "remMachine" variable: Insert the remote machines's username, password and IP address (eppc://username:userpass@remote_ip.local)
    2. On the line: Tell application "iTunes", delete the "--" before "of machine remMachine" so it reads: tell application "iTunes" of machine remMachine.
    3. Enable Remote Apple Events on the remote machine:
      1. Open System Preferences and click Sharing.
      2. Turn on Remote Apple Events by checking the checkbox.
      3. Close the window to save your settings.
    [/color]
  3. Save the edited script as "Add to iTunes Auto-Tag.scpt"
  4. Move the script file to your Mac's main Folder Action Scripts folder (Macintosh HD/Library/Scripts/Folder Action Scripts/). Note: The script may not execute if located elsewhere on your system.


Enabling Folder Actions
  1. Right-Click (Control+Click) on the folder you want to attach the folder action to (ex. ~/Movies).
  2. Scroll to the bottom of the pop-up and Select More > Enable Folder Actions

    Image
  3. Right-Click (Control+Click) on the folder again and Select More > Attach a Folder Action

    Image
  4. Navigate and Choose your "Add to iTunes Auto-Tag.scpt"

    Image
  5. The script should now execute whenever files are added to this folder.

    Note: If you keep your movie files and TV files in separate folders, you may want to repeat these steps on your other media folders.
Last edited by mac.jedi on Tue Oct 20, 2009 5:02 pm, edited 10 times in total.
timmyt
Posts: 4
Joined: Sat May 10, 2008 7:22 pm

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

Post by timmyt »

This is amazing thank you, im getting a mac soon and have upwards of 200 DVDs to ecode this come in handy
Cavalicious
Moderator
Posts: 1804
Joined: Mon Mar 26, 2007 12:07 am

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

Post by Cavalicious »

Based on the amount of work that was put into this post...I believe it's work a sticky.
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 »

Post Edited:
This post originally included a step for changing the MP4 output container to M4V for 5.1 Dolby Digital output. This is now a property in the BatchRip.scpt and also allows HandBrakeCLI to save files in three other widely used containers: .mkv, .avi, and .ogm.
Last edited by mac.jedi on Thu Nov 27, 2008 7:48 am, edited 1 time in total.
FritzsCorner
Posts: 7
Joined: Mon May 14, 2007 4:12 am

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

Post by FritzsCorner »

I will give this a shot tonight! I am guessing there may be some slight tweaks that need to be made for the 0.9.3 release? I appreciate all the time and effort you put into this guide, it looks fantastic.
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 »

FritzsCorner wrote:I will give this a shot tonight! I am guessing there may be some slight tweaks that need to be made for the 0.9.3 release? I appreciate all the time and effort you put into this guide, it looks fantastic.
I tested it this morning with 0.9.3 and it worked fine. Keep an eye out on this thread as I might be making some changes to the scripts to make them easier to setup.
FritzsCorner
Posts: 7
Joined: Mon May 14, 2007 4:12 am

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

Post by FritzsCorner »

Looking forward to it. I haven't been able to get everything working 100% yet. The batchRip.scpt is working fine other than the Growl Notification part. The batchEncode.scpt will run but will instantly give me a growl notification that my encodes are done. I am guessing I have something configured incorrectly in my HandBrakeCLI-batch.sh shell script since it also doesn't work when I try to run it directly from the Terminal. I am going to keep digging and see what I messed up. ;)

Thanks Again!

# set the global variables to default
toolName="HandBrakeCLI"
toolPath="/usr/bin/$toolName"
toolTrackArgs="-t 0"
toolArgs="-2 -w 640" # also of interest -v
inputSearchDir="/Volumes/Leopard/Users/Fritz/Movies/DVDRips/BatchRip"
outputDir="$HOME/Movies/DVDRips/BatchEncode"
minTrackTime="60" # this is in minutes
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 »

FritzsCorner wrote: inputSearchDir="/Volumes/Leopard/Users/Fritz/Movies/DVDRips/BatchRip"
outputDir="$HOME/Movies/DVDRips/BatchEncode"
Hey FritzsCorner,

Try changing your inputSearchDir to "/Users/Fritz/Movies/DVDRips/BatchRip/"

Then, change your outputDir to "/Users/Fritz/Movies/DVDRips/BatchEncode/"

Also, don't forget to include the slash at the end of your last folder. I noticed it was missing.

Thx
Abulia
Posts: 47
Joined: Thu Feb 21, 2008 12:16 am

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

Post by Abulia »

Fantastic tutorial! Thank you for spending the time to put it together.

That said, the HandBrakeCLI doesn't work for me. Same thing as above, instant notification but the script never appears to kick off. I presume it's a file path issue.
mac.jedi wrote: Also, don't forget to include the slash at the end of your last folder. I noticed it was missing.
I don't have a slash at the end of mine. That's most likely the problem. Also, you may want to update the examples above to include this; the samples don't have a trailing slash either.

BTW, any quick way to disable the auto-rip script when you put in a DVD? Say, for example, I want to look at a DVD but not have it rip aside from going to System Preferences? Similar to holding down SHIFT in Windows to prevent autorun from kicking in?
FritzsCorner
Posts: 7
Joined: Mon May 14, 2007 4:12 am

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

Post by FritzsCorner »

mac.jedi,

Thanks again for your help.

I updated all my paths per your recommendation before I left for work this morning and I am still having the same issue. I didn't have a chance to do any further troubleshooting but it looks as if it isn't calling the HandBrakeCLI-batch.sh correctly or else it just isn't launching. I did try to launch it from terminal using "./HandBrakeCLI-batch.sh" to see what happens but it just tells me permission denied and when I try launching it using "sudo ./HandBrakeCLI-batch.sh" and enter an admin password I get "command not found" I did make sure I was trying to launch it from the same directory the script was in. I will hopefully have more time to mess around with it tonight when I get back from work. I am certain I am just doing something stupid and will be kicking myself when I get it working. ;)

Thanks again,

Fritz
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 »

ANNOUNCEMENT!
The tutorial instructions and scripts have been updated to make them more plug and play.

Changes:
  • Scripts have been rewritten to make them much easier to setup. My hope is that most users will not have to modify the scripts at all.
  • Scripts now include defaults that should run on any system. Default locations for files and scripts have been set to the ~/Movies/ directory.
  • BatchRip and BatchEncode Folders are now automatically created in your ~/Movies/ folder.
  • Growl Nofity Code has been moved to a script library that is loaded when called. You can now easily enable it in your batch script's properties.
  • BatchRip now auto-checks if two disks are loaded, no dual-drive setup required.
  • BatchRip now includes an auto-eject yes/no property.
  • BatchRip will now growl the disk name(s) when completed. Great for email notification.
  • HandBrakeCLI-Batch.sh shell script has been updated & posted. No additional setup should be needed.
  • BatchEncode now uses HandBrake's Universal preset by default.
  • BatchEncode now includes easier setup for encoding two batch folders at the same time.
  • BatchEncode now has a file type property to easily change output container. Default has been set to .m4v.
That might be it. Will edit if I think of anything else. Thx.
FritzsCorner
Posts: 7
Joined: Mon May 14, 2007 4:12 am

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

Post by FritzsCorner »

Thanks again mac.jedi! I will give this a shot after I recover from my turkey induced coma later today. ;)
FritzsCorner
Posts: 7
Joined: Mon May 14, 2007 4:12 am

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

Post by FritzsCorner »

That did it! It is working like a charm now. Thanks again for this awesome guide and scripts!
mnbearfan
Posts: 7
Joined: Sat Nov 29, 2008 6:59 am

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

Post by mnbearfan »

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'
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 »

mnbearfan wrote:So I have things working until the encode step.
Sorry you are having trouble. My advice is to start from scratch, follow the instructions exactly and don't modify the code in any of the scripts until you get them working.

Please use the default locations for your scripts and folders (~/Movies). Do not change the paths and name the files exactly as indicated.

Usually the problem is with directory paths. Either the are not entered in POSIX, start at wrong locations, the syntax is wrong or the path contains spaces. The original MediaForkCLI-batch.sh contains some code that parses the directory paths to compensate for an old MediaFork bug.

Testing BatchEncode:
Make sure HandBrakeCLI is installed in your Applications Folder or /usr/bin/.
Make sure the HandBrakeCLI-batch.sh was created a new Plain Text TextEdit Document (File > New. Format > Make Plain Text). DO NOT EDIT THE CODE. The file should be saved in your ~/Movies/BatchScripts/ folder as: HandBrakeCLI-batch.sh.
Make sure the script is executable. Open Terminal.app, type: chmod 777 ~/Movies/BatchScripts/HandBrakeCLI-batch.sh , then hit return.
Make sure the batchEncode.scpt was saved in your ~/Movies/BatchScripts/ folder as: batchEncode.scpt
Have a Video_TS folder ready in your ~/Movies/BatchRip/ folder.
Open the batchEncode.scpt and hit run.
Open Activity Monitor and sort by cpu. HandBrakeCLI should be running and you should see your CPU usage topping out.

If you still have issues PM me. THX!
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 »

mnbearfan wrote: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
What code did you do to achieve this? I thought about adding something like this to the batchRip script, but tossed it cause I couldn't find and easy way to let the computer know when I wanted it to the run the script or ignore it without having to click something each time. My last thought was to just create an applet that turns it on or off:

Code: Select all

-- Change DVD Preferences Script
-- Save as run-only app

on run
	display dialog "Run BatchRip Automatically" buttons {"Yes", "No"} default button 2
	if the button returned of the result is "Yes" then
		tell application "System Events" to tell CD and DVD preferences to set properties of video DVD to {insertion action:run a script, custom script:file POSIX file "~/Movies/BatchScripts/batchRip.scpt"}
		
	else
		tell application "System Events" to tell CD and DVD preferences to set properties of video DVD to {insertion action:ignore}
	end if
end run
mnbearfan
Posts: 7
Joined: Sat Nov 29, 2008 6:59 am

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

Post by mnbearfan »

I'll give that a try and let you know how it goes. It'll be interesting trying to figure out where the path problem might be. But I'll try using the defaults first and work backwards from there.

As for waiting for disk insertion, I used a less-than-ideal approach ... DVD Player. In its dictionary is a command for whether there is media inserted. So I just run a loop until that returns true and then quit DVD Player and go from there. It's not pretty but it works perfectly well. My script can just sit in the background running through this loop until I insert the disk. Its not a script I would leave running all the time. But for my purposes it does the job I had in mind. Here's the outline of my script so far. Once I get it cleaned up I'll definitely post it here.

1) Create the various folders for the process, if they don't exist.
2) Check to make sure all of the necessary software is installed where it should be.
3) Wait for a disk to be installed
4) Run the ripping process (basically a slightly modified version of your script.)

Then I'd like to be able to pass that along to the encoding process automatically and maybe even to the multiple episode namer and dumping the final result into iTunes.
mnbearfan
Posts: 7
Joined: Sat Nov 29, 2008 6:59 am

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

Post by mnbearfan »

well no luck on my end. I created the folders in ~/Movies, put the scripts in the scripts folder, the ripped disk folder in the BatchRip folder and made sure the .sh file had the proper permissions. I still get the same results. The applescript does nothing but kick off the Growl notification and when I try manually running the script, I get the errors I posted previously. it's late and I'm out of brain power to dig into this further tonight, so at this point I'm baffled. it seems like there's something wrong with my .sh script, but I recreated it verbatim from what you posted. The applescript also was recreated from your most recent post, the only thing I changed was the path to to the growl library. And I've verified that the Handbrake CLI is in Applications (and /usr/bin just in case.)
mnbearfan
Posts: 7
Joined: Sat Nov 29, 2008 6:59 am

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

Post by mnbearfan »

just wanted to post an update. I still had no luck with the .sh script. I couldn't sleep and sometimes I like challenges :) So I started seeing if there was a way I could do everything that the .sh script does in Applescript instead. I'm happy to say, after a couple of hours of trial and error, I think I can do it. I've got the beginnings of a workable script. It uses the Handbrake CLI to return a list of tracks, it then parses the duration for each track and compares that to a minimum number. If it is greater than or equal to that minimum it adds that track to a list of tracks to be encoded. Then, it will pass that list onto the encoding step and encode each one in turn (I'm now working on this part.) I'd love to be able to show some sort of progress bar during the encoding process but I'm not exactly sure how to go about that - I'm thinking I'd have to do it with Applescript Studio - which would probably be the way I'd prefer to deliver this anyway.

So, if anyone is interested, I'll be happy to post the progress on the rest of my solution as I progress.
mac.jedi
Enlightened
Posts: 108
Joined: Thu Apr 24, 2008 11:17 pm

BatchEncode Progress in Terminal

Post by mac.jedi »

mnbearfan, sorry you are still having trouble with the shell script. I've ran the script on several systems with no problem. Very strange, maybe try using TextMate to compile it?

Anyway, for those interested, the HandBrakeCLI-batch.sh script has real-time reporting built in, but you have to run it from Terminal. I've got a modified BatchEncode.scpt that runs in Terminal and may be helpful for troubleshooting. It also writes the session to a log file. FYI, if you've got dual-encodes going it puts each session in it's own tab. Enjoy!

Code: Select all

---------- BatchEncode.scpt For Terminal ----------

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/" -- 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()
	if batchFolders is 1 then mkDir(inputPath1)
	if batchFolders is 2 then mkDir(inputPath1) & mkDir(inputPath2)
	with timeout of 36000 seconds
		doScript()
		growlMe(growlTitle, growlMessage) of (load script growlLibraryPath)
		tell application "Terminal" to quit
	end timeout
end try

---------- Sub-routines ----------
to doScript()
	tell application "Terminal"
		activate
		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 " --input " & batchFolder & "/"
end setInput

to setOutput(batchOutput)
	mkDir(batchOutput)
	set spc to " "
	set outputDir to spc & "--output" & spc & batchOutput & "/" & spc
	set minTime to spc & "--minGetTime" & spc & minGetTime & spc
	set fileExt to spc & "--fileType ." & fileType & spc
	set outputCmd to outputDir & minTime & fileExt & encodeSettings
end setOutput

to createBatchScript()
	set inputDir1 to setInput(inputPath1)
	set inputDir2 to setInput(inputPath2)
	set outputOptions to setOutput(outputPath)
	set logFile to " | tee " & outputPath
	set batchScript1 to scriptPath & inputDir1 & outputOptions & logFile & "/BatchEncode.log"
	set batchScript2 to scriptPath & inputDir2 & outputOptions & logFile & "/BatchEncode2.log"
end createBatchScript

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

---------- End Script ---------
mnbearfan
Posts: 7
Joined: Sat Nov 29, 2008 6:59 am

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

Post by mnbearfan »

So, I have a functional application up and running. It was built with Xcode in Applescript and completely forgoes the need to use the HandBrakeCLI-batch.sh script. I've also been attempting to wrap many of these functions with some feedback so you know what's happening. Here's what it does...
After entering the minimum amount of time for a track to be encoded, and after entering a name format you want it to use (currently it takes this name and just appends a sequential number to the end,) it:

1) Creates the necessary folders for backing up and encoding (BatchRip and BatchEncode)
2) Checks to make sure the necessary applications are installed (VLC, HandbrakeCLI and Fairmount.)
3) Waits for the DVD to be installed (this was harder than I anticipated)
4) Launches FairMount and backs up the DVD to your hard drive to the BatchRip folder
3) Using HandBrakeCLI it scans the newly backed up Video_TS folder on your hard drive and figures out which tracks meet the minimum you entered. Once it figures out which tracks meet that standard it
4) Starts encoding each track. When it does this, it creates a file on your desktop called hbencode. This file is used to keep track of the progress of the encode for each track and report that progress back to you through the application.

This is very much a work in progress, especially the feedback mechanisms. For instance, I haven't yet figured out how to report the progress of the backup step, so that part will sit there for about 20 minutes. Also, during encoding, it will report the progress of the individual track encode, but doesn't give you an idea which track out of how many total tracks it is currently encoding. I'm hoping to add that soon.

This is all just an interesting project for me. The question I have for everyone here is whether anyone is actually interested in trying it out. It's really no different that what mac.jedi has posted, except it forgoes the HandBrakeCLI-batch.sh script and Growl and means you don't need to build your own app. And it wraps almost all of the functions into one app. I'm still thinking through how to deal with naming the tracks properly and how to import into iTunes. Also, I'm thinking about how I could split the rip from the encode so you don't have to run those time consuming steps one right after the other. Anyway, I'm curious if anyone is interested in trying it out before I post it. Just let me know if I should bother.
m021478
Posts: 13
Joined: Tue Feb 26, 2008 11:57 pm

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

Post by m021478 »

mnbearfan wrote:I'm curious if anyone is interested in trying it out before I post it. Just let me know if I should bother.
Yes...I'd be very interested...Please post your application...

Thanks!
mnbearfan
Posts: 7
Joined: Sat Nov 29, 2008 6:59 am

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

Post by mnbearfan »

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
Terc
Posts: 40
Joined: Wed May 28, 2008 6:15 am

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

Post by Terc »

I will certainly be including lots of this in my current script.
I prefer my extra step of ripping to the hard drive first. This makes it possible to rip disk in about 15 minutes or so, then insert another. Encoding is differed until the computer has time to get to it.
Also, it has worked very well for me to use the disk label as the name for my encode, at least until I have time to change it manually
I'd gladly share any part of my scripts with you if you'd like to include any parts of them.
mnbearfan
Posts: 7
Joined: Sat Nov 29, 2008 6:59 am

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

Post by mnbearfan »

I completely agree - I want to separate the backup from the encode. I've got a couple of ideas on how I could implement that function, I just need to see which one works out the best. My goal is three-fold...

1) Have an app that can be a "set it and forget it" solution to backup and encode a disk.
2) Have an app that can do either backup or encode separately. I haven't done a ton of this so far, so let me ask: On average, how much is performance degraded when a backup and an encode are happening simultaneously?
3) Have an app that can have the encode "scheduled" (via an iCal alarm.)

Because I'd like to do with all in one app (just a personal challenge - I could obviously build 3 separate apps to accomplish the above, but then what's the fun in that? :-) ) I'm trying to figure out how to know, when the app is launched, which of the above the user wants to do. And because it could be launched via an alarm, it needs to be able to be fully automated. Currently, I'm thinking I could, on launch, have it check for the existence of "something" in the BatchRip folder. If there is something in there, that means a backup has already happened and an encode is possible. Alternatively I could say that, when setting an alarm, you must put the backup folder name in the comments field. That way, I can read that on launch and if it's empty know the user isn't scheduling an encode but rather wants to start a backup OR start a backup and encode.

I know...I'm probably making it harder than it needs to be :-) What I'm shooting for though is something that could be given to a novice with the instructions "install VLC, HandbrakeCLI and FairMount. Run this app, set the time of the episodes on the disk you want to backup and give them a name and click GO" Without them having to compile any scripts, that was my original goal.

Good idea about the naming convention - just use the disk label. I'm thinking of offering an option to load a CSV file as well, so that, if one wants to include the individual track names, they had the option. I was also thinking I could have that as an option to be run after the encode as well (say from a menu or something.)
Post Reply