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:
@@ -99,7 +99,7 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"display.look_default": (409, "The default look can't be deleted. Make another look the default first."),
|
||||
"display.not_a_display": (404, "Device {device_id} isn't a customer display."),
|
||||
"media.not_found": (404, "File {media_id} isn't in the media library."),
|
||||
"media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4 or WebM)."),
|
||||
"media.type": (422, "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4, MOV or WebM)."),
|
||||
"media.too_big": (413, "The file is too big (at most {max_mb} MB)."),
|
||||
"media.too_many_pixels": (422, "The picture is too large (at most {max_mp} megapixels)."),
|
||||
"media.unreadable": (422, "This picture can't be read. Save it again as JPG or PNG and upload it."),
|
||||
|
||||
@@ -66,6 +66,8 @@ async def lifespan(app: FastAPI):
|
||||
from services.tls_identity import ensure_tls_identity
|
||||
ensure_tls_identity()
|
||||
start_print_retry_thread()
|
||||
from services.video import start_worker as start_video_worker
|
||||
start_video_worker() # videos' still frames and playable versions (5.4e)
|
||||
pruned = prune_old_events(hours=24)
|
||||
if pruned:
|
||||
logger.info("ws_bus: pruned %d old sync_events", pruned)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Video versions (plan step 5.4e): a video's still frame and a version every screen plays are
|
||||
made in the background after the upload; the library shows how far it got.
|
||||
|
||||
Videos already in the library are queued (`waiting`) so they get theirs too.
|
||||
|
||||
Revision ID: 0031_video_versions
|
||||
Revises: 0030_signage_schedules
|
||||
Create Date: 2026-11-18 09:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '0031_video_versions'
|
||||
down_revision = '0030_signage_schedules'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('media', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('processing', sa.String(), nullable=True))
|
||||
batch_op.add_column(sa.Column('progress', sa.Integer(), nullable=True))
|
||||
op.execute("UPDATE media SET processing = 'waiting' WHERE kind = 'video'")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('media', schema=None) as batch_op:
|
||||
batch_op.drop_column('progress')
|
||||
batch_op.drop_column('processing')
|
||||
@@ -34,6 +34,11 @@ class Media(Base):
|
||||
created_at = Column(UTCDateTime, default=utcnow, nullable=False)
|
||||
# Shipped with the server (assets/builtin_media, step 5.4a): can't be deleted or renamed
|
||||
builtin = Column(Boolean, nullable=False, default=False, server_default='0')
|
||||
# Videos (step 5.4e, services/video.py): the still frame and the version every screen plays are
|
||||
# made in the background. waiting | working | done | failed; None = nothing to do (pictures,
|
||||
# or no video tool on this server). `progress` 0-100 while working.
|
||||
processing = Column(String, nullable=True)
|
||||
progress = Column(Integer, nullable=True)
|
||||
|
||||
uploader = relationship("User", lazy="joined")
|
||||
|
||||
|
||||
@@ -12,3 +12,4 @@ python-multipart==0.0.9
|
||||
cryptography==46.0.4
|
||||
alembic==1.14.0
|
||||
tzdata==2026.6
|
||||
imageio-ffmpeg==0.8.1
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
GET /api/media/{id} one item, with what uses it
|
||||
PATCH /api/media/{id} rename
|
||||
DELETE /api/media/{id} refused with `media.in_use` while something uses it
|
||||
GET /api/media/file/{sha}/{variant} the bytes: thumb | card | full (images, WebP)
|
||||
| original. Public (LAN, like the customer display's
|
||||
GET /api/media/file/{sha}/{variant} the bytes: thumb | card | full (WebP: a picture,
|
||||
or a video's still frame) | original | play (a video's
|
||||
version every screen plays, step 5.4e). Public (LAN, like the customer display's
|
||||
images), cached for a year: a URL never changes meaning.
|
||||
|
||||
Whoever manages the menu, the customer display, signage or the menu tablets manages the
|
||||
@@ -30,6 +31,7 @@ from database import get_db
|
||||
from datetime import datetime
|
||||
from models.media import Media
|
||||
from services import media as store
|
||||
from services import video
|
||||
|
||||
router = APIRouter()
|
||||
MANAGE = ("catalog.menu.manage", "customer_display.manage", "signage.manage", "menu_tablet.manage")
|
||||
@@ -53,6 +55,8 @@ class MediaOut(BaseModel):
|
||||
uploaded_by_name: Optional[str] = None
|
||||
created_at: datetime
|
||||
builtin: bool = False
|
||||
processing: Optional[str] = None # videos: waiting | working | done | failed (5.4e)
|
||||
progress: Optional[int] = None
|
||||
urls: dict = Field(default_factory=dict)
|
||||
|
||||
|
||||
@@ -131,6 +135,8 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
|
||||
info = store.ingest(tmp, sha, size)
|
||||
item = Media(name=(name or "").strip()[:120] or _name_from(file.filename),
|
||||
original_name=(file.filename or None), sha256=sha, bytes=size, uploaded_by=user.id, **info)
|
||||
if item.kind == "video":
|
||||
video.queued(item) # its still frame and playable version, in the background
|
||||
try:
|
||||
db.add(item)
|
||||
db.commit()
|
||||
@@ -138,6 +144,8 @@ def upload_media(response: Response, file: UploadFile = File(...), name: Optiona
|
||||
store.delete_files(sha)
|
||||
raise
|
||||
db.refresh(item)
|
||||
if item.processing:
|
||||
video.wake()
|
||||
return _out(item, UploadOut)
|
||||
|
||||
|
||||
@@ -149,10 +157,10 @@ def media_file(sha: str, variant: str, request: Request, db: Session = Depends(g
|
||||
path = store.ensure_variant(item, variant) if item is not None else None
|
||||
if not path or not os.path.exists(path):
|
||||
raise XeniaError("media.not_found", media_id=sha)
|
||||
ctype = item.content_type if variant == "original" else "image/webp"
|
||||
ctype = item.content_type if variant == "original" else "video/mp4" if variant == "play" else "image/webp"
|
||||
headers = {"Cache-Control": CACHE, "Accept-Ranges": "bytes"}
|
||||
rng = request.headers.get("range")
|
||||
if rng and variant == "original":
|
||||
if rng and variant in ("original", "play"):
|
||||
return _ranged(path, ctype, rng, headers)
|
||||
return FileResponse(path, media_type=ctype, headers=headers)
|
||||
|
||||
|
||||
@@ -37,6 +37,7 @@ from core.errors import XeniaError
|
||||
from database import get_db
|
||||
from models.signage import SignagePlaylist, SignageSchedule, SignageSlide
|
||||
from services import media as media_store
|
||||
from services import video as video_store
|
||||
from services.ws_bus import broadcast_sync
|
||||
|
||||
router = APIRouter()
|
||||
@@ -406,8 +407,12 @@ def _media_map(db, ids) -> dict:
|
||||
out = {}
|
||||
for m in (db.query(Media).filter(Media.id.in_(ids)).all() if ids else []):
|
||||
urls = media_store.urls(m)
|
||||
video = m.kind == "video"
|
||||
out[str(m.id)] = {"id": m.id, "kind": m.kind, "name": m.name, "width": m.width, "height": m.height,
|
||||
"duration_ms": m.duration_ms, "url": urls.get("full") or urls["original"],
|
||||
"duration_ms": m.duration_ms,
|
||||
# a video plays its version made for screens once there is one (5.4e)
|
||||
"url": media_store.video_src(m) if video else urls.get("full") or urls["original"],
|
||||
"poster": urls.get("full") if video else None,
|
||||
"thumb": urls.get("thumb"), "builtin": bool(m.builtin)}
|
||||
return out
|
||||
|
||||
@@ -428,6 +433,17 @@ def _uses(db, media_id: int) -> list:
|
||||
media_store.register_usage("signage_slide", _uses)
|
||||
|
||||
|
||||
def _video_done(db, media_id: int) -> None:
|
||||
"""A video's playable version is ready (services/video.py): the screens playing it switch to it."""
|
||||
playlists = {s.playlist_id for s in db.query(SignageSlide).filter(SignageSlide.kind == "video")
|
||||
if media_id in media_ids(s.content or {})}
|
||||
if playlists:
|
||||
_tell([d for pid in playlists for d in _screens_playing(db, pid)])
|
||||
|
||||
|
||||
video_store.on_done(_video_done)
|
||||
|
||||
|
||||
def tell_all_screens(db) -> None:
|
||||
"""Something every screen may show changed (the message of the day, the weather)."""
|
||||
_tell([d.id for d in _screens(db)])
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Video versions (plan step 5.4e): every uploaded video gets a still frame and, where needed, a
|
||||
version every screen plays (H.264 MP4, at most 1920 px), made in the background; the original
|
||||
is kept; signage plays the version and tells its screens when it is ready."""
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from services import video
|
||||
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
|
||||
from tests.test_media import media_dir, mp4, up # noqa: F401 (fixture + helpers)
|
||||
from tests.test_signage import playlist, screens, sent, slide # noqa: F401 (fixtures + helpers)
|
||||
|
||||
needs_tool = pytest.mark.skipif(not video.available(), reason="no ffmpeg (pip install imageio-ffmpeg)")
|
||||
|
||||
IPHONE = """Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'IMG_0042.MOV':
|
||||
Metadata:
|
||||
major_brand : qt
|
||||
Duration: 00:00:07.43, start: 0.000000, bitrate: 22912 kb/s
|
||||
Stream #0:0[0x1](und): Video: hevc (Main 10) (hvc1 / 0x31637668), yuv420p10le(tv, bt2020nc/bt2020/arib-std-b67), 3840x2160, 22570 kb/s, 29.98 fps, 30 tbr, 600 tbn (default)
|
||||
Side data:
|
||||
DOVI configuration record: version: 1.0, profile: 8, level: 7, rpu flag: 1, el flag: 0, bl flag: 1, compatibility id: 4
|
||||
displaymatrix: rotation of -90.00 degrees
|
||||
Stream #0:1[0x2](und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 186 kb/s (default)
|
||||
"""
|
||||
READY = """ Duration: 00:00:15.00, start: 0.000000, bitrate: 4100 kb/s
|
||||
Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(tv, bt709, progressive), 1920x1080 [SAR 1:1 DAR 16:9], 3970 kb/s, 25 fps (default)
|
||||
Stream #0:1[0x2](und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s (default)
|
||||
"""
|
||||
|
||||
|
||||
def test_reading_what_ffmpeg_says():
|
||||
phone = video.parse_probe(IPHONE)
|
||||
assert phone == {"duration_ms": 7430, "width": 2160, "height": 3840, "vcodec": "hevc", "pix_fmt": "yuv420p10le",
|
||||
"hdr": True, "acodec": "aac", "kbps": 22912, "rotation": 270} # filmed upright: shown tall
|
||||
ready = video.parse_probe(READY)
|
||||
assert (ready["vcodec"], ready["width"], ready["height"], ready["hdr"], ready["rotation"]) == ("h264", 1920, 1080, False, 0)
|
||||
assert video.parse_probe("garbage")["vcodec"] is None
|
||||
|
||||
|
||||
def test_which_videos_need_a_version():
|
||||
ready = video.parse_probe(READY)
|
||||
assert video.needs_version(ready, "mp4") is False # plays everywhere as it is
|
||||
assert video.needs_version(ready, "mov") is True # MOV / WebM: not every TV
|
||||
assert video.needs_version(ready, "webm") is True
|
||||
assert video.needs_version(video.parse_probe(IPHONE), "mov") is True # HEVC, 4K, HDR
|
||||
for change in ({"vcodec": "hevc"}, {"width": 3840, "height": 2160}, {"pix_fmt": "yuv420p10le"}, {"hdr": True},
|
||||
{"acodec": "opus"}, {"kbps": 30000}):
|
||||
assert video.needs_version({**ready, **change}, "mp4") is True, change
|
||||
assert video.needs_version({**ready, "acodec": None}, "mp4") is False # no sound is fine
|
||||
|
||||
|
||||
def make(path, args):
|
||||
r = subprocess.run([video.ffmpeg(), "-hide_banner", "-y", *args, str(path)], capture_output=True)
|
||||
assert r.returncode == 0, r.stderr.decode()[-500:]
|
||||
return path.read_bytes()
|
||||
|
||||
|
||||
def phone_video(tmp_path):
|
||||
"""A 2 s 2560 × 1440 HEVC MOV in HDR (10-bit HLG) with sound, like an iPhone's."""
|
||||
return make(tmp_path / "IMG_0042.MOV", ["-f", "lavfi", "-i", "testsrc2=s=2560x1440:r=25:d=2", "-f", "lavfi", "-i", "sine=d=2",
|
||||
"-vf", "setparams=color_primaries=bt2020:color_trc=arib-std-b67:colorspace=bt2020nc",
|
||||
"-pix_fmt", "yuv420p10le", "-c:v", "libx265", "-x265-params", "log-level=error", "-tag:v", "hvc1", "-c:a", "aac", "-shortest"])
|
||||
|
||||
|
||||
def tv_video(tmp_path):
|
||||
"""A 2 s 1280 × 720 H.264 MP4: already plays everywhere."""
|
||||
return make(tmp_path / "ready.mp4", ["-f", "lavfi", "-i", "testsrc2=s=1280x720:r=25:d=2", "-c:v", "libx264", "-pix_fmt", "yuv420p"])
|
||||
|
||||
|
||||
@needs_tool
|
||||
def test_a_phone_video_gets_a_still_frame_and_a_version_every_screen_plays(client, db, owner_h, media_dir, tmp_path):
|
||||
"""Done when (5.4e): an uploaded phone video gets its still frame and a version every screen plays."""
|
||||
data = phone_video(tmp_path)
|
||||
r = up(client, owner_h, data, name="IMG_0042.MOV", ctype="video/quicktime")
|
||||
assert r.status_code == 201, r.text
|
||||
m = r.json()
|
||||
assert (m["kind"], m["content_type"], m["processing"]) == ("video", "video/quicktime", "waiting")
|
||||
assert set(m["urls"]) == {"original"} # nothing made yet
|
||||
seen = []
|
||||
video.on_done(lambda db_, mid: seen.append(mid))
|
||||
try:
|
||||
assert video.process_next(db) is True
|
||||
finally:
|
||||
video._done_listeners.pop()
|
||||
assert video.process_next(db) is False and seen == [m["id"]]
|
||||
got = client.get(f"/api/media/{m['id']}", headers=owner_h).json()
|
||||
assert (got["processing"], got["progress"], got["width"], got["height"], got["duration_ms"]) == ("done", None, 2560, 1440, 2000)
|
||||
assert set(got["urls"]) == {"original", "thumb", "card", "full", "play"}
|
||||
assert set(got["files"]) == {"original", "thumb", "card", "full", "play"}
|
||||
assert (got["files"]["play"]["width"], got["files"]["play"]["height"]) == (1920, 1080)
|
||||
assert (got["files"]["full"]["width"], got["files"]["thumb"]["width"]) == (1920, 200) # the still frame's sizes
|
||||
orig = client.get(got["urls"]["original"])
|
||||
assert orig.content == data and orig.headers["content-type"] == "video/quicktime" # the original, untouched
|
||||
play = client.get(got["urls"]["play"])
|
||||
assert play.status_code == 200 and play.headers["content-type"] == "video/mp4" and "immutable" in play.headers["cache-control"]
|
||||
part = client.get(got["urls"]["play"], headers={"Range": "bytes=0-99"})
|
||||
assert part.status_code == 206 and len(part.content) == 100
|
||||
out = tmp_path / "play.mp4"
|
||||
out.write_bytes(play.content)
|
||||
info = video.probe(str(out))
|
||||
assert (info["vcodec"], info["pix_fmt"], info["acodec"], info["width"], info["height"]) == ("h264", "yuv420p", "aac", 1920, 1080)
|
||||
assert b"moov" in play.content[:4096] # starts playing at once
|
||||
assert client.get(got["urls"]["thumb"]).headers["content-type"] == "image/webp"
|
||||
|
||||
|
||||
@needs_tool
|
||||
def test_a_video_that_already_plays_everywhere_is_left_as_it_is(client, db, owner_h, media_dir, tmp_path):
|
||||
m = up(client, owner_h, tv_video(tmp_path), name="ready.mp4", ctype="video/mp4").json()
|
||||
video.process_next(db)
|
||||
got = client.get(f"/api/media/{m['id']}", headers=owner_h).json()
|
||||
assert got["processing"] == "done" and set(got["urls"]) == {"original", "thumb", "card", "full"} # a still frame, no copy
|
||||
from models.media import Media
|
||||
from services import media as store
|
||||
assert store.video_src(db.get(Media, m["id"])) == got["urls"]["original"]
|
||||
|
||||
|
||||
@needs_tool
|
||||
def test_a_broken_video_fails_and_its_original_stays(client, db, owner_h, media_dir):
|
||||
m = up(client, owner_h, mp4(), name="broken.mp4", ctype="video/mp4").json() # a header and no pictures
|
||||
video.process_next(db)
|
||||
got = client.get(f"/api/media/{m['id']}", headers=owner_h).json()
|
||||
assert got["processing"] == "failed" and set(got["urls"]) == {"original"}
|
||||
assert client.get(got["urls"]["original"]).status_code == 200
|
||||
assert not [n for n in os.listdir(os.path.join(str(media_dir), m["sha256"][:2], m["sha256"])) if "part" in n] # nothing half-made
|
||||
|
||||
|
||||
@needs_tool
|
||||
def test_signage_plays_the_version_and_tells_its_screens(client, db, owner_h, media_dir, tmp_path, screens, sent):
|
||||
"""Done when (5.4e): … and the signage player uses it."""
|
||||
m = up(client, owner_h, phone_video(tmp_path), name="promo.mov", ctype="video/quicktime").json()
|
||||
p = playlist(client, owner_h, orientation="landscape")
|
||||
slide(client, owner_h, p["id"], "video", content={"media_id": m["id"]})
|
||||
client.put(f"/api/signage/screens/{screens[1]['id']}", headers=owner_h, json={"playlist_id": p["id"]})
|
||||
before = client.get("/api/signage/screen", headers=screens[1]["h"]).json()
|
||||
vid = before["playlist"]["media"][str(m["id"])]
|
||||
assert vid["url"] == m["urls"]["original"] and vid["poster"] is None # not made yet: the original
|
||||
sent.clear()
|
||||
video.process_next(db)
|
||||
assert ("signage.changed", [screens[1]["id"]]) in sent # only the screen playing it
|
||||
after = client.get("/api/signage/screen", headers=screens[1]["h"]).json()
|
||||
vid = after["playlist"]["media"][str(m["id"])]
|
||||
assert vid["url"].endswith("/play") and vid["poster"].endswith("/full") and after["version"] != before["version"]
|
||||
|
||||
|
||||
def test_without_the_tool_videos_play_as_uploaded(client, owner_h, media_dir, monkeypatch):
|
||||
monkeypatch.setattr(video, "_tool", [None])
|
||||
m = up(client, owner_h, mp4(), name="v.mp4", ctype="video/mp4").json()
|
||||
assert m["processing"] is None and set(m["urls"]) == {"original"}
|
||||
|
||||
|
||||
def test_a_mov_is_taken_as_a_video(client, owner_h, media_dir):
|
||||
data = mp4().replace(b"isom\x00\x00\x02\x00", b"qt \x00\x00\x02\x00", 1)
|
||||
m = up(client, owner_h, data, name="IMG_1.MOV", ctype="video/quicktime").json()
|
||||
assert (m["kind"], m["content_type"], m["duration_ms"]) == ("video", "video/quicktime", 12500)
|
||||
assert m["urls"]["original"].endswith("/original")
|
||||
Reference in New Issue
Block a user