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.
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.
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
- Navigate to your ~/Movies folder.
- 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.
- 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.
- 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.
- Download and Install Growl. Then restart your computer.
- 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 ----------
- 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
- 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 ----------
- 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.
- Navigate and Choose your batchRip script.
- Close the window to save your settings.
Testing Your Batch Rip Automation
- Insert a DVD (or DVDs if you have a dual-drive system)
- 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).
- The DVD will unmount and re-mount as a disk image.
- After a short delay, the DVD will start copying to your ~/Movies/BatchRip/ folder.
- 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.
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
- Download and open the HandBrakeCLI disk image.
- Next, drag the HandBrakeCLI application from the disk image to your applications folder.
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.
- Open TextEdit and create a new PLAIN TEXT document.
- 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
- Save the file in your ~/Movies/BatchScripts folder as: HandBrakeCLI-batch.sh. If you're prompted, save using the .sh extension.
- Next we need to set the file permissions, open Terminal.app, type: chmod 777 ~/Movies/BatchScripts/HandBrakeCLI-batch.sh
- 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.
- 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 ---------
- Choose Script > Compile (CMD-K)
- Follow the steps in the script to set the properties, if needed.
- Save the script in your ~/Movies/BatchScripts folder as "batchEncode.scpt"
Setting An iCal Batch Encode Alarm
- Create a Calendar and name it (ex. Scripts)
- Select your new calender, create a New Event and name it (ex. Encode Alarm)
- Set the Start Time to the time you'd like your encodes to begin (ex. 12:00AM)
- Set the End Time to the Start Time + 1 minute (ex. 12:01AM)
- Set Repeat to "Every Day" (if you want it to run every night)
- Set End to "Never"
- Set Alarm to "Run Script"
- Below "Run Script", change "None" to "Other" and navigate to select your batchEncode.scpt
- Set Notification to "0 minutes before"
- 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:
- Create a plain text file for each season you've encoded and want to rename.
- 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
- a. Copy and paste an entire season of episode names into a txt file (one on each paragraph line). Only include the episode name.
- Create the droplet
- 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. - Save the script as an application: Choose File > Save As... > select Application from the File Format popup menu.
- Verify that no options are checked.
- Click Save.
- Select, copy and paste the script below into a new Script Editor document.
- Rename your episode files
- 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.
- Drag and drop the selected files onto the TV Show Renamer droplet.
- Navigate and select the text file you created in Step 1 from the dialog box.
- The episodes should automatically be renamed with the following file naming convention: Season#_Episode#(sequential)_Show Name_Episode Title.ext
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:
- 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
- Choose Script > Compile (CMD-K)
Optional: If you are adding to are remote machine:
- Change the "remMachine" variable: Insert the remote machines's username, password and IP address (eppc://username:userpass@remote_ip.local)
- On the line: Tell application "iTunes", delete the "--" before "of machine remMachine" so it reads: tell application "iTunes" of machine remMachine.
- Enable Remote Apple Events on the remote machine:
- Open System Preferences and click Sharing.
- Turn on Remote Apple Events by checking the checkbox.
- Close the window to save your settings.
- Save the edited script as "Add to iTunes Auto-Tag.scpt"
- 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
- Right-Click (Control+Click) on the folder you want to attach the folder action to (ex. ~/Movies).
- Scroll to the bottom of the pop-up and Select More > Enable Folder Actions
- Right-Click (Control+Click) on the folder again and Select More > Attach a Folder Action
- Navigate and Choose your "Add to iTunes Auto-Tag.scpt"
- 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.