Code

HandBrake your DVDs for iPad

No Comments »Written on December 31st, 2010 by
Categories: Python, Technology, Travel
HandBrake your DVDs for iPad

Who loves HandBrake? Can I get a “woohoo”?

For anyone who doesn’t know, HandBrake is a freebie app for Windows, Mac and Linux which rips DVDs to iGadget-compatible files with striking ease.

I’ve been jetting about a fair bit recently, and with the big Eurotrip on the horizon, it’s been all about gearing up for long plane trips. That means my beloved trusty iPad and a few choice movies.

I hate pirating movies. I have around 2,000 legit DVDs and BluRays, so downloading them again using torrents seems both tiresome and pointless. Enter HandBrake – just simmer for 30 mins on my beasty Mac Pro and serve warm to iPad.

At least that’s the theory. Even though the HandBrake Apple Universal profile uses AVC level 3.1, it marks its output files as 4.1, which iPad seems to arbitrarily reject for roughly 1 in 3 files.

Not to worry – it’s literally a case of changing one bit in the m4v file (that’s right – changing a 0 to a 1) and HandBrake output magically becomes iPad compatible. If you’re a glutton for punishment, you can use a hex editor and hunt around, or you can use this nifty Python script I cobbled together one bright Sunday morning.

#!/usr/bin/python

import sys
import os

if len(sys.argv) < 2:
	sys.exit("Target file not specified")

f = open(sys.argv[1],"r+b")
f.seek(0,os.SEEK_END)

marker = "avcC"+chr(1)
mlen = len(marker)

sys.stdout.write("Searching");

found = 0
while found==0:
	if(f.tell()%50000==0):
		sys.stdout.write(".")
		sys.stdout.flush()
	f.seek(-mlen-1,os.SEEK_CUR)
	s=f.read(mlen)
	if s==marker:
		found=1
	elif f.tell()==mlen:
		f.close()
		sys.exit("\nCould not find file marker")

f.seek(2,os.SEEK_CUR)
f.write(chr(0x1F))
print "\nFile successfully patched"

f.close()

If you’re not familiar with Python, don’t worry; just copy the code above into a new text file, call it ipadfix.py or similar, and run it from a command line with your file-to-be-fixed as the only parameter. If you’re on Windows, you’ll need to download and install Python. If not, make sure you enable execute permission on the script (chmod +x ipadfix.py), or it won’t run.

This solution is based on research I found posted in the Apple Support Forum.

I’ve only tested this solution on Mac – I have no idea if it works on other platforms, or if it’s even needed. It’s also the first Python script I ever wrote, so yes, it could be a little more efficient. OK, a lot more efficient! Hey, it gets the job done :)