media-sucker/src/encoder.py

98 lines
2.9 KiB
Python
Raw Normal View History

2022-02-26 08:05:20 -07:00
#! /usr/bin/python3
import os
import threading
import subprocess
import glob
import os
import json
import io
import shutil
import time
import re
2022-08-20 16:42:53 -06:00
import logging
2022-02-26 08:05:20 -07:00
class Encoder(threading.Thread):
def __init__(self, directory=None, **kwargs):
self.status = {}
self.directory = directory
2022-08-21 15:58:11 -06:00
] return super().__init__(**kwargs)
2022-02-26 08:05:20 -07:00
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):
2022-08-20 16:42:53 -06:00
logging.error("Not implemented")
2022-02-26 08:05:20 -07:00
def encode_video(self, fdir, obj):
self.status["state"] = "encoding"
title = os.path.basename(fdir)
self.status["title"] = title
2022-08-21 15:58:11 -06:00
num_tracks = len(self.status["tracks"])
for track in self.status["tracks"]:
2022-02-26 08:05:20 -07:00
2022-08-21 15:58:11 -06:00
logging.info("encoding: %s (%s)" % (title, fdir))
2022-02-26 08:05:20 -07:00
2022-08-21 15:58:11 -06:00
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,
)
2022-02-26 08:05:20 -07:00
# vi: sw=4 ts=4 et ai