#! /usr/bin/python3 import os import threading import subprocess import glob import os import json import io import shutil import time import re import logging class Encoder(threading.Thread): def __init__(self, directory=None, **kwargs): self.status = {} self.directory = directory ] 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): logging.error("Not implemented") def encode_video(self, fdir, obj): self.status["state"] = "encoding" title = os.path.basename(fdir) self.status["title"] = title num_tracks = len(self.status["tracks"]) for track in self.status["tracks"]: logging.info("encoding: %s (%s)" % (title, fdir)) outfn = "%s-%d.mkv" % (title, track) tmppath = os.path.join(fdir, outfn) outpath = os.path.join(self.directory, outfn) p = subprocess.Popen( [ "nice", "HandBrakeCLI", "--json", "--input", "%s/VIDEO_TS" % fdir, "--output", tmppath, "--title", track, "--native-language", "eng", "--markers", "--loose-anamorphic", "--all-subtitles", "--all-audio", "--aencoder", "copy", "--audio-copy-mask", "aac,ac3,mp3", "--audio-fallback", "aac", ], encoding="utf-8", stdout=subprocess.PIPE, stderr=None, ) # 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, ) # vi: sw=4 ts=4 et ai