- THIRD_PARTY_NOTICES.md in the backend image: FFmpeg (GPL v3, via imageio-ffmpeg) - video.requeue_missing(): videos whose still frame is gone (a partial restore) are prepared again when the backend starts (+1 test, backend 542 passed) - pack README: data/media belongs in every site backup with pos.db - stack.mjs: the test video is unique per run (the stack keeps its data between runs) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
321 lines
13 KiB
Python
321 lines
13 KiB
Python
"""Video versions (plan step 5.4e): what pictures get on upload, videos get in the background.
|
|
|
|
For every uploaded video the server makes
|
|
* a still frame, kept as the same three WebP sizes a picture gets (thumb / card / full): the
|
|
library shows it, and screens show it while the video loads;
|
|
* where needed, a version every screen plays (`play.mp4`: H.264 + AAC in MP4, at most 1920 px
|
|
on its long side, 8-bit colour, the index at the front so it starts playing at once).
|
|
A phone video usually needs it (HEVC from iPhones, 4K, HDR, MOV / WebM); one that already
|
|
plays everywhere (H.264 MP4 at TV size) is left alone and played as it is.
|
|
The untouched original is always kept.
|
|
|
|
The tool is ffmpeg, from the `imageio-ffmpeg` package (one pinned static build for Linux x86-64,
|
|
ARM64 and the Windows dev machine) or `XENIA_FFMPEG` / the system's. Without it, videos are
|
|
kept and played as uploaded, as before this step.
|
|
|
|
One video at a time, in one background thread (`start_worker`, main.py), at low priority and
|
|
two threads so the tills stay quick. `Media.processing`: waiting → working (progress 0-100) →
|
|
done | failed. A restart picks up what was waiting or half done. When a video is done, whoever
|
|
registered with `on_done` hears of it (signage tells the screens playing it).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import threading
|
|
from typing import Callable
|
|
|
|
from services import media as store
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
MAX_SIDE = 1920
|
|
MAX_KBPS = 12_000 # above this a TV over Wi-Fi may stutter
|
|
THREADS = 2
|
|
_tool: list = [] # [path or None], found once
|
|
_wake = threading.Event()
|
|
_done_listeners: list[Callable] = []
|
|
|
|
|
|
# ── the tool ─────────────────────────────────────────────────────────────────
|
|
|
|
def ffmpeg() -> str | None:
|
|
if not _tool:
|
|
path = os.environ.get("XENIA_FFMPEG") or None
|
|
if not path:
|
|
try:
|
|
import imageio_ffmpeg
|
|
path = imageio_ffmpeg.get_ffmpeg_exe()
|
|
except Exception:
|
|
path = shutil.which("ffmpeg")
|
|
_tool.append(path if path and os.path.exists(path) else None)
|
|
return _tool[0]
|
|
|
|
|
|
def available() -> bool:
|
|
return ffmpeg() is not None
|
|
|
|
|
|
def _run(args: list[str], timeout: float = 120) -> subprocess.CompletedProcess:
|
|
return subprocess.run([ffmpeg(), "-hide_banner", "-nostdin", *args], capture_output=True, timeout=timeout,
|
|
**_low_priority())
|
|
|
|
|
|
def _low_priority() -> dict:
|
|
if os.name == "posix":
|
|
return {"preexec_fn": lambda: os.nice(10)}
|
|
return {"creationflags": getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)}
|
|
|
|
|
|
# ── what a file is ───────────────────────────────────────────────────────────
|
|
|
|
_DURATION = re.compile(r"Duration: (\d+):(\d+):(\d+(?:\.\d+)?)")
|
|
_BITRATE = re.compile(r"Duration: .*?bitrate: (\d+) kb/s")
|
|
_VIDEO = re.compile(r"Stream #\d+:\d+.*?: Video: (\w+).*?, (\w+)(\([^)]*\))?, (\d+)x(\d+)")
|
|
_AUDIO = re.compile(r"Stream #\d+:\d+.*?: Audio: (\w+)")
|
|
_ROTATION = re.compile(r"rotation of (-?\d+(?:\.\d+)?) degrees")
|
|
|
|
|
|
def parse_probe(text: str) -> dict:
|
|
"""What `ffmpeg -i` says about a file (pure; tested with its real output):
|
|
{duration_ms, width, height (as shown, after rotation), vcodec, pix_fmt, hdr, acodec, kbps, rotation}."""
|
|
out: dict = {"duration_ms": None, "width": None, "height": None, "vcodec": None, "pix_fmt": None,
|
|
"hdr": False, "acodec": None, "kbps": None, "rotation": 0}
|
|
m = _DURATION.search(text)
|
|
if m:
|
|
h, mi, s = m.groups()
|
|
out["duration_ms"] = int(round((int(h) * 3600 + int(mi) * 60 + float(s)) * 1000))
|
|
m = _BITRATE.search(text)
|
|
if m:
|
|
out["kbps"] = int(m.group(1))
|
|
m = _VIDEO.search(text)
|
|
if m:
|
|
out["vcodec"], out["pix_fmt"] = m.group(1), m.group(2)
|
|
colour = m.group(3) or ""
|
|
out["hdr"] = "arib-std-b67" in colour or "smpte2084" in colour
|
|
out["width"], out["height"] = int(m.group(4)), int(m.group(5))
|
|
m = _AUDIO.search(text)
|
|
if m:
|
|
out["acodec"] = m.group(1)
|
|
m = _ROTATION.search(text)
|
|
if m:
|
|
out["rotation"] = int(round(float(m.group(1)))) % 360
|
|
if out["rotation"] in (90, 270) and out["width"]:
|
|
out["width"], out["height"] = out["height"], out["width"]
|
|
return out
|
|
|
|
|
|
def probe(path: str) -> dict:
|
|
return parse_probe(_run(["-i", path], timeout=60).stderr.decode("utf-8", "replace"))
|
|
|
|
|
|
def needs_version(info: dict, container: str) -> bool:
|
|
"""Does this video need a version every screen plays? (pure)
|
|
`container` is the original's extension: mp4 | mov | webm."""
|
|
if container != "mp4" or info.get("vcodec") != "h264":
|
|
return True
|
|
if info.get("pix_fmt") not in ("yuv420p", "yuvj420p") or info.get("hdr"):
|
|
return True
|
|
if max(info.get("width") or 0, info.get("height") or 0) > MAX_SIDE:
|
|
return True
|
|
if info.get("acodec") not in (None, "aac", "mp3"):
|
|
return True
|
|
return (info.get("kbps") or 0) > MAX_KBPS
|
|
|
|
|
|
# ── making the files ─────────────────────────────────────────────────────────
|
|
|
|
def _fit() -> str:
|
|
return (f"scale=w='min({MAX_SIDE},iw)':h='min({MAX_SIDE},ih)':force_original_aspect_ratio=decrease"
|
|
f":force_divisible_by=2")
|
|
|
|
|
|
def _colour(info: dict) -> str:
|
|
"""HDR (iPhones film in HDR) to ordinary colour so it doesn't look washed out; else 8-bit 4:2:0."""
|
|
if info.get("hdr"):
|
|
return ("zscale=t=linear:npl=100,format=gbrpf32le,zscale=p=bt709,tonemap=hable:desat=0,"
|
|
"zscale=t=bt709:m=bt709:r=tv,format=yuv420p")
|
|
return "format=yuv420p"
|
|
|
|
|
|
def still_frame(src: str, sha: str, info: dict) -> None:
|
|
"""The picture shown for the video: a frame a second in (or half way in a short one), as WebP sizes."""
|
|
tmp = os.path.join(store.folder(sha), "frame.part.png")
|
|
dur = info.get("duration_ms") or 0
|
|
at = min(1.0, dur / 2000) if dur else 0
|
|
filters = ",".join([_colour(info), _fit()])
|
|
try:
|
|
for seek in ((at, 0) if at else (0,)):
|
|
r = _run(["-y", "-ss", f"{seek:.2f}", "-i", src, "-frames:v", "1", "-vf", filters, "-update", "1", tmp])
|
|
if r.returncode == 0 and os.path.exists(tmp) and os.path.getsize(tmp) > 0:
|
|
break
|
|
else:
|
|
raise RuntimeError(r.stderr.decode("utf-8", "replace")[-400:])
|
|
img, _ = store.open_image(tmp)
|
|
store.make_variants(img, sha)
|
|
finally:
|
|
store._remove(tmp)
|
|
|
|
|
|
def convert(src: str, sha: str, info: dict, on_progress: Callable[[int], None]) -> None:
|
|
"""The version every screen plays → play.mp4 (written aside and moved in when complete)."""
|
|
dest = store.play_path(sha)
|
|
tmp = dest + ".part.mp4"
|
|
args = [ffmpeg(), "-hide_banner", "-nostdin", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a:0?",
|
|
"-vf", ",".join([_colour(info), _fit()]),
|
|
"-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-profile:v", "high", "-level:v", "4.1",
|
|
"-maxrate", "8M", "-bufsize", "16M", "-threads", str(THREADS),
|
|
"-c:a", "aac", "-b:a", "128k", "-ac", "2",
|
|
"-movflags", "+faststart", "-progress", "pipe:1", "-nostats", tmp]
|
|
dur_us = (info.get("duration_ms") or 0) * 1000
|
|
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **_low_priority())
|
|
err: list[bytes] = []
|
|
drain = threading.Thread(target=lambda: err.append(proc.stderr.read()), daemon=True)
|
|
drain.start()
|
|
last = -1
|
|
try:
|
|
for raw in proc.stdout:
|
|
line = raw.decode("ascii", "replace").strip()
|
|
if line.startswith("out_time_us=") and dur_us:
|
|
try:
|
|
pct = max(0, min(99, int(int(line.split("=", 1)[1]) * 100 / dur_us)))
|
|
except ValueError:
|
|
continue
|
|
if pct >= last + 5:
|
|
last = pct
|
|
on_progress(pct)
|
|
proc.wait()
|
|
drain.join(5)
|
|
if proc.returncode != 0 or not os.path.exists(tmp):
|
|
raise RuntimeError(b"".join(err).decode("utf-8", "replace")[-400:])
|
|
os.replace(tmp, dest)
|
|
finally:
|
|
if proc.poll() is None:
|
|
proc.kill()
|
|
store._remove(tmp)
|
|
|
|
|
|
# ── the queue ────────────────────────────────────────────────────────────────
|
|
|
|
def on_done(fn: Callable) -> None:
|
|
"""fn(db, media_id) after a video's versions are made (signage tells its screens)."""
|
|
_done_listeners.append(fn)
|
|
|
|
|
|
def queued(item) -> None:
|
|
"""A video was just added: mark it for the worker (or leave it as is with no tool)."""
|
|
item.processing = "waiting" if available() else None
|
|
item.progress = None
|
|
|
|
|
|
def wake() -> None:
|
|
_wake.set()
|
|
|
|
|
|
def process_next(db) -> bool:
|
|
"""Make the versions of the next waiting video. → False when nothing waits."""
|
|
from models.media import Media
|
|
item = db.query(Media).filter(Media.kind == "video", Media.processing.in_(("waiting", "working"))) \
|
|
.order_by(Media.id).first()
|
|
if item is None:
|
|
return False
|
|
media_id, sha = item.id, item.sha256
|
|
item.processing, item.progress = "working", 0
|
|
db.commit()
|
|
|
|
def progress(pct: int) -> None:
|
|
db.query(Media).filter(Media.id == media_id).update({"progress": pct})
|
|
db.commit()
|
|
|
|
state = "done"
|
|
try:
|
|
src = store.original_path(sha)
|
|
if not src:
|
|
raise RuntimeError("the original is missing")
|
|
info = probe(src)
|
|
found = db.get(Media, media_id)
|
|
if found is None:
|
|
return True
|
|
for k in ("duration_ms", "width", "height"): # as shown (a phone video filmed upright is tall)
|
|
if info.get(k):
|
|
setattr(found, k, info[k])
|
|
db.commit()
|
|
still_frame(src, sha, info)
|
|
container = src.rsplit(".", 1)[-1].lower()
|
|
if needs_version(info, container):
|
|
convert(src, sha, info, progress)
|
|
except Exception as e: # the original still plays where it can
|
|
logger.warning("video %s: versions not made: %s", media_id, e)
|
|
state = "failed"
|
|
db.expire_all()
|
|
found = db.get(Media, media_id)
|
|
if found is None: # deleted while it was being made
|
|
store.delete_files(sha)
|
|
return True
|
|
found.processing, found.progress = state, None
|
|
db.commit()
|
|
for fn in _done_listeners:
|
|
try:
|
|
fn(db, media_id)
|
|
except Exception as e:
|
|
logger.warning("video %s: a listener failed: %s", media_id, e)
|
|
return True
|
|
|
|
|
|
def _loop() -> None:
|
|
from database import SessionLocal
|
|
while True:
|
|
try:
|
|
db = SessionLocal()
|
|
try:
|
|
while process_next(db):
|
|
pass
|
|
finally:
|
|
db.close()
|
|
except Exception as e:
|
|
logger.warning("video worker: %s", e)
|
|
_wake.wait(60)
|
|
_wake.clear()
|
|
|
|
|
|
def requeue_missing(db=None) -> int:
|
|
"""Videos marked done whose still frame is missing (a restore without all of data/media):
|
|
made again. → how many."""
|
|
from database import SessionLocal
|
|
from models.media import Media
|
|
own = db is None
|
|
db = db or SessionLocal()
|
|
try:
|
|
n = 0
|
|
for m in db.query(Media).filter(Media.kind == "video", Media.processing == "done"):
|
|
if store.original_path(m.sha256) and not os.path.exists(store.variant_path(m.sha256, "thumb")):
|
|
m.processing, n = "waiting", n + 1
|
|
db.commit()
|
|
return n
|
|
finally:
|
|
if own:
|
|
db.close()
|
|
|
|
|
|
def start_worker() -> None:
|
|
"""main.py: one background thread. With no tool, waiting videos are just played as uploaded."""
|
|
if not available():
|
|
from database import SessionLocal
|
|
from models.media import Media
|
|
db = SessionLocal()
|
|
try:
|
|
db.query(Media).filter(Media.processing.in_(("waiting", "working"))) \
|
|
.update({"processing": None, "progress": None}, synchronize_session=False)
|
|
db.commit()
|
|
finally:
|
|
db.close()
|
|
logger.warning("video versions: no ffmpeg on this server; videos play as uploaded")
|
|
return
|
|
requeue_missing()
|
|
threading.Thread(target=_loop, daemon=True, name="video-versions").start()
|
|
logger.info("video versions: worker started (%s)", ffmpeg())
|
|
|