I’ve been working with some AppleScript lately to help with my video conversions, and I’ve come up with something that saves me quite a bit of hassle. It uses the free command-line interface of Handbrake called HandbrakeCLI, and is able to convert all videos from specified extensions (ex. avi and mkv) to something that is a bit more widely supported (ex. MP4). All you have to do is point it to a directory and it will start converting all matching videos one-by-one.
How does it work? This is (kind of) a step-by-step walkthrough of how the code processes files if you’re using it without any reconfiguration. You can, of course, tailor it a bit more to your needs.
- The script looks at a drive called “SecondaryHD” in a directory called “Movies” for any video files that have an extension of AVI or MKV (it even looks recursively through all subfolders), and also makes sure that the video has no label color assigned yet. You’ll find out why the label color thing is important in the next step.
- It loops through all of the files it found, and before it begins processing it sets the label color of the file to gray. That way if you run multiple instances of this at the same time it will not process the same file twice. If you do run this multiple times, however, it only runs one instance of Handbrake at a time.
- It now runs the HandbrakeCLI using a set of parameters that I’ve found to work well on my Xbox 360 (I know the bitrate is unnecessarily high at 4000Kbps, but it helps make sure I don’t lose quality). You can configure the parameters to your liking using the information on this page. Also, it’s important to note that the command is run using “nice”, which will run the conversion process using low priority. That way it shouldn’t affect the overall performance of your system.
- It sets the label color of the original file to green, which assuming the next step works will be worthless. It’s just good measure.
- The original file is deleted so that all you have left over is the MP4 version of the original video.
- That’s it. If any error occurs during the conversion process or on any of the other steps the label color of the original file will be set to red. That way you’ll know something didn’t go as expected. Plus if the label color is set to red the video will not be reprocessed if you decide to run the script again, unless you manually remove the label color by right-clicking on the file.
Here is the code (download the script):
--on adding folder items to this_folder after receiving these_items
with timeout of (720 * 60) seconds
tell application "Finder"
--Get all AVI and MKV files that have no label color yet, meaning it hasn’t been processed
set allFiles to every file of entire contents of ("SecondaryHD:Movies" as alias) whose ((name extension is "avi" or name extension is "mkv") and label index is 0)
--Repeat for all files in above folder
repeat with i from 1 to number of items in allFiles
set currentFile to (item i of allFiles)
try
--Set to gray label to indicate processing
set label index of currentFile to 7
--Assemble original and new file paths
set origFilepath to quoted form of POSIX path of (currentFile as alias)
set newFilepath to (characters 1 thru -5 of origFilepath as string) & "mp4'"
--Start the conversion
set shellCommand to "nice /Applications/HandBrakeCLI -i " & origFilepath & " -o " & newFilepath & " -e x264 -b 4000 -a 1 -E faac -B 160 -R 48 -6 dpl2 -f mp4 –crop 0:0:0:0 -x level=40:ref=2:mixed-refs:bframes=3:weightb:subme=9:direct=auto:b-pyramid:me=umh:analyse=all:no-fast-pskip:filter=-2,-1 ;"
do shell script shellCommand
--Set the label to green in case file deletion fails
set label index of currentFile to 6
--Remove the old file
set shellCommand to "rm -f " & origFilepath
do shell script shellCommand
on error errmsg
--Set the label to red to indicate failure
set label index of currentFile to 2
end try
end repeat
end tell
end timeout
--end adding folder items to
Notes about the code:
- You can specify any extensions you want to include in the conversion process, but it really only works with extensions that are 3 characters based on the way it generates the filename of the new path. I’m sure this can be improved, but I only wanted AVI and MKV files converted.
- You’ll likely need to update the folder location that is searched. The way the path is specified is in an AppleScript format, and this may help you if you’ve never dealt with them before.
- This is is assuming you’ve downloaded HandbrakeCLI and put it in the Applications folder.
- You can use this with folder actions if you uncomment the first and last lines. Keep in mind that this enables it to run when a file is added to a particular folder, but will still process every matching file in that folder. It doesn’t actually use the items it is passed.
- You can schedule this to run at certain times using iCal.
- Try downloading the script directly if you copied and pasted the script and are having troubles. There may be some characters that got incorrectly encoded when being posted here, and won’t translate well in the code.
If you’ve got any updates to the code please feel free to send them our way. There are probably much more elegant ways of doing this, but this works well for me. Hopefully this will at least point some of you in the right direction for creating your own scripts.

“convert all videos from specified extensions (ex. avi and mkv)”
Haven’t heard of an ‘mkv’ format…was that suppose to be ‘mov’?
Nope. MKV is one of the most widely adapted h.264 video formats.
Sorry, I only know a little bit about Applescript, and haven’t found much on Google to answer my question-
How do I specify my own folder as the folder to take the files from? For example, if I want to convert everything in a folder found in ‘User/Name/Movies/Files to Convert’ how exactly do I format that to insert in your Applescript?
Thanks!
It should be something like Macintosh HD:User:Name and so on. The Macintosh HD is the name od the drive. Take a look at the link I reference in the article for help with path names.
Ryan –
Nice bit of Scripting! I’m about to attempt adapting your script to accept Video TS file-sets – a first step, and if that works out, well, I have a lot of DVD 16×9 and bunch of DVD 4×3 disks to add to my I-Tunes library; but processing each of them one per night takes sooo many nights!
(About six months ago a nearby Blockbuster closed, selling out a lot of titles; I am still just putting TS Folders into my NAS, networked with my Home Theater, computers, and Apple TV.
Appears that maybe multiple computers could concurrently work copies of the script each working a separate NAS file, thanks to your concepts of: ‘color coding’ each candidate, and the failed files, and deleting each completed file. Nicely planned! Might it also be necessary to assign each computer a unique ‘I am working here’ color to put on its current file/folder?
I’ll let you know if these plans work out – hope you will accept questions when the road gets rough.
Thanking you, in advance.
William
Awesome William. Glad you are going to adapt it to your needs. Can’t wait to hear what you come up with.
Just wanted to say this worked perfectly for me. Thank you.
Been looking for a way to do this via AppleScript so I can use in conjunction with Hazel — thanks! One question: is there a way to edit the AppleScript so the converted mp4 file is saved to a different folder than the original?
I’d like to save the final file to a “converted” folder and keep the original.
You should be able to modify the origFilePath variable to point to where you want the file stored.
Please, could you advice how I set a different target folder?
Thx
This is great!
I too am wondering how to change the output location. There a a few different instances of the origFilePath variable and am wondering which one i need to change?
Thanks
here is what I did to move the files to another folder after conversion..
i didn’t want it deleting the old files, as i save them as masters
so i took that code out, and added
tell current application
do shell script “mv ” & newFilepath & ” ~/Desktop/Converted”
end tell
this will move files to the desktop in a converted folder after conversion
Hi, I’ve been looking for something like this for ages, thanks. How would I go about making it run not “nicely”? I’m going to run it overnight and so system performance for other things isn’t important to me. at the moment encodes that would normally take about 20mins on my i7 MBP seem to be taking far longer. can I just remove the word “nice” from this part of the script:
–Start the conversion
set shellCommand to “nice /Applications/HandBrakeCLI -i ” & origFilepath & ” -o ” & newFilepath & ” -e x264 -b 1000 -a 1 -E faac -B 160 -R 48 -6 dpl2 -f mp4 –crop 0:0:0:0 -x level=40:ref=2:mixed-refs:bframes=3:weightb:subme=9:direct=auto:b-pyramid:me=umh:analyse=all:no-fast-pskip:filter=-2,-1 ;”
do shell script shellCommand
, or is there something else to be done?
Yes, you should just be able to remove “nice” from that line.
Hi ryan!
Thanks for this awsome script can’t wait to get it optimized for my needs.
One question: I want this script to get it input folder not from an static location but from the selected folder. (like a finder service which i can launch from the contextual menu).
I can’t seem to get the right code combination for this to work.
I hav tried to exchange the “SecondaryHD:Movies” from:
set allFiles to every file of entire contents of (“SecondaryHD:Movies” as alias)
with: “theSel” which i found from this script:
tell application “Finder”
set theSel to item 1 of (get selection) — returns a reference
end tell
and also: “theItem to the selection as alias” from another script but nothing works.
Can you help me?
Thanks
-Kris
this is great, my one issue is that I want to us the new “AppleTV 2″ preset and cannot figure out how to modify your script.
The issue is that the preset has a space in the name.
I think the argument to pass to handbrake CLI is
–preset= “AppleTV 2″
Any ideas?
Thanks.
Phil
To make this work as a Folders actions script I replaced this line at the start of the script
with timeout of (720 * 60) seconds
with
on adding folder items to this_folder after receiving added_items
and at the end of the script replace
end timeout
with
end adding folder items to
other than that I thank you for your efforts. The reference for HandBrakecli is very good reference for customizing to each persons needs.
Simon
I included the lines in the code (commented out) that you just had to uncomment to make it use as a folder action. You may still want to leave the timeout line in there.
Phil, go here [trac.handbrake.fr] and it has the whole line for the Apple tv 2 preset.
OP
The script seems to keep making my finder non responsive. any ideas? G4 1.5 ghz PB osx 10.5.8.
Cheers for a good script, stoked to find it.
Is it at least processing when your Finder freezes, or does it not appear to be doing anything? I’m running Snow Leopard so I’m not sure if that may have something to do with it. I wouldn’t think so since the script isn’t really using anything special.
Yeah it is running in the background I found out after posting. The only way I noticed was the fan on so I check istat and saw it the processes. Unfortunitly it make the computers finder unusable though when running. not sure how to kill the process without restarting the computer too so not the ideal situation especially with the low power and slow encoding of my g4. I have a shed load of avi s and want to avoid and hrs of queing HB.
Another Automator script for encoding t_s folders i have treid had a terminal come up which showed HB cli progress which did not happen this. I treid modifying the this script to show verbose mode but no luck.
Thanks heaps for the code may check HB cli forum for something as well.
Cheers
You can always kill the process through the Activity Monitor. There should be a HandbrakeCLI process running that you can kill. When you do so it will continue on to the next file though, and will color code the failed one with a red label.
This is fantastic!
I modified to run the Apple TV 2 preset as
set shellCommand to “nice /Applications/HandBrakeCLI -i ” & origFilepath & ” -o ” & newFilepath & ” –preset=’AppleTV 2′ ”
But I want it to run also on .eyetv (ie 5 character extensions) files. Is it as simple as just adding
‘or name extension is “eyetv”‘ or will there be problems with the
set newFilepath to (characters 1 thru -5 of origFilepath as string) & “mp4′”
part? I didn’t understand the 1 thru -5 operation – please could you advise, many thanks
Richard
I have changed my default folder and have changed the preset to AppleTV2. It all compiled properly, but when I run it, I see the files all change to red and HandBrakeCLI doesn’t launch. I also don’t see the process running. Am I missing something? Is there a way to debug and see what is going wrong? This is my first attempt at AppleScripting.
Thanks.
OK…I am a new MAC user and owner so if my comments sound a little off please bear with me. I installed HandbrakeCLI and when I open it, a terminal window comes up with an error that says “missing input” Not sure what that means. However in the instructions, I saw nothing that says I even need to open HandbrakeCLI so I am not sure I should even worry about it. The thing that is really puzzling me is I ran this script by compiling and running in the Apple Script editor. All I get is the following message:
(
tell application “Finder”
get every file of entire contents of alias “MAC:Users:toine910:Hi:” whose (name extension = “avi” or name extension = “mpg”) and label index = 0
end tell)
Nothing appears to be happening yet all the files in my HI folder are red.
Please help!!!
Thanks,
Antoine
This is a great script. Has anyone been able to change the output folder? I see the comment above about changing origFilePath but I haven’t been able to figure out how to isolate the file name and tack that on to a new path.
Also – if I want this script to run whenever a new file is added to the original file folder, do I just need to uncomment the first and last line? Does this script have to reside in the same folder, or will it run whenever a new file is added to a subfolder of allFiles?
Thanks again for the very helpful script!
First of all, thanks a million for the script! (As well as the comments from others)
I was also looking for the solution to having the output directory changed as well. After a large number of failures adjusting the script itself, I decided to try and use automator to create a folder action incorporating the above script instead:
I created a folder called: “converter”
I created a new workflow in automator as a “folder action”.
I used the following steps:
1) “Find Finder items” (Select “converter” folder and have finder find all files with the extension .avi)
2) “Run Applescript” (This is where I copied the above script with some modifications as to the Handbrake quality)
3) “Find Finder Items” (Select “converter” folder and have finder find all files with the extension .mp4)
4) “Move finder items” (Have finder move the found mp4 to the “Automatically Add to iTunes” folder)
5) “Loop” (Loop automatically)
Now, all I have to do is drop those avi’s into the “converter”-folder to see them appear into iTunes automatically whenever handbrake is finished with them.
Obviously, you could set your dvd-ripper or torrent-program with such a “converter” folder as the target, making the whole process from ripping/download to inclusion into iTunes automated.
Now all I have to do is find a script that automatically adds art-work, correct tags, etc ;-)
Hope this is useful for someone!
I am getting an error -10004 every time I try to run this. Can anyone help get passed it?
Thanks!
I ran into the -10004 error too. Apparently it’s a security violation as of 10.6 / Snow Leopard. In effect we’re asking Finder to run a shell script, which is something our script should be doing. I fixed it by changing:
do shell script shellCommand
to:
tell current application
do shell script shellCommand
end tell
Hope this helps!
Hey guys. I keep getting an error when i try to set the file name which is searches the movies extensions. I’m trying”Macintosh HD:user:jason:movies:convert” Is this wrong. Or should i put something else?????
isn’t the folder called “users” (note the plural).
HELP! Something has gone wrong and it has deleted a bunch of my films. I managed to force quite the script after watching it delete all the A’s and some of the B’s of my film collection. Is there any way to recover these?
Many thanks
Al
I found this tool, VideoDrive ([aroona.net]), that can use HandBrakeCLI for batch processing. It has a lot of options and features to customize the conversion process. Then, you can make it download artwork and movie descriptions and at the file to iTunes. It even has folder actions so it can monitor when you download new files to automatically import them. Until now, I’m very impressed with it.
Thought I’d make this into a stand alone app find it here. [rapdigital.net]
This doesn’t seem to limit the number of HandbrakeCLI processes. If you have a folder of 15 video files then you will get 15 HandbrakeCLI process running. Is this correct?
On my machine it only does one at a time.
Any call to the shell via applescript is one process at a time.
This is a great script thanks a million. I have set it up as a folder action. When I drop multiple files into the folder they all process but only the first one gets deleted. The remaining files stay “grey”. Any thoughts?
Thx!
I’ve never done any AppleScript but this was a good way to start ’cause I really wanted to “automate” Handbrake…
By the way, does anyone know if there is a way to add ALL audio tracks by default? i don’t want to check how many tracks has every file… :-P
Thx again!
Great Script! Has someone an idea how to add external srt files? When I run it in the terminal it works fine. My adopted Script doesn’t work. That’s what I added:
–Assemble original and new file paths
set origFilepath to quoted form of POSIX path of (currentFile as alias)
set newFilepath to (characters 1 thru -5 of origFilepath as string) & “mp4′”
set srtEng to (characters 1 thru -6 of origFilepath as string) & “-eng.srt”
–Start the conversion
set shellCommand to “/usr/bin/HandBrakeCLI -i ” & origFilepath & ” -o ” & newFilepath & ” –srt-file ” & srtEng & ” –preset=’Normal’”
do shell script shellCommand
Thx
Sebastien
I just had forgotten a single quotation mark.
This Script is awesome. I just have one question. I have changed it to keep them in an MKV format with the extension of “1.mkv” so the out put is The Movie Name.1.mkv (so i know it has been converted) my only problem is that every time I run the script it wants to convert my entire library again. So my questions is, is there a way that I can have it flag some sort of Atribute in the file and have it skip the file if it has said atribute set? I have never used an applescript before but this thing is awesome. Any help that you can offer would be great!
Thanks,
Paul
Thank you Ryan for the great article. The article and user comments helped solve all of my questions for making the script work properly, however I have one strange request…
Is there a way to limit the number of cores used by HandBrake via the script? I know this will reduce performance and therefore take longer to complete the tasks but I would rather have a functioning computer while HandBrake is doing its job in the background. Say use 4 of my “8″ cores or any similar variance.
Thank you,
Casey
You might be able to use the -C or –cpu parameters to specify a lower number of CPUs available on your machine. You can find more info here about it: [trac.handbrake.fr]
WOW! Thank you, this is fantastic!!
Thankyou so much!
If I were to add a small function to send the successfully encoded file to iDentify for tagging where in this script would be the appropriate place to do so?
Good work script worked great!
Great work on this script. Had to modify the finder statement a little because it was not searching all of my recursive folders. But, otherwise bloody good work.
GREAT script! I have been using it for months and LOVE it.
Unfortunately, today, I started to get this error message.
error “Finder got an error: Can’t get alias \”Macintosh HD:Users:vhaghiri:Desktop:Converting:\”.” number -1728 from alias “Macintosh HD:Users:vhaghiri:Desktop:Convertin:”
Any idea why???
Sorry, typo
error “Finder got an error: Can’t get alias \”Macintosh HD:Users:vhaghiri:Desktop:Converting:\”.” number -1728 from alias “Macintosh HD:Users:vhaghiri:Desktop:Converting:
AWSOME! YOU ARE AWSOME, AND HAVE SAVED ME HOURS!!!! caps lock is necessary I have been converting everything manually.
Interesting issue… Oh right, I have this in an automator workflow (same as Anthonio), and I’ll add in a batch of mkv files and it will start to process them, but it will stop after a certain point. There are no red flagged files so nothing failed. Anybody come across this? Is there any way to restart
Guys,
awesome script, I use it together with an Automator Workflow, but I have trouble with one specific file…
Everytime the script starts, the file is labeled red, conversion is not working, or sometimes is added to my “not added” folder in iTunes. I can open the file, downloaded it again, same issue.
I changed the script a bit to my settings, with other files it´s working fine.
Anyone an idea??
I’m running the script and it finishes without an error but it never launches HandbrakeCLI
Any ideas on how to debug?
Does anyone know if this will work with videos that are currently in iPhoto? I have a bunch of videos that have been imported to iPhoto as .avi files and I want to convert them but keep the converted version in the same location in iPhoto.
Has anyone figured out how to use the AppleTV 3 preset in handbrake with this AWESOME script?? I tried the shellcommand above that somebody posted for AppleTV 2 but I couldn’t get it to work…
Ideas out there?
You can customise the output by looking up the parameters in the CLIguide.
[trac.handbrake.fr]
Just change the script to the same parameters used by the preset you want.
I’ve been running this script along with hazel for ages and it works great. I’d love to have a progress bar for the CLI encoding though.
The HandbrakeCLI guide says that the ETA data is logged through the standard output pipe. I’ve googled everything I can think of and I can’t find anywhere that explains how to get at this information and use it.
Even just a text file that logs the ETA every minute or so would be fantastic.
Any ideas?
I will try to take a look at this to see if I can add it to the script.
hello, thank you very much for all of your helps. the guides are really helpful.. however i found another problem while trying to add srt file to the conversion.
i got this error message:
–> error “sh: -c: line 0: unexpected EOF while looking for matching `”
anyone could help me to explain what’s wrong happened?
thanks in advance
i want to use automator or hazel to ensure that the files get imported into itunes, only after the conversion completes, not while the mp4s are made. is there a way to change the color label to the new file only after a successful conversion?
thanks, im new at this.