Files
xenia-pos-local/local_backend/tests/test_video.py
T
bonaminandClaude Opus 5.5 b5361e10ca 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>
2026-11-18 02:10:22 +02:00

157 lines
9.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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")