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:
+1
-1
@@ -47,7 +47,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
|
||||
| `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` |
|
||||
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
|
||||
| `local_backend/routers/customer_display.py`, `models/display_look.py`, `terminal/src/apps/customer-display/` | The customer display (3.4, 5.3): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is a **look** (`display_looks`: name, `is_default`, config = style, message, theme, QR, pictures as media library ids; looks register their media usage). One look is the venue's default; a display shows the look in its device config `look` (a `ref` to `display_looks`, also set from Settings → Customer display through `PUT /api/display/displays/{id}/look`) or the default. A look's change sends `display.settings` only to the displays showing it. Pictures are served from the library (`full` for image / slides, `card` for the logo). The POS's last state lives in memory |
|
||||
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m` |
|
||||
| `local_backend/routers/media.py`, `services/media.py`, `models/media.py`; manager `src/pages/media/` | The media library (5.1, 5.2): every picture and video once, by sha256, under `/app/data/media/<sha[:2]>/<sha>/` (the untouched original + `thumb` 200 / `card` 600 / `full` 1920 WebP for pictures, AVIF accepted; videos kept as uploaded). Served public by hash at `/api/media/file/<sha>/<variant>` with year-long `immutable` caching (a different file is a different URL; byte ranges for video). The display name is only for people; files on disk are named by the backend. Whoever manages the menu, customer display, signage or menu tablets manages it. **What points at media has a `media_id` column and registers `register_usage(kind, fn)`** (products and categories in `routers/products.py`) so delete is refused (`media.in_use`) while it's used. APIs give `image` = `{id, name, thumb, card, full}` (`services.media.image_of`); a product's `image_url` is its card size. Manager: the Media page (batch upload, details) and `MediaField` (upload on the spot / pick from the library / "Name it after" with `latin()` from `@xenia/i18n`) for any form that takes a picture. The waiter fetches the menu's photos ahead (`services/photoCache.js`; PWA: workbox `xenia-media` cache-first) so they show offline. Upload limits: 20 MB pictures, 200 MB videos; every nginx config sets `client_max_body_size 250m`. **Videos (5.4e, `services/video.py`):** MP4 / MOV / WebM kept as uploaded; a background thread (`start_worker` in `main.py`'s lifespan, one video at a time, low priority, 2 threads) makes the still frame (the same `thumb` / `card` / `full` WebP) and, when `needs_version()` says so (not H.264 MP4, over 1920 px, 10-bit / HDR, other audio, > 12 Mbps), `play.mp4` (H.264 + AAC, ≤ 1920 px, HDR tone-mapped, faststart). `Media.processing` waiting → working (`progress`) → done | failed; migration 0031 queues existing videos. ffmpeg comes from the pinned `imageio-ffmpeg` wheel (static, Linux x86-64 / ARM64 / Windows; `XENIA_FFMPEG` overrides); without it videos stay as uploaded (`processing` null). `urls` gains `thumb`/`card`/`full`/`play` as they exist; `media.video_src()` is what a screen plays; `video.on_done(fn)` listeners (signage tells the screens playing it) |
|
||||
| `local_backend/routers/signage.py`, `models/signage.py`, `assets/builtin_media/` | Digital signage (5.4a): **playlists** (name, orientation, default transition) of **slides** (kind menu / image / video / text, position, duration, transition, video to its end, on / off, days / hours / dates window, `content` typed per kind in the router: extra fields refused, pictures and videos as media ids, walked by `media_ids()` for the library's usage check). A screen's device config: `playlist` (ref `signage_playlists`), `orientation`, `rotation`; `GET /api/signage/screen` gives it the playlist resolved (enabled slides, media addresses, a `version` hash); changes send `signage.changed` only to the screens playing that playlist. **Built-in pictures:** files in `assets/builtin_media/` are imported at start (`services.media.import_builtin`, `media.builtin`), listed as their own collection, never deleted or renamed. **Menu boards (5.4b):** `services/signage_menu.py` resolves a menu slide (all / whole categories incl. sub-categories, live / single products, minus exclusions; the board's own `category_order` / `product_order`; prices from `pos_cart.unit_prices` of its sales point; customer-facing names); every request that changes the menu (`cloud_sync.menu_changed` paths) also sends `signage.changed` to the screens with a menu board (`main._signage_menu_changed`). **The editor (5.6a):** manager `src/pages/signage/` (Management → Signage): playlists, the timeline (drag / arrows, duplicate, remove), a slide's settings with a live preview (`SlidePreview`), templates (`signageLogic.TEMPLATES`), the orientation warning; `GET /api/signage/venue` and `POST /api/signage/preview/menu` feed the previews. The menu board editor (5.6b, `MenuEditor.jsx`) orders what the server resolved: `boardOrder()` writes the whole shown order into `category_order` / `product_order`; widgets: `WidgetsEditor.jsx`. Tabs (5.6c): Screens (`ScreensTab`: playlist, schedule, shape, rotation through `PUT /api/signage/screens/{id}`), Schedules (`SchedulesTab`), Message and weather (`SignageSettingsTab`: `PUT /api/signage/message`, the town search and `PUT /api/signage/weather/place`). **Widgets (5.4c):** `Widget` on text and menu slides (logo, name, date, clock, message, QR, weather; position, size); the screen also gets `venue` = name, the message of the day (`signage.message`, `PUT /api/signage/message` tells every screen) and the weather (`services/weather.py`: Open-Meteo, no key, every 30 min by the signage worker, kept in memory; `null` when there is no place, no internet or it is older than 3 h, so the player hides the widget). **Schedules (5.4d):** `signage_schedules` (entries {playlist, days, hours that may pass midnight, dates, priority} + a fallback); a screen's `schedule` (ref) wins over its `playlist`; `services/signage_schedule.pick` chooses in venue time (highest priority, then dates > days > hours, then the later entry); `/screen` then carries the schedule (with the venue's time zone) and every playlist in it so the player switches offline; `schedule_worker` (30 s) tells a screen when its pick changes. **The player (5.5a):** `terminal/src/apps/signage/` (the logic and slides moved to `packages/signage` in 5.6a; the schedule pick ported from Python with the same test cases, slide windows, next slide, frame rotation; `SignageApp.jsx`: the last `/screen` answer in localStorage, every picture / video (≤ 120 MB) as an in-memory blob copy, so it plays with the server down; reads again on `signage.changed`, `device.updated`, a reconnect and every 5 min). Signage is in `QUIET_OFFLINE` (`apps/registry.js`): no offline banner, a small mark. The terminal is plain HTTP (no service worker), so a TV that restarts while the server is down waits for it. Menu boards page by themselves (`boardPages`: rows that fit from the frame's shape, text size, photos / descriptions, title and widget bars; `page_size` overrides) and go round while the slide lasts (at least its pages × `page_seconds`); widgets in `Slides.jsx` (`Widgets`), a widget with nothing to show (no weather, no message) is left out |
|
||||
| `local_backend/routers/menu_tablet.py`, `terminal/src/apps/menu-tablet/` | The menu tablet (5.7a): `GET /api/menu-tablet/menu` (a paired tablet) gives categories in the catalogue's order with their products (a product in several categories shows in each), the products once with the tablet's sales point price, photos, tags, and its device config (view compact / expanded / full, photos, descriptions, group, theme, prices of, sold out, one category, search, languages, idle reset). Menu changes send `menu_tablet.changed` (the same hook as signage). The app: search folds accents and also matches names typed in Latin letters (`latin`, `@xenia/i18n/latin`); the last menu in localStorage. **Call a waiter (5.7b):** device config `table` (ref `tables`) + `call_waiter`; `POST /api/menu-tablet/call` sends a `table_call` staff message (the open order's waiters, else the zone's; `qr_orders.waiters_for`) at most once a minute per tablet (in memory); the waiter's phone shows it with "Open the table" |
|
||||
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
|
||||
|
||||
@@ -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")
|
||||
@@ -6,9 +6,9 @@ import toast from 'react-hot-toast'
|
||||
import { Trash2 } from 'lucide-react'
|
||||
import { errorMessage } from '@xenia/api'
|
||||
import { useFormat, useTranslation } from '@xenia/i18n'
|
||||
import { Button, Dialog, Field, Input, Spinner } from '@xenia/ui'
|
||||
import { Button, Dialog, Field, Input, Spinner, cx } from '@xenia/ui'
|
||||
import { deleteMedia, getMedia, renameMedia } from './mediaApi'
|
||||
import { duration, fileSize, resolution, VARIANT_ORDER } from './mediaLogic'
|
||||
import { duration, fileSize, preparing, resolution, VARIANT_ORDER, videoState } from './mediaLogic'
|
||||
|
||||
export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
|
||||
const { t } = useTranslation('manager')
|
||||
@@ -26,6 +26,16 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
|
||||
.catch(err => { toast.error(errorMessage(err, t)); close.current() })
|
||||
return () => { live = false }
|
||||
}, [id, t])
|
||||
// A video being prepared for screens (5.4e): follow it until it is done.
|
||||
const changed = useRef(onChanged)
|
||||
useEffect(() => { changed.current = onChanged })
|
||||
const working = preparing([item])
|
||||
useEffect(() => {
|
||||
if (!working) return
|
||||
const h = setInterval(() => { getMedia(id).then(m => { setItem(it => ({ ...it, ...m })); changed.current?.(m) }).catch(() => {}) }, 2000)
|
||||
return () => clearInterval(h)
|
||||
}, [working, id])
|
||||
const state = videoState(item)
|
||||
|
||||
const save = async () => {
|
||||
setBusy(true)
|
||||
@@ -68,7 +78,7 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
|
||||
<div className="grid gap-4" data-testid="media-details" data-id={item.id}>
|
||||
<div className="rounded-card bg-surface-3 overflow-hidden flex items-center justify-center" style={{ maxHeight: '45vh' }}>
|
||||
{item.kind === 'video'
|
||||
? <video src={item.urls.original} controls preload="metadata" className="max-h-[45vh] max-w-full" />
|
||||
? <video src={item.urls.play || item.urls.original} poster={item.urls.full} controls preload="metadata" className="max-h-[45vh] max-w-full" />
|
||||
: <img src={item.urls.full} alt={item.name} className="max-h-[45vh] max-w-full object-contain" />}
|
||||
</div>
|
||||
|
||||
@@ -90,6 +100,8 @@ export default function MediaDetails({ id, onClose, onChanged, onDeleted }) {
|
||||
<section className="grid gap-1">
|
||||
<h3 className="text-label font-semibold text-ink">{t('media.sizes')}</h3>
|
||||
<p className="text-caption text-ink-3">{t(item.kind === 'video' ? 'media.sizesVideo' : 'media.sizesHint')}</p>
|
||||
{state && <p className={cx('text-label font-medium', state === 'failed' ? 'text-danger-ink' : state === 'ready' || state === 'asIs' ? 'text-success-ink' : 'text-accent-ink')}
|
||||
data-testid="media-video-status" data-state={state}>{t(`media.processing.${state}`, { progress: item.progress ?? 0 })}</p>}
|
||||
<ul className="grid gap-1" data-testid="media-sizes">
|
||||
{VARIANT_ORDER.filter(v => item.files?.[v]).map(v => (
|
||||
<li key={v} className="flex gap-3 text-label">
|
||||
|
||||
@@ -9,7 +9,7 @@ import { errorMessage } from '@xenia/api'
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { Button, EmptyState, Input, Select, Spinner, cx } from '@xenia/ui'
|
||||
import { listMedia } from './mediaApi'
|
||||
import { ACCEPT } from './mediaLogic'
|
||||
import { ACCEPT, preparing } from './mediaLogic'
|
||||
import MediaDetails from './MediaDetails'
|
||||
import { MediaGrid, UploadQueue } from './MediaParts'
|
||||
import { useUploadQueue } from './mediaHooks'
|
||||
@@ -32,6 +32,13 @@ export default function MediaPage() {
|
||||
try { setPage(await listMedia({ kind, q: search, collection })); setError(null) } catch (err) { setError(errorMessage(err, t)) }
|
||||
}, [kind, search, collection, t])
|
||||
useEffect(() => { load() }, [load])
|
||||
// Videos are prepared for screens in the background (5.4e): read the list again while any is.
|
||||
const busy = preparing(page?.items)
|
||||
useEffect(() => {
|
||||
if (!busy) return
|
||||
const h = setInterval(load, 3000)
|
||||
return () => clearInterval(h)
|
||||
}, [busy, load])
|
||||
|
||||
// Each finished upload shows at once; the list is read again when the batch is done.
|
||||
const { queue, add, clear, summary } = useUploadQueue(useCallback(item => {
|
||||
|
||||
@@ -4,14 +4,22 @@ import { CheckCircle2, Copy, Film, ImageOff, Loader2, XCircle } from 'lucide-rea
|
||||
import { useTranslation } from '@xenia/i18n'
|
||||
import { cx } from '@xenia/ui'
|
||||
import { useMediaMeta } from './mediaHooks'
|
||||
import { videoState } from './mediaLogic'
|
||||
|
||||
/** The small picture of a library item (a film mark for videos, which have no still frame yet: 5.4e). */
|
||||
/** The small picture of a library item; a video shows its still frame (5.4e) with a film mark, or just the mark. */
|
||||
export function MediaThumb({ item, className }) {
|
||||
const [broken, setBroken] = useState(false)
|
||||
if (item?.kind === 'video') {
|
||||
return <div className={cx('flex items-center justify-center bg-surface-3 text-ink-2', className)}><Film size={28} aria-hidden="true" /></div>
|
||||
}
|
||||
const src = item?.urls?.thumb || item?.thumb
|
||||
if (item?.kind === 'video') {
|
||||
return (
|
||||
<div className={cx('relative flex items-center justify-center bg-surface-3 text-ink-2 overflow-hidden', className)}>
|
||||
{src && !broken && <img src={src} alt="" loading="lazy" onError={() => setBroken(true)} className="absolute inset-0 w-full h-full object-cover" />}
|
||||
<span className={cx('relative flex items-center justify-center', src && !broken && 'absolute bottom-1.5 left-1.5 w-7 h-7 rounded-full bg-surface/85 text-ink')}>
|
||||
<Film size={src && !broken ? 16 : 28} aria-hidden="true" />
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
if (!src || broken) {
|
||||
return <div className={cx('flex items-center justify-center bg-surface-3 text-ink-3', className)}><ImageOff size={24} aria-hidden="true" /></div>
|
||||
}
|
||||
@@ -34,6 +42,7 @@ export function MediaGrid({ items, onOpen, selectedId, selectedIds, testid = 'me
|
||||
<span className="block px-2 pt-1.5 text-label font-medium text-ink truncate" title={item.name}>{item.name}</span>
|
||||
{item.builtin && <span className="block px-2 text-caption text-info-ink" data-testid="media-builtin">{t('media.builtin')}</span>}
|
||||
<span className="block px-2 pb-2 text-caption text-ink-3 truncate">{meta(item)}</span>
|
||||
<VideoBadge item={item} />
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
@@ -41,6 +50,20 @@ export function MediaGrid({ items, onOpen, selectedId, selectedIds, testid = 'me
|
||||
)
|
||||
}
|
||||
|
||||
/** Under a video in the grid while it is being prepared for screens, or when that failed (5.4e). */
|
||||
function VideoBadge({ item }) {
|
||||
const { t } = useTranslation('manager')
|
||||
const state = videoState(item)
|
||||
if (state !== 'waiting' && state !== 'working' && state !== 'failed') return null
|
||||
return (
|
||||
<span className={cx('flex items-center gap-1 px-2 pb-2 -mt-1 text-caption truncate', state === 'failed' ? 'text-danger-ink' : 'text-accent-ink')}
|
||||
data-testid="media-video-state" data-state={state}>
|
||||
{state !== 'failed' && <Loader2 size={12} className="animate-spin shrink-0" aria-hidden="true" />}
|
||||
{t(`media.processingShort.${state}`, { progress: item.progress ?? 0 })}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
/** The list of files being uploaded, with how each one went. */
|
||||
export function UploadQueue({ queue, summary, onClear }) {
|
||||
const { t } = useTranslation('manager')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// The media library's pure helpers (plan step 5.2): no React, unit-tested in tests/media.test.mjs.
|
||||
|
||||
/** What file inputs accept: everything the backend takes (services/media.py). */
|
||||
export const ACCEPT = 'image/jpeg,image/png,image/webp,image/avif,image/gif,video/mp4,video/webm'
|
||||
export const ACCEPT = 'image/jpeg,image/png,image/webp,image/avif,image/gif,video/mp4,video/quicktime,.mov,video/webm'
|
||||
|
||||
/** What an app needs to show a library picture (the same shape as the API's `image`). */
|
||||
export function imageOf(item) {
|
||||
@@ -34,7 +34,23 @@ export function duration(ms) {
|
||||
}
|
||||
|
||||
/** Sizes in the order people read them: small → large → the original. */
|
||||
export const VARIANT_ORDER = ['thumb', 'card', 'full', 'original']
|
||||
export const VARIANT_ORDER = ['thumb', 'card', 'full', 'play', 'original']
|
||||
|
||||
/**
|
||||
* How far a video is in being prepared for screens (plan step 5.4e; services/video.py):
|
||||
* 'waiting' | 'working' | 'ready' (a version for screens was made) | 'asIs' (it plays everywhere as
|
||||
* uploaded) | 'failed' | null (a picture, or no video tool on the server).
|
||||
*/
|
||||
export function videoState(item) {
|
||||
if (item?.kind !== 'video' || !item.processing) return null
|
||||
if (item.processing === 'done') return item.urls?.play ? 'ready' : 'asIs'
|
||||
return item.processing
|
||||
}
|
||||
|
||||
/** Is any of these videos still being prepared? (the page then reads them again every few seconds) */
|
||||
export function preparing(items) {
|
||||
return (items || []).some(i => i?.kind === 'video' && (i.processing === 'waiting' || i.processing === 'working'))
|
||||
}
|
||||
|
||||
/**
|
||||
* A batch upload's queue: one entry per file, uploaded one after another.
|
||||
|
||||
@@ -112,7 +112,7 @@ export function mediaEntry(item) {
|
||||
export function mediaLookup(map) {
|
||||
return id => {
|
||||
const m = map?.[String(id)]
|
||||
return m ? { ...m, src: m.url } : null
|
||||
return m ? { ...m, src: m.url, poster: m.poster || undefined } : null
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// The media library's helpers and its nav rule (plan step 5.2).
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { duration, fileSize, imageOf, queueFrom, queueSummary, resolution } from '../src/pages/media/mediaLogic.js'
|
||||
import { duration, fileSize, imageOf, preparing, queueFrom, queueSummary, resolution, videoState } from '../src/pages/media/mediaLogic.js'
|
||||
import { canSee, pageFor } from '../src/shell/nav.js'
|
||||
|
||||
test('sizes, resolutions and lengths for people', () => {
|
||||
@@ -22,6 +22,20 @@ test('a library item as the picture an app shows', () => {
|
||||
assert.equal(imageOf(null), null)
|
||||
})
|
||||
|
||||
test('a video being prepared for screens (5.4e)', () => {
|
||||
const v = (processing, urls = {}) => ({ kind: 'video', processing, urls: { original: '/o', ...urls } })
|
||||
assert.equal(videoState(v('waiting')), 'waiting')
|
||||
assert.equal(videoState(v('working')), 'working')
|
||||
assert.equal(videoState(v('done', { play: '/p' })), 'ready')
|
||||
assert.equal(videoState(v('done')), 'asIs')
|
||||
assert.equal(videoState(v('failed')), 'failed')
|
||||
assert.equal(videoState(v(null)), null)
|
||||
assert.equal(videoState({ kind: 'image', processing: null }), null)
|
||||
assert.equal(preparing([v('done'), v('working')]), true)
|
||||
assert.equal(preparing([v('done'), v('failed'), { kind: 'image' }]), false)
|
||||
assert.equal(preparing(undefined), false)
|
||||
})
|
||||
|
||||
test('a batch upload queue and its summary', () => {
|
||||
const q = queueFrom([{ name: 'a.jpg' }, { name: 'b.jpg' }], 3)
|
||||
assert.deepEqual(q.map(x => [x.key, x.status]), [['3:a.jpg', 'waiting'], ['4:b.jpg', 'waiting']])
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
},
|
||||
"media": {
|
||||
"not_found": "Το αρχείο {{media_id}} δεν υπάρχει στη βιβλιοθήκη πολυμέσων.",
|
||||
"type": "Ανεβάστε εικόνα (JPG, PNG, WebP, AVIF ή GIF) ή βίντεο (MP4 ή WebM).",
|
||||
"type": "Ανεβάστε εικόνα (JPG, PNG, WebP, AVIF ή GIF) ή βίντεο (MP4, MOV ή WebM).",
|
||||
"too_big": "Το αρχείο είναι πολύ μεγάλο (έως {{max_mb}} MB).",
|
||||
"too_many_pixels": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mp}} megapixel).",
|
||||
"unreadable": "Αυτή η εικόνα δεν διαβάζεται. Αποθηκεύστε τη ξανά ως JPG ή PNG και ανεβάστε τη.",
|
||||
|
||||
@@ -774,11 +774,12 @@
|
||||
"saveName": "Αποθήκευση ονόματος",
|
||||
"sizes": "Μεγέθη που φτιάχτηκαν",
|
||||
"sizesHint": "Ο διακομιστής τα έφτιαξε από το πρωτότυπο· κάθε οθόνη φορτώνει το μικρότερο που χρειάζεται.",
|
||||
"sizesVideo": "Τα βίντεο κρατιούνται όπως ανέβηκαν προς το παρόν· μικρότερες εκδοχές και στιγμιότυπο έρχονται αργότερα.",
|
||||
"sizesVideo": "Ο server έφτιαξε ένα στιγμιότυπο από το βίντεο και, όπου χρειάζεται, μια έκδοση που παίζει σε κάθε οθόνη. Το πρωτότυπο κρατιέται.",
|
||||
"variants": {
|
||||
"thumb": "Μικρό (λίστες)",
|
||||
"card": "Κάρτα (μενού)",
|
||||
"full": "Μεγάλο (πλήρης οθόνη)",
|
||||
"play": "Για οθόνες (H.264)",
|
||||
"original": "Πρωτότυπο"
|
||||
},
|
||||
"usedBy": "Χρησιμοποιείται από",
|
||||
@@ -805,7 +806,19 @@
|
||||
"builtin": "Ενσωματωμένα"
|
||||
},
|
||||
"builtin": "Ενσωματωμένο",
|
||||
"builtinHint": "Οι ενσωματωμένες εικόνες έρχονται με το Xenia: χρησιμοποιούνται παντού, αλλά δεν μετονομάζονται ούτε διαγράφονται."
|
||||
"builtinHint": "Οι ενσωματωμένες εικόνες έρχονται με το Xenia: χρησιμοποιούνται παντού, αλλά δεν μετονομάζονται ούτε διαγράφονται.",
|
||||
"processing": {
|
||||
"waiting": "Περιμένει να ετοιμαστεί για τις οθόνες",
|
||||
"working": "Ετοιμάζεται για τις οθόνες… {{progress}}%",
|
||||
"ready": "Έτοιμη έκδοση για κάθε οθόνη",
|
||||
"asIs": "Παίζει σε κάθε οθόνη όπως είναι",
|
||||
"failed": "Δεν ετοιμάστηκε: παίζει όπως ανέβηκε, όπου μπορεί η οθόνη"
|
||||
},
|
||||
"processingShort": {
|
||||
"waiting": "Σε αναμονή…",
|
||||
"working": "Ετοιμάζεται {{progress}}%",
|
||||
"failed": "Δεν ετοιμάστηκε"
|
||||
}
|
||||
},
|
||||
"signage": {
|
||||
"pageTitle": "Προβολή",
|
||||
|
||||
@@ -129,7 +129,7 @@
|
||||
},
|
||||
"media": {
|
||||
"not_found": "File {{media_id}} isn't in the media library.",
|
||||
"type": "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4 or WebM).",
|
||||
"type": "Upload a picture (JPG, PNG, WebP, AVIF or GIF) or a video (MP4, MOV or WebM).",
|
||||
"too_big": "The file is too big (at most {{max_mb}} MB).",
|
||||
"too_many_pixels": "The picture is too large (at most {{max_mp}} megapixels).",
|
||||
"unreadable": "This picture can't be read. Save it again as JPG or PNG and upload it.",
|
||||
|
||||
@@ -774,11 +774,12 @@
|
||||
"saveName": "Save name",
|
||||
"sizes": "Sizes made",
|
||||
"sizesHint": "The server made these from the original; each screen loads the smallest one it needs.",
|
||||
"sizesVideo": "Videos are kept as uploaded for now; smaller versions and a still frame come later.",
|
||||
"sizesVideo": "The server made a still frame from the video and, where a screen needs it, a version every screen plays. The original is kept.",
|
||||
"variants": {
|
||||
"thumb": "Small (lists)",
|
||||
"card": "Card (menus)",
|
||||
"full": "Large (full screen)",
|
||||
"play": "For screens (H.264)",
|
||||
"original": "Original"
|
||||
},
|
||||
"usedBy": "Used by",
|
||||
@@ -805,7 +806,19 @@
|
||||
"builtin": "Built-in"
|
||||
},
|
||||
"builtin": "Built-in",
|
||||
"builtinHint": "Built-in pictures come with Xenia: they can be used anywhere, but not renamed or deleted."
|
||||
"builtinHint": "Built-in pictures come with Xenia: they can be used anywhere, but not renamed or deleted.",
|
||||
"processing": {
|
||||
"waiting": "Waiting to be prepared for screens",
|
||||
"working": "Preparing for screens… {{progress}}%",
|
||||
"ready": "A version for every screen is ready",
|
||||
"asIs": "Plays on every screen as it is",
|
||||
"failed": "Couldn't be prepared: it plays as uploaded where the screen can"
|
||||
},
|
||||
"processingShort": {
|
||||
"waiting": "Waiting…",
|
||||
"working": "Preparing {{progress}}%",
|
||||
"failed": "Not prepared"
|
||||
}
|
||||
},
|
||||
"signage": {
|
||||
"pageTitle": "Signage",
|
||||
|
||||
@@ -36,7 +36,7 @@ function VideoSlide({ slide, media, onEnded, playing }) {
|
||||
}, [m?.src, playing])
|
||||
return (
|
||||
<div className="absolute inset-0" style={{ background: c.background_colour || '#000' }}>
|
||||
{m && <video ref={ref} src={m.src} autoPlay={playing} muted={c.muted !== false || !playing} playsInline loop={!slide.video_to_end}
|
||||
{m && <video ref={ref} src={m.src} poster={m.poster} autoPlay={playing} muted={c.muted !== false || !playing} playsInline loop={!slide.video_to_end}
|
||||
onEnded={slide.video_to_end ? onEnded : undefined} onError={slide.video_to_end ? onEnded : undefined}
|
||||
className="w-full h-full" style={{ objectFit: c.fit || 'cover' }} data-testid="signage-video" />}
|
||||
</div>
|
||||
|
||||
@@ -105,7 +105,12 @@ export function mediaUrls(data) {
|
||||
if (!data) return []
|
||||
const lists = data.schedule ? Object.values(data.playlists || {}) : (data.playlist ? [data.playlist] : [])
|
||||
const out = new Set()
|
||||
for (const p of lists) for (const m of Object.values(p.media || {})) if (m.url) out.add(m.url)
|
||||
for (const p of lists) {
|
||||
for (const m of Object.values(p.media || {})) {
|
||||
if (m.url) out.add(m.url)
|
||||
if (m.poster) out.add(m.poster) // a video's still frame (5.4e), shown while it loads
|
||||
}
|
||||
}
|
||||
return [...out]
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,8 @@ test('how long a slide stays; the frame for a turned TV; what to keep on the dev
|
||||
const data = { schedule: {}, playlists: { 1: { media: { 5: { url: '/a' } } }, 2: { media: { 6: { url: '/b' }, 5: { url: '/a' } } } } }
|
||||
assert.deepEqual(mediaUrls(data).sort(), ['/a', '/b'])
|
||||
assert.deepEqual(mediaUrls({ playlist: null }), [])
|
||||
const vid = { playlist: { media: { 7: { url: '/v/play', poster: '/v/full' } } } } // a video keeps its still frame too (5.4e)
|
||||
assert.deepEqual(mediaUrls(vid).sort(), ['/v/full', '/v/play'])
|
||||
})
|
||||
|
||||
test('a menu board in pages: headings count, a cut group repeats its heading', () => {
|
||||
|
||||
@@ -131,7 +131,7 @@ function Player({ playlist, kept, tz, venue, now, rotation }) {
|
||||
const [prev, setPrev] = useState(null)
|
||||
const media = id => {
|
||||
const m = playlist.media?.[String(id)]
|
||||
return m ? { ...m, src: kept[m.url] || m.url } : null
|
||||
return m ? { ...m, src: kept[m.url] || m.url, poster: m.poster ? kept[m.poster] || m.poster : undefined } : null
|
||||
}
|
||||
|
||||
const curRef = useRef(cur)
|
||||
|
||||
+24
-1
@@ -23,7 +23,7 @@ const managerVite = spawn('npx', ['vite', '--port', String(MPORT), '--strictPort
|
||||
const waiterVite = await startViteNative({ port: 5191, backendUrl: backend.url })
|
||||
const WAITER = 'http://localhost:5191'
|
||||
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
|
||||
const r = reporter('media: Media page (batch upload, details), product photos (library + on the spot), waiter offline photos (5.2)')
|
||||
const r = reporter('media: Media page (batch upload, details), product photos (library + on the spot), waiter offline photos (5.2), video versions (5.4e)')
|
||||
const errors = []
|
||||
let failures = 0
|
||||
|
||||
@@ -110,6 +110,29 @@ try {
|
||||
await page.screenshot({ path: path.join(OUT, 'media-details.png') })
|
||||
await page.keyboard.press('Escape')
|
||||
|
||||
// 5.4e: a phone video gets its still frame and a version every screen plays, in the background
|
||||
const ff = execFileSync(PYTHON, ['-c', 'import imageio_ffmpeg as i; print(i.get_ffmpeg_exe())']).toString().trim()
|
||||
const mov = path.join(OUT, 'IMG_0042.MOV')
|
||||
execFileSync(ff, ['-hide_banner', '-loglevel', 'error', '-y', '-f', 'lavfi', '-i', 'testsrc2=s=2560x1440:r=25:d=3', '-f', 'lavfi', '-i', 'sine=d=3',
|
||||
'-c:v', 'libx265', '-x265-params', 'log-level=error', '-tag:v', 'hvc1', '-c:a', 'aac', '-shortest', mov])
|
||||
await page.getByTestId('media-file-input').setInputFiles(mov)
|
||||
const vidItem = page.locator('[data-testid="media-item"][data-name="IMG_0042"]')
|
||||
r.check('5.4e: a phone video (HEVC .MOV, 2560 × 1440) goes into the library', await vidItem.waitFor({ timeout: 30_000 }).then(() => true).catch(() => false))
|
||||
r.check('5.4e: …and its still frame shows in the grid by itself once the server made it (no reload)',
|
||||
await vidItem.locator('img').waitFor({ timeout: 60_000 }).then(() => true).catch(() => false))
|
||||
await vidItem.click()
|
||||
const vstatus = page.getByTestId('media-video-status')
|
||||
r.check('5.4e: details: "a version for every screen is ready", with its size listed',
|
||||
await waitFor(async () => ((await vstatus.getAttribute('data-state').catch(() => null)) === 'ready' ? true : null), 60_000, 500)
|
||||
&& await page.getByTestId('media-sizes').locator('li').count() === 5)
|
||||
const vid = (await api('GET', '/api/media?kind=video', { token: boss })).items.find(i => i.name === 'IMG_0042')
|
||||
const play = await fetch(backend.url + vid.urls.play, { headers: { range: 'bytes=0-15' } })
|
||||
r.check('5.4e: the version plays as MP4 (seekable); the original MOV is kept as uploaded',
|
||||
play.status === 206 && play.headers.get('content-type') === 'video/mp4' && vid.content_type === 'video/quicktime'
|
||||
&& vid.bytes === statSync(mov).size, `${play.status} ${play.headers.get('content-type')}`)
|
||||
await page.screenshot({ path: path.join(OUT, 'media-video.png') })
|
||||
await page.keyboard.press('Escape')
|
||||
|
||||
// ── A product's photo from the library, another one uploaded on the spot ────
|
||||
const products = await api('GET', '/api/products/?sold_at=in_store,in_store_takeaway', { token: boss })
|
||||
const [p1, p2] = products.filter(p => !p.is_service_item && p.lifecycle_status === 'active')
|
||||
|
||||
+17
-1
@@ -100,6 +100,8 @@ try {
|
||||
// ── the TV ────────────────────────────────────────────────────────────────
|
||||
const tv = await (await browser.newContext({ viewport: { width: 1280, height: 720 } })).newPage()
|
||||
tv.on('pageerror', e => errors.push(e.message))
|
||||
const fetched = []
|
||||
tv.on('request', q => fetched.push(q.url()))
|
||||
await tv.goto(term.url)
|
||||
await shown(tv, 'pairing-code', 20_000)
|
||||
const code = await tv.getByTestId('pairing-code').getAttribute('data-code')
|
||||
@@ -123,6 +125,18 @@ try {
|
||||
r.check('the menu board lists the products with prices', await tv.getByTestId('signage-menu-item').count() > 0 && await tv.getByTestId('signage-menu-price').count() > 0)
|
||||
await tv.screenshot({ path: path.join(OUT, 'signage-menu.png') })
|
||||
|
||||
// ── 5.4e: the server makes the video's version for screens; the TV switches to it by itself ──
|
||||
const ready = await waitFor(async () => {
|
||||
const m = await api('GET', `/api/media/${video.id}`, { token: boss })
|
||||
return m.processing === 'done' || m.processing === 'failed' ? m : null
|
||||
}, 90_000, 1000)
|
||||
r.check('5.4e: the WebM video gets a still frame and a version every screen plays (H.264 MP4)', !!ready?.urls?.play && !!ready?.urls?.full,
|
||||
JSON.stringify(ready && { processing: ready.processing, urls: Object.keys(ready.urls) }))
|
||||
r.check('5.4e: …the TV is told and fetches that version without a reload',
|
||||
!!(await waitFor(async () => (fetched.some(u => u.endsWith(`${video.sha256}/play`)) ? true : null), 20_000, 300)))
|
||||
const poster = await waitFor(async () => ((await kindNow(tv)) === 'video' ? tv.getByTestId('signage-video').getAttribute('poster') : null), 30_000, 200)
|
||||
r.check('5.4e: …and plays it with its still frame behind it while it loads', !!poster, String(poster))
|
||||
|
||||
// ── a TV mounted sideways ─────────────────────────────────────────────────
|
||||
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { rotation: 90 } })
|
||||
r.check('turn the picture 90°: the frame turns', await waitFor(async () => (await tv.getByTestId('signage-frame').getAttribute('data-rotation')) === '90', 15_000, 300))
|
||||
@@ -280,7 +294,9 @@ try {
|
||||
// ── 5.6c: screens, schedules, the message of the day ─────────────────────
|
||||
await api('PUT', `/api/signage/screens/${dev.id}`, { token: boss, body: { playlist_id: pl.id } })
|
||||
await mgr.getByTestId('signage-tab-settings').click()
|
||||
await mgr.getByTestId('signage-weather').waitFor({ timeout: 10_000 }) // loaded: the message field holds the saved text
|
||||
await mgr.getByTestId('signage-weather').waitFor({ timeout: 10_000 })
|
||||
const savedMessage = (await api('GET', '/api/signage/message', { token: boss })).text || ''
|
||||
await waitFor(async () => ((await mgr.getByTestId('signage-message').inputValue()) === savedMessage ? true : null), 10_000, 200) // loaded
|
||||
await mgr.getByTestId('signage-message').fill('Kalimera from the manager')
|
||||
await mgr.getByTestId('signage-message-save').click()
|
||||
await sleep(700)
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
// - the proxy still starts when the stack has no terminal container (older compose file)
|
||||
// - a media upload bigger than nginx's 1 MB default gets through the proxy and the manager's
|
||||
// nginx (step 5.1), and its sizes come back with year-long cache headers
|
||||
// - a phone video gets its version for screens inside the backend image (ffmpeg, step 5.4e)
|
||||
// node stack.mjs (builds the images: a few minutes the first time, cached after)
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import { reporter } from './lib/env.mjs'
|
||||
@@ -78,6 +79,24 @@ try {
|
||||
card?.status === 200 && card.headers.get('content-type') === 'image/webp' && /immutable/.test(card.headers.get('cache-control') || ''),
|
||||
`${card?.status} ${card?.headers.get('cache-control')}`)
|
||||
|
||||
// 5.4e: the backend image carries the video tool: a phone video gets its version for screens
|
||||
const ff = execFileSync('python', ['-c', 'import imageio_ffmpeg as i; print(i.get_ffmpeg_exe())'], { encoding: 'utf8' }).trim()
|
||||
const hevc = execFileSync(ff, ['-hide_banner', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc2=s=2560x1440:r=25:d=2', '-c:v', 'libx265',
|
||||
'-x265-params', 'log-level=error', '-tag:v', 'hvc1', '-f', 'mov', '-movflags', 'frag_keyframe+empty_moov', 'pipe:1'], { maxBuffer: 64 << 20 })
|
||||
const vf = new FormData()
|
||||
vf.append('file', new Blob([hevc], { type: 'video/quicktime' }), 'IMG_0001.MOV')
|
||||
const vid = await (await fetch(`${M}/api/media`, { method: 'POST', headers: { Authorization: `Bearer ${token}` }, body: vf })).json()
|
||||
let done = null
|
||||
for (let i = 0; i < 90 && vid?.id && !done; i++) {
|
||||
const m = await (await fetch(`${M}/api/media/${vid.id}`, { headers: { Authorization: `Bearer ${token}` } })).json()
|
||||
if (m.processing === 'done' || m.processing === 'failed' || m.processing == null) done = m
|
||||
else await new Promise(res => setTimeout(res, 1000))
|
||||
}
|
||||
const play = done?.urls?.play ? await fetch(`http://127.0.0.1:19080${done.urls.play}`, { headers: { Range: 'bytes=0-15' } }) : null
|
||||
r.check('media (5.4e): the backend image makes the version for screens of a phone video (ffmpeg inside), served seekable on :80',
|
||||
vid?.processing === 'waiting' && done?.processing === 'done' && !!done.urls.thumb && play?.status === 206 && play.headers.get('content-type') === 'video/mp4',
|
||||
`${vid?.processing} → ${done?.processing} ${play?.status}`)
|
||||
|
||||
// LAN vs not: the proxy joins a second network whose addresses aren't private
|
||||
const proxy = stack.compose('ps', '-q', 'proxy').trim()
|
||||
docker('network', 'create', '--subnet', '100.64.50.0/24', WAN)
|
||||
|
||||
Reference in New Issue
Block a user