feat(media): video versions: still frame + a version every screen plays (platform-v2 5.4e)
- services/video.py: background worker (one video at a time, low priority) makes a still frame (thumb/card/full WebP) and, when needed, play.mp4 (H.264+AAC, <=1920 px, HDR tone-mapped, faststart); the original is kept. Media.processing/progress (migration 0031, existing videos queued). ffmpeg from the pinned imageio-ffmpeg wheel; none = as uploaded. - MOV (video/quicktime) accepted; /api/media/file/<sha>/play served with ranges. - Signage plays the version (poster = still frame) and tells the screens playing it when ready. - Manager library: still frames in the grid, preparing progress, status in the details. - Tests: test_video.py (8), backend 541 passed; e2e media/signage/stack new checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -6,9 +6,13 @@ whatever copies the database must copy this folder too):
|
||||
<sha[:2]>/<sha>/{thumb,card,full}.webp images only, made on upload (and again on
|
||||
request if missing, e.g. after a partial restore)
|
||||
|
||||
<sha[:2]>/<sha>/play.mp4 videos: the version every screen plays, when one is needed
|
||||
(step 5.4e; videos get thumb/card/full from a still frame)
|
||||
|
||||
Images: JPEG, PNG, WebP, AVIF or GIF (first frame), turned upright from their EXIF, never made
|
||||
bigger than they are. Videos: MP4 or WebM, kept as uploaded (no transcoding on the venue's
|
||||
box); an MP4's length and size are read from its header when it has them.
|
||||
bigger than they are. Videos: MP4, MOV or WebM, kept as uploaded; an MP4's length and size are
|
||||
read from its header when it has them. Their still frame and playable version are made in the
|
||||
background afterwards (services/video.py).
|
||||
|
||||
Usage: what points at a media item registers a check with `register_usage(kind, fn)`,
|
||||
fn(db, media_id) -> [{"kind", "id", "name"}]. Delete is refused while any check finds a use.
|
||||
@@ -36,8 +40,8 @@ SIZES = {"thumb": 200, "card": 600, "full": 1920}
|
||||
WEBP_QUALITY = 80
|
||||
IMAGE_TYPES = {"JPEG": ("image/jpeg", "jpg"), "PNG": ("image/png", "png"),
|
||||
"WEBP": ("image/webp", "webp"), "GIF": ("image/gif", "gif"), "AVIF": ("image/avif", "avif")}
|
||||
VIDEO_TYPES = {"mp4": "video/mp4", "webm": "video/webm"}
|
||||
VARIANTS = (*SIZES, "original")
|
||||
VIDEO_TYPES = {"mp4": "video/mp4", "mov": "video/quicktime", "webm": "video/webm"}
|
||||
VARIANTS = (*SIZES, "original", "play")
|
||||
|
||||
_lock = threading.Lock() # one writer per file set at a time
|
||||
|
||||
@@ -63,6 +67,10 @@ def variant_path(sha: str, variant: str) -> str:
|
||||
return os.path.join(folder(sha), f"{variant}.webp")
|
||||
|
||||
|
||||
def play_path(sha: str) -> str:
|
||||
return os.path.join(folder(sha), "play.mp4")
|
||||
|
||||
|
||||
def image_of(item) -> dict | None:
|
||||
"""What an app needs to show a picture from the library: {"id", "name", "thumb", "card", "full"}."""
|
||||
if item is None or item.kind != "image":
|
||||
@@ -75,9 +83,20 @@ def urls(item) -> dict:
|
||||
out = {"original": f"{base}/original"}
|
||||
if item.kind == "image":
|
||||
out.update({v: f"{base}/{v}" for v in SIZES})
|
||||
else: # a video's still frame and version, once made (5.4e)
|
||||
if os.path.exists(variant_path(item.sha256, "thumb")):
|
||||
out.update({v: f"{base}/{v}" for v in SIZES})
|
||||
if os.path.exists(play_path(item.sha256)):
|
||||
out["play"] = f"{base}/play"
|
||||
return out
|
||||
|
||||
|
||||
def video_src(item) -> str:
|
||||
"""The file a screen plays: the version made for screens when there is one, else the original."""
|
||||
u = urls(item)
|
||||
return u.get("play") or u["original"]
|
||||
|
||||
|
||||
# ── receiving an upload ─────────────────────────────────────────────────────
|
||||
|
||||
def receive(src: IO[bytes], max_bytes: int) -> tuple[str, str, int]:
|
||||
@@ -109,11 +128,13 @@ def receive(src: IO[bytes], max_bytes: int) -> tuple[str, str, int]:
|
||||
|
||||
|
||||
def sniff(path: str) -> str | None:
|
||||
"""'image' | 'mp4' | 'webm' | None, from the first bytes (never from the name)."""
|
||||
"""'image' | 'mp4' | 'mov' | 'webm' | None, from the first bytes (never from the name)."""
|
||||
with open(path, "rb") as f:
|
||||
head = f.read(16)
|
||||
if head[4:8] == b"ftyp":
|
||||
return "image" if head[8:12] in (b"avif", b"avis") else "mp4"
|
||||
if head[8:12] in (b"avif", b"avis"):
|
||||
return "image"
|
||||
return "mov" if head[8:12] == b"qt " else "mp4"
|
||||
if head[:4] == b"\x1a\x45\xdf\xa3":
|
||||
return "webm"
|
||||
if head[:3] == b"\xff\xd8\xff" or head[:8] == b"\x89PNG\r\n\x1a\n" or head[:6] in (b"GIF87a", b"GIF89a") \
|
||||
@@ -161,8 +182,14 @@ def ensure_variant(item, variant: str) -> str | None:
|
||||
"""The file to serve for a variant, re-making image sizes that are missing."""
|
||||
if variant == "original":
|
||||
return original_path(item.sha256)
|
||||
if item.kind != "image" or variant not in SIZES:
|
||||
if variant == "play":
|
||||
p = play_path(item.sha256)
|
||||
return p if item.kind == "video" and os.path.exists(p) else None
|
||||
if variant not in SIZES:
|
||||
return None
|
||||
if item.kind != "image": # a video's still frame: made by services/video.py
|
||||
p = variant_path(item.sha256, variant)
|
||||
return p if os.path.exists(p) else None
|
||||
p = variant_path(item.sha256, variant)
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
@@ -192,7 +219,7 @@ def ingest(tmp: str, sha: str, size: int) -> dict:
|
||||
make_variants(img, sha)
|
||||
elif found in VIDEO_TYPES:
|
||||
ext = found
|
||||
info = {"kind": "video", "content_type": VIDEO_TYPES[found], **(mp4_info(tmp) if found == "mp4" else {})}
|
||||
info = {"kind": "video", "content_type": VIDEO_TYPES[found], **(mp4_info(tmp) if found in ("mp4", "mov") else {})}
|
||||
else:
|
||||
raise XeniaError("media.type")
|
||||
store(tmp, sha, ext)
|
||||
@@ -220,12 +247,14 @@ def files_info(item) -> dict:
|
||||
from PIL import Image
|
||||
out = {}
|
||||
for v in VARIANTS:
|
||||
p = original_path(item.sha256) if v == "original" else variant_path(item.sha256, v)
|
||||
p = original_path(item.sha256) if v == "original" else play_path(item.sha256) if v == "play" else variant_path(item.sha256, v)
|
||||
if not p or not os.path.exists(p):
|
||||
continue
|
||||
info = {"bytes": os.path.getsize(p), "width": None, "height": None}
|
||||
if v == "original":
|
||||
info.update(width=item.width, height=item.height)
|
||||
elif v == "play":
|
||||
info.update(zip(("width", "height"), fitted(item.width, item.height)))
|
||||
else:
|
||||
try:
|
||||
with Image.open(p) as im:
|
||||
@@ -236,6 +265,14 @@ def files_info(item) -> dict:
|
||||
return out
|
||||
|
||||
|
||||
def fitted(w, h, side: int = 1920) -> tuple:
|
||||
"""A video's size in its playable version (at most `side` on the long side, even numbers)."""
|
||||
if not w or not h:
|
||||
return None, None
|
||||
k = min(1.0, side / max(w, h))
|
||||
return int(w * k) // 2 * 2, int(h * k) // 2 * 2
|
||||
|
||||
|
||||
def store(tmp: str, sha: str, ext: str) -> None:
|
||||
"""Move the received temp file into place as the original."""
|
||||
d = folder(sha)
|
||||
|
||||
@@ -0,0 +1,300 @@
|
||||
"""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 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
|
||||
threading.Thread(target=_loop, daemon=True, name="video-versions").start()
|
||||
logger.info("video versions: worker started (%s)", ffmpeg())
|
||||
|
||||
Reference in New Issue
Block a user