Source

iviewautodownload / python-iview / handbrake.py

Full commit

import subprocess
import fnmatch
import os

HANDBRAKE = r"C:\Program Files\Handbrake\HandBrakeCLI.exe" 
WIDTH = 960
HEIGHT = 640

def _setpriority(pid=None,priority=0):
    """ Set The Priority of a Windows Process.  Priority is a value between 0-5 where
        2 is normal priority.  Default sets the priority of the current
        python process but can take any valid process ID. """
    
    import win32api,win32process,win32con
        
    priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
                       win32process.BELOW_NORMAL_PRIORITY_CLASS,
                       win32process.NORMAL_PRIORITY_CLASS,
                       win32process.ABOVE_NORMAL_PRIORITY_CLASS,
                       win32process.HIGH_PRIORITY_CLASS,
                       win32process.REALTIME_PRIORITY_CLASS]
    if pid == None:
        pid = win32api.GetCurrentProcessId()
    handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
    win32process.SetPriorityClass(handle, priorityclasses[priority])

def makenice():
    '''Make the current process "nice" (or low priority) on most platforms.
    '''
    if hasattr(os, 'nice'):
        os.nice(15)
    else:
        _setpriority()

def iphoneconvert(srcpath, outputpath):
    '''Converts the passed in show at path to an iPhone video at outputpath
    '''
    # Force low priority
    makenice()
    
    cmd = [HANDBRAKE, '-i', 
            srcpath,
            '-t', '1', '-c', '1', '-o', 
            outputpath,
            '-f', 'mp4',
            '-e', 'x264', '-q', '20', '-a', '1', '-E', 'faac', '-6', 'dpl2',
            '-R', '48', '-B', '128', '-D', '0.0', '-x', 
            'cabac=0:ref=2:me=umh:bframes=0:subq=6:8x8dct=0:trellis=0:weightb=0',
            '-v', '1',
            '--maxWidth', str(WIDTH), '--maxHeight', str(HEIGHT)]
    print "Command:", ' '.join(cmd)
    
    p = subprocess.Popen(cmd)
    p.wait()
    if p.returncode != 0:
        print 'Error encoding file: %s' % p.returncode
    else:
        print 'Encoded file OK.'

def processdir(srcdir, outputdir, match='*'):
    srcfns = []
    for fn in os.listdir(srcdir):
        if fnmatch.fnmatch(fn, match):
            srcfns.append(os.path.join(srcdir, fn))
    for fn in srcfns:
        outfn = os.path.basename(fn)
        outfn = os.path.splitext(outfn)[0] + '.mp4'
        outfn = os.path.join(outputdir, outfn)
        print fn, outfn
        if os.path.isfile(outfn):
            print 'File exists, skipping...'
        else:
            iphoneconvert(fn, outfn)

if __name__ == '__main__':
    processdir(r'H:\Media\Jade\Dora Undercover', r'H:\iPhone\Dora Undercover', '*')