PDA

View Full Version : Part 2: (Tutorial) Automating DVD Backup with FairMount, HandBrake and iTunes




mac.jedi
Nov 14, 2008, 06:42 PM
Announcement

I've posted a new tutorial thread in the Apple TV and Home Theater forum:
How-To: Automating DVD & Blu-Ray (Backup, Encoding & Tagging) for Mac OS X 10.6 (http://forums.macrumors.com/showthread.php?t=805573)

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

Enjoy!


Part 2: Automating DVD Backup with FairMount, HandBrake and iTunes

Parts to this tutorial:
Part 1: Introduction
Part 2: Using AppleScript to Automate Ripping
Part 3: Using a Batch Script to Automate HandBrake
Part 4: TV Show Renamer Droplet
Part 5: Add to iTunes and Auto-tag Script

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 (http://www.metakine.com/products/fairmount/)
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 (http://www.videolan.org/vlc/)
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 (http://www.apple.com/applescript/firsttutorial/02.html)
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


Select, Copy and Paste the batchRip script into a new Script Editor document.


---------- 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 : "BatchRip"
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 ----------


Choose Script > Compile (Command-K)
Follow the steps in the script to set the properties, if needed.
Save the script in your ~Movies/BatchScripts folder as "batchRip.scpt"



Making Your Script the Default Action When a DVD is Inserted:


Open System Preferences and click CDs & DVDs.
Choose the action "Run Script…" from the DVD pop-up menu.

http://dl.getdropbox.com/u/242398/screenshots/ripguide/dvd_prefs.jpg


Navigate and Choose your batchRip script.

http://dl.getdropbox.com/u/242398/screenshots/ripguide/dvd_prefs2.jpg


Close the window to save your settings.



Testing Your Batch Rip Automation


Insert a DVD (or DVDs if you have a dual-drive system)

http://dl.getdropbox.com/u/242398/screenshots/ripguide/fairmount_frame2.jpg


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).

http://dl.getdropbox.com/u/242398/screenshots/ripguide/fairmount_frame5.jpg


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

http://dl.getdropbox.com/u/242398/screenshots/ripguide/fairmount_frame8.jpg


After a short delay, the DVD will start copying to your destination folder.

http://dl.getdropbox.com/u/242398/screenshots/ripguide/fairmountss.jpg


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.


If you've set up growl support, you will be notified by display, speech or email when completed.

http://dl.getdropbox.com/u/242398/screenshots/ripguide/ripnotify.jpg



Go To Part 3: Using a Batch Script to Automate HandBrake



PaulCaden
Nov 26, 2008, 07:02 AM
Forgive the newbie question, but is there any quality difference by not using DVD2One to do the ripping?

I followed another tutorial that uses Fairmount, DVD2One, and Handbrake to get the DVDs onto Apple TV.

mac.jedi
Nov 26, 2008, 10:46 AM
Forgive the newbie question, but is there any quality difference by not using DVD2One to do the ripping?

Hi Paul,

There is no loss in quality, it's only copying the data. I use DTOX only when a rip fails. I'll go into DTOX and select the main title and deselect zero cells. Unfortunately, you have to do this disk by disk which is what we're trying to solve through automation.

THX

mac.jedi
Nov 27, 2008, 10:12 AM
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.

mrklaw
Jan 18, 2009, 11:15 AM
Hi,

This is great work, but how would I go about changing the locations for rips and encodes? Only having a 120GB HDD on my mini I'd prefer to use my external drive if possible.

edit: gave up trying to keep spaces in my volume names so renamed them.

Now I am having problems with 'silent running' which I thought as an old, bare-bones release woudl have been a simple test. Ripped tremors ok but fairmount is taking eons to deal with silent running. probably 3 hours in and its still only claiming 2.5GB.

mac.jedi
Jan 19, 2009, 09:42 AM
Hi,

This is great work, but how would I go about changing the locations for rips and encodes? Only having a 120GB HDD on my mini I'd prefer to use my external drive if possible.

edit: gave up trying to keep spaces in my volume names so renamed them.

Now I am having problems with 'silent running' which I thought as an old, bare-bones release woudl have been a simple test. Ripped tremors ok but fairmount is taking eons to deal with silent running. probably 3 hours in and its still only claiming 2.5GB.

Spaces in the path shouldn't be a problem. To change to a volume other than your boot drive, you need to edit the output path in the script. Between the quotes in the property, change to "/Volumes/your external drive/BatchRip". Don't put a "/" at the end of your path.

The reason I don't use external volumes is speed. Not with the ripping, but for the encoding.

Sometimes, I'll come along a disk that fairmount can't handle alone. In those cases I use DVD2One, RipIt, MtR, or AnyDVD on VMware.

I hope this helps!

mrklaw
Jan 19, 2009, 10:41 AM
I did. I tried "/Volumes/Iomega HDD/rips" and it didn't work. It actually created a folder on my home folder called 'HDD' and put the rips folder in there. Tried with %20 and "\ " but nothing.

anyway, done now.


Would you know how to change the handbrake CLI parameters to select Japanese language audio and english subtitles? I'd use that for the large collection of Ghilbi/Japanese movies. I'd rip/encode all my english stuff, then switch the script and rip all my Japanese titles.

mac.jedi
Jan 19, 2009, 12:30 PM
I did. I tried "/Volumes/Iomega HDD/rips" and it didn't work. It actually created a folder on my home folder called 'HDD' and put the rips folder in there. Tried with %20 and "\ " but nothing.

anyway, done now.


Would you know how to change the handbrake CLI parameters to select Japanese language audio and english subtitles? I'd use that for the large collection of Ghilbi/Japanese movies. I'd rip/encode all my english stuff, then switch the script and rip all my Japanese titles.


You're right! The script isn't escaping spaces. You need to "\\ " a space in the path. I'll add a sub-routine to do this automatically. Thanks for letting me know.

As far as language and subtitle, you'll need to do some testing as I never done it with the CLI. The HB CLI wiki had info for setting those. You'll just add them to your encodeSettings in the script.

mrklaw
Jan 19, 2009, 01:35 PM
can't seem to get growl working. Have it installed, but its not showing that script in the applications list - just handbrake (the gui version as it has the pineapple icon) and firefox.

i've tried running the script manually, and I have it set to 'yes' for ripping/encoding.

Ideally I want it to email me when the encoding is done but I don't see how I can do that if I can't see it appear in the growl settings.

mac.jedi
Jan 19, 2009, 03:01 PM
can't seem to get growl working. Have it installed, but its not showing that script in the applications list - just handbrake (the gui version as it has the pineapple icon) and firefox.

i've tried running the script manually, and I have it set to 'yes' for ripping/encoding.

Ideally I want it to email me when the encoding is done but I don't see how I can do that if I can't see it appear in the growl settings.

If the path to the growl script contains spaces, it might be causing the issue. I'll update the script to fix it. In the meantime, add a \\ before each space in your path.

Also, the script needs to run at least once before you'll see it in growl.

Let me know if any of this helps.

mac.jedi
Jan 19, 2009, 03:06 PM
can't seem to get growl working. Have it installed, but its not showing that script in the applications list - just handbrake (the gui version as it has the pineapple icon) and firefox.

i've tried running the script manually, and I have it set to 'yes' for ripping/encoding.

Ideally I want it to email me when the encoding is done but I don't see how I can do that if I can't see it appear in the growl settings.

Also, I forgot to mention that you need to do the growl script steps in Part 1 (in case you skipped that step).

mrklaw
Jan 20, 2009, 01:54 AM
Hi

still no luck. I have the script from part 1 in the BatchScripts folder - the only folders I changed were the encode/rip ones - all scripts are in richardmini/Movies/BatchScripts/

Tried restarting the computer and still nothing is showing up in growl. Is there something I can check to see if the scripts are trying to send the notifications?


Everything else seems to work fantastically so thank you for this great guide, just this one little bit is missing. And with the mini being almost headless (TV it uses isn't accessible all the time), and handbrake CLI being invisible it would be good to be informed when its finished.

mac.jedi
Jan 22, 2009, 05:48 PM
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.

mac.jedi
Jan 22, 2009, 07:06 PM
Hi Richard,

Here are some suggestions that may help:

all scripts are in richardmini/Movies/BatchScripts/

Make sure you have the growlLibraryPath property set exactly as shown.

property growlLibraryPath : POSIX file "Users/richardmini/Movies/BatchScripts/GrowlNotifyLib.scpt"

Is there something I can check to see if the scripts are trying to send the notifications?

You can comment the noted lines below (--) in the batchRip script to skip the ripping and go straight to notification. Make sure you have a DVD mounted. Run the script through script editor and you should see a display notification if successful. If not, go to the growl system pref pane to see if the script is making to the applications list. You can also look at the event log in script editor to see the script progress.


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



handbrake CLI being invisible it would be good to be informed when its finished.

The batchEncode script now runs through a terminal window. The paths and tools variables are now shown on screen as well as encode progress.

I hope this helps!

thx.

mrklaw
Jan 23, 2009, 03:59 AM
well, after mashing my head against the keyboard most of the morning, it seems to be working. Uninstalled growl, restarted, reinstalled, restarted, ran scripts, checked application list etc. Nothing. Then it just appeared.

Strangely though, both batchrip and batchencode show up now in the growl application list, but while batchencode shows up a notification successfully, batchrip still doesn't. Don't mind too much - the main reason was to enable email notifications of the batch encode finishing so I can monitor progress and estimate time taken for future scheduling etc.

(although it seems like your logs will help just as much with that).


BTW, looking in the growl application support folders, the batchrip.growlticket is massive compared to others - 1.1MB compared to 64KB for superduper or firefox. Is that due to it being a script, or some other reason?


Anyway, seems to be ok now. Next step is to set up two different batch encode scripts so I can rip my Japanese language stuff with subtitles. Already have two different versions of batchrip set to buttons on my remote via remotebuddy (hope it works ok with longer scripts), so I'll be filling up two rip folders depending on the disc content.


Thanks very much for your help and this guide, its been invaluable.

mac.jedi
Jan 24, 2009, 10:50 AM
Batch Encoding m2ts Files with tsMuxeR and HandBrakeCLI


Backing up Blu-Ray's for AppleTV has a long way to go before it becomes as easy as backing up DVD's on a Mac. I've been playing around with this a lot and have written a few scripts that allow for easy meta file creation, batch m2ts muxing and batch HandBrake encoding.

I'm using VMware Fusion/XP Pro on an 8-core Mac Pro. My workflow is as follows:

Use AnyDVDHD to copy all the BD disks you want to batch process to a BatchRip Folder.
Use the tsMuxerGUI as you normally would but click "Copy to clipboard" instead of "Start muxing"
Double-click the tsMuxeR_metaFile.cmd script. This will copy the metadata into a new metafile in the bd movie's folder. This filename is tagged with a search string to allow the next script to find it.
Repeat the last two steps on all your bd rips.
When ready, double-click the run_batchtsmuxer.cmd script. This will find all the tagged metafiles in your batch folder and launch the batchtsmuxer.cmd script to mux them one-by-one according to the options set in their metafile.
Once the m2ts files are muxed, we encode on the Mac side using HandBrakeCLI.
I create an iCal alarm to execute the batchEncodeHD.scpt at midnight so when I wake up, Voila! All the m2ts files are now m4v's!


REQUIREMENTS:

If you haven't yet: read, follow and understand CaveMan's instructions on the MacRumors forum for ripping and encoding BD disks. http://forums.macrumors.com/showpost.php?p=6012016&postcount=1
Windows for AnyDVD and tsMuxerGUI and tsMuxer command line tool for ripping and muxing. MacOSX and HandBrakeCLI for encoding.
In order to execute, you need to set up the input, output and script paths in these scripts. The scripts are commented and should be relatively easy to follow.
The meta and m2ts files you want to convert need to have some sort of a search string to identify them as the files you want to process (Example: Iron Man_BD.m2ts). The search string will be removed from the resulting m4v. You must also specify this search string (Example: "_BD.m2ts") in the batchEncodeHD.scpt.
Most of this based on my post ""Automating DVD Backup with FairMount, HandBrake and iTunes"

I'd suggest looking over the batch encoding with handbrake section if you aren't familiar with this process. http://forums.macrumors.com/showthread.php?t=600467


Here are the scripts:

Happy Encoding!

tsMuxeR_metaFile.cmd


@echo off
:: tsMuxeR_metaFile.cmd - UPDATED: 01-23-2009

:: This script uses the command line extension Clipboard. This allows the tsMuxeR metadata copied to the clipboard to be accessed via command prompt. It can be found at http://www.steve.org.uk/Software/clipboard/clipboard.zip

:: Until someone can point out a better way to do this, you will need to edit the commands below to create the metafile in the right location with the right filename. In the second FOR command, you need to include the number of tokens "\" in your directory tree to obtain the path to your BD folders and get their names, in my case this would translate to Z:\MyDisk\BatchRip\Iron_Man\. The tokens=1,2,3,4 for my file path. You will also need to specify each token in the output command at the end: %%n\%%o\%%p\%%q\%%q_BD.meta would create the metafile in Z:\MyDisk\BatchRip\Iron_Man\Iron_Man_BD.meta. As you'll notice the BD rip's parent folder token is entered twice to name the file with the BD's name followed by a search string. I know this is complicated, but I'm a Mac guy and I'm surprised I even got this far.

clipboard | for /f "skip=1 eol=# delims=, tokens=2" %%i in ('findstr "BDMV"') do echo %%i | for /f "delims=\ tokens=1,2,3,4" %%n in (%%i) do clipboard > %%n\%%o\%%p\%%q\%%q_BD.meta

:: endscript




run_batchtsmuxer.cmd


:: run_batchtsmuxer.cmd UPDATED: 01-23-2009

:: this script is used in conjunction with batchtsmuxer.cmd

@echo off

:: set your input directory to process the specified meta files
set batchfolder="C:\Documents and Settings\userloginname\My Documents\Batch Rip"

cd /d %batchfolder%

:: set the search string appended to the filename of the meta file ex. "*_BD.meta"
for /r %%i in (*_BD.meta) do set metafile="%%i" & call batchtsmuxer.cmd

:: endscript




batchtsmuxer.cmd


:: batchtsmuxer.cmd UPDATED: 01-23-2009

:: place this file in your batch folder
:: this script is used in conjunction with run_batchtsmuxer.cmd

for /f "delims=." %%n in ("%metafile%") do set outfile="%%~dpnn.m2ts"
if exist %outfile% (
echo Output file SKIPPED because it already exists
) else (
echo "Creating %outfile% from %metafile%"
"C:\Program Files\tsMuxeR\tsMuxeR.exe" %metafile% %outfile%
echo " - - - - - - - - - - - - - - - -"
)
:: endscript




batchEncodeHD.scpt


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


global batchScript

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

-- Search String: This script's default search string is "_BD.m2ts". Any .m2ts file name with this search string (located in the input directory) will be processed with HandBrake.
property searchString : "_BD.m2ts"

-- The input directory to process all m2ts files with a specified string appended to the filename. Default path is: ~/Movies/BatchRip.
property inputPath : "~/Movies/BatchRip"

-- The output directory for all output files. Default is: ~/Movies/BatchEncode.
property outputPath : "~/Movies/BatchEncode"

-- The path to your HandBrakeCLI-batchHD.sh script. Default is: ~/Movies/BatchScripts/HandBrakeCLI-batchHD.sh
property scriptPathHD : "~/Movies/BatchScripts/HandBrakeCLI-batchHD.sh"

-- Set your HandBrakeCLI encode settings. Default is the AppleTV preset, 1280w, with quality set at 57%. For more info in setting parameters, visit http://handbrake.fr and read the CLI Guide Wiki.
property encodeSettings : "-e x264 -q 0.56 -a 1,1 -E faac,ac3 -B 160,auto -R 48,Auto -6 dpl2,auto -f mp4 -4 -w 1280 -m -x level=30:cabac=0:ref=3:mixed-refs=1:bframes=6:weightb=1:direct=auto:no-fast-pskip=1:me=umh:subq=7:analyse=all"

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

-- 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(outputPath)
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}
do script batchScript in tab 1 of window 1
repeat until tab 1 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 inputDir to setInput(inputPath)
set logFile to " | tee " & escapePath(outputPath)
set outputDir to quoted form of outputPath
set batchScript to escapePath(scriptPathHD) & spc & inputDir & spc & outputDir & spc & quoted form of searchString & spc & quoted form of encodeSettings & logFile & "/BatchEncodeHD.log" & " wait"
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 ---------




HandBrakeCLI-batchHD.sh


#!/bin/sh

# UPDATED: 01-22-2009
# HandBrakeCLI-batchHD.sh is a script to batch execute the HandBrakeCLI specifially for encoding m2ts files to m4v.

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

# const global variables
scriptName=`basename "$0"`
scriptVers="2.0"
scriptPID=$$
skipDuplicates=1 # if this option is off,
# 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"
searchString="$3" # Search String: Any .m2ts file name with this search string (located in the input directory) will be processed with HandBrake (Example: "_BD.m2ts").
toolArgs="$4" # set handbrakecli encode settings: "-e x264 -q 0.56 -a 1,1 -E faac,ac3 -B 160,auto -R 48,Auto -6 dpl2,auto -f mp4 -4 -w 1280 -m -x level=30:cabac=0:ref=3:mixed-refs=1:bframes=6:weightb=1:direct=auto:no-fast-pskip=1:me=umh:subq=7:analyse=all"



#############################################################################
# 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 m2ts files in it (default: /Movies/BatchRip)"
echo " arg2: outputDir=<string> Set output directory for all output files (default: ~/Movies/BatchEncode)"
echo " arg3: searchString <string> Set the text appended to the filename of the .m2ts/s to encode (default: _BD.m2ts)"
echo " arg4: toolArgs=<string> Set the HandBrakeCLI encode settings (example: -e x264 -q 0.56 -a 1,1 -E faac,ac3 -B 160,auto -R 48,Auto -6 dpl2,auto -f mp4 -4 -w 1280 -m -x level=30:cabac=0:ref=3:mixed-refs=1:bframes=6:weightb=1:direct=auto:no-fast-pskip=1:me=umh:subq=7:analyse=all) "

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
}

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"
}


#############################################################################
# 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 " Search string: $searchString"
echo " Tool path: $toolPath"
echo " Tool args: $toolArgs"
echo " - - - - - - - - - - - - - - - -"

# find all the m2ts files in the input directory tree
find "$inputSearchDir" -type f -name "*$searchString" | while read i ; do

# set the bd movie name to output
echo "$i"
dvdName=`basename "$i" $searchString`

# execute handbrakecli and skip output files that already exist.
if [[ ! -e $outputDir/"$dvdName".m4v || skipDuplicates -eq 0 ]];
then
$toolPath -i "$i" -o "$outputDir"/"$dvdName".m4v $toolArgs & wait


else
echo " Output file SKIPPED because it ALREADY EXISTS" & wait
fi
done

# END SCRIPT

mrklaw
Jan 25, 2009, 09:48 AM
nm, posted in the ripping section (part 3)

brettatredback
Feb 28, 2009, 08:05 PM
Hi - Great work, thanks! Under what circumstances/cases, do dvd's need something like mactheripper here? I am starting to rip my collection, but wondering how and where something like this will be needed. Is there any way that mactheripper could be added in as an optional step?

thanks!!
Brett

quesoamarillo
Mar 10, 2009, 09:58 AM
Hi,

I was having problems with Growl as well - notifications not showing up. I added a line to the growlMe function and got it working:

on growlMe(growlTitle, growlMessage)
setGrowl(growlTitle)
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

Apparently Growl needs the script to register itself. Calling the setGrowl function seems to do the trick.

brettatredback
Mar 10, 2009, 10:28 PM
Has anyone else found that occasionally the dvd rips fine but then becomes unjectable without a reboot - the eject command via disc utility says there are open files/applications on the disc? I wonder if the script is not closing something here??

notsofatjames
May 11, 2009, 02:25 AM
Just a quick bug I found whilst trying to rip Pineapple Express. It seems like your script also doesnt like filenames that have "<" in them. I'm not sure if you're able to expand the EscapePath sub. I'm not quite that good. :P
I'm talking about the DVD not the blue-ray script.

mac.jedi
May 13, 2009, 02:17 PM
Just a quick bug I found whilst trying to rip Pineapple Express. It seems like your script also doesnt like filenames that have "<" in them. I'm not sure if you're able to expand the EscapePath sub. I'm not quite that good. :P
I'm talking about the DVD not the blue-ray script.

I'll send you a PM with a revised script. Let me know how it works as I can't really test it without a DVD that has illegal characters in its volume name. Please note that you may have to update the output paths, etc.

spyderboyy
May 24, 2009, 02:22 PM
Hi, Mac.Jedi

Thanks for making this tutorial. I need to note that I am a beginner level at using AppleScript, and I've followed your instructions to the letter so far.

When I go to save batchRip.scpt, it pops up with this syntax error message:

Can't make file
:Users:joelbonner:Movies:BatchScripts:GrowlNotifyLib.scpt
into type reference.

Also, does it matter that I've saved the first file (and trying to save this one) with the .scpt at the end of the file names?

padawan
Jun 7, 2009, 02:25 AM
Thanks for making this tutorial. I need to note that I am a beginner level at using AppleScript, and I've followed your instructions to the letter so far.

When I go to save batchRip.scpt, it pops up with this syntax error message:

Can't make file
:Users:joelbonner:Movies:BatchScripts:GrowlNotifyLib.scpt
into type reference.

I have the same problem like the one above, and would like to get some help on this problem, Im a total newbie.
Thanks

toppledwagon
Jul 3, 2009, 10:08 PM
Since the wife sometimes wants to watch the DVD right as she inserts it, I've added this little tidbit to the BatchRip.scpt. This will pull up a dialog and ask if you want to play the DVD. Just hit 'enter' or click the Play button to play. It will also timeout after 30 seconds, so you can still have unattended ripping. If you want to use "DVD Player" instead of "Front Row", that works too.


try
activate
display dialog "Play DVD or RIP?" default button "Play" giving up after 30 buttons {"RIP", "Play"}
if (button returned of the result is "Play") then
tell application "Front Row"
activate
end tell
tell me to quit
exit repeat
end if
tell application "FairMount" to launch
delay 20
countDisks()
copyDisks()
tell application "FairMount" to quit
end try

toppledwagon
Jul 3, 2009, 10:12 PM
Thanks for making this tutorial. I need to note that I am a beginner level at using AppleScript, and I've followed your instructions to the letter so far.

When I go to save batchRip.scpt, it pops up with this syntax error message:

Can't make file
:Users:joelbonner:Movies:BatchScripts:GrowlNotifyLib.scpt
into type reference.

I have the same problem like the one above, and would like to get some help on this problem, Im a total newbie.
Thanks

I had to add a / at the beginning of the quoted string. Then it worked for me.

property growlLibraryPath : POSIX file "/Users/david/Movies/BatchScripts/GrowlNotifyLib.scpt" -- Set the path to the GrowlNotifyLib.scpt.

bdbode
Jul 9, 2009, 12:07 PM
I'll send you a PM with a revised script. Let me know how it works as I can't really test it without a DVD that has illegal characters in its volume name. Please note that you may have to update the output paths, etc.

Were you able to resolve this? I am having the same problem. I apologize if you've already posted the updated script but I'm not good enough at interpreting Applescript yet to see whether it accounts for this now.

mac.jedi
Oct 20, 2009, 10:15 AM
Announcement

I've posted a new tutorial thread in the Apple TV and Home Theater forum:
How-To: Automating DVD & Blu-Ray (Backup, Encoding & Tagging) for Mac OS X 10.6 (http://forums.macrumors.com/showthread.php?t=805573)

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

Enjoy!

robert.daniel
Jul 7, 2010, 08:35 PM
Hi all,

The scripts work great for importing DVDs for use in Plex.

I had a problem getting the script to run on insertion of a new DVD. The issue was that there is some new file format in Snow Leopard (10.6 and above) that will cause the file to not start up. I found the solution was to open the file in AppleScriptEditor and then do 'Save As..' with the same file name.

It was pretty odd since the script would run fine when manually executed but not when read from the disk. Hope this clears up any problems others may be seeing.

Thanks,
Rob

See Script File Formats int the Snow Leopard Apple Script Release Notes at this URL http://developer.apple.com/mac/library/releasenotes/AppleScript/RN-AppleScript/RN-10_6/RN-10_6.html

Bboy486
Jul 12, 2010, 05:03 PM
Is there anyway to modify the batch encode script to, instead of using ical, have it watch the BatchScript Folder and automatically encode when a file is in there?