#! /usr/bin/python3 import os import threading import subprocess import glob import os import json import io import shutil import time import re class Encoder(threading.Thread): def __init__(self, directory=None, **kwargs): self.status = {} self.directory = directory for d in ("audio", "video"): os.makedirs(os.path.join(directory, d), exist_ok=True) return super().__init__(**kwargs) def run(self): while True: wait = True self.status = {"type": "encoder", "state": "idle"} for mtype in ("audio", "video"): for fn in glob.glob(os.path.join(self.directory, mtype, "*", "sucker.json")): fdir = os.path.dirname(fn) with open(fn) as f: obj = json.load(f) self.encode(mtype, fdir, obj) wait = False if wait: time.sleep(12) def encode(self, mtype, fdir, obj): if mtype == "audio": self.encode_audio(fdir, obj) else: self.encode_video(fdir, obj) shutil.rmtree(fdir) def encode_audio(self, fdir, obj): print("Not implemented") def encode_video(self, fdir, obj): self.status["state"] = "encoding" title = os.path.basename(fdir) self.status["title"] = title print("encoding", title, fdir) outfn = "%s.mkv" % title tmppath = os.path.join(fdir, outfn) outpath = os.path.join(self.directory, outfn) p = subprocess.Popen( [ "HandBrakeCLI", "--json", "--input", "%s/VIDEO_TS" % fdir, "--main-feature", "--native-language", "eng", "--preset", "Chromecast 1080p60 Surround", "--markers", "--all-audio", "--all-subtitles", "--aencoeder", "copy:aac,copy:ac3,av_aac", "--audio-copy-mask", "aac,ac3", "--audio-fallback", "aac", "--output", tmppath, ], encoding="utf-8", stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, ) # HandBrakeCLI spits out sort of JSON. # But Python has no built-in way to stream JSON objects. # Hence this kludge. progressRe = re.compile(r'^"Progress": ([0-9.]+),') for line in p.stdout: line = line.strip() m = progressRe.search(line) if m: progress = float(m[1]) self.status["complete"] = progress os.rename( src=tmppath, dst=outpath, ) pass # vi: sw=4 ts=4 et ai