Compare commits

..
6 Commits
Author SHA1 Message Date
shinyobjectz fc6b75267f LX7's plan: the clipping check in a crate of its own (raea-sys-clip, systems/clip): raea-sys-contact plus a broad phase would pass 2000 lines (rask check failed scene-faults and render-memory on it), and the clipping check moving off the render's thread is its own job; contact's deepest, Hit and solid cache become its public interface 2026-11-29 15:18:02 -08:00
shinyobjectz 456fd1e153 An index job reserves 2 cores and 8 GB
It reserved 4 and 16, and from 11-17 to 11-29 raea-ingest's CPU and memory cost more than its GPU ($7.05 against
$5.97). A 52 s clip measured 1.9 cores busy and 4.9 GB across its processes. A job that takes more is billed for what
it takes. Deployed 11-29 and checked: /healthz on both servers, and the same clip indexed through the deployed job
(10 fragments, 9 posters, 23 s). The search server and the frame API keep their sizes, unmeasured.
2026-11-29 09:55:34 -08:00
shinyobjectz 3afc53d45b A raea render's GPU container reserves 2 cores and 8 GB, and each job says what it used
From 11-17 to 11-29 the farm's CPU and memory came to 65% on top of its GPUs: every GPU container reserved 4 cores
and 16 GiB. A 1080p cut measured 1.3 to 1.4 cores busy and 2.7 GB in its biggest process, so raea's containers now
reserve half (farm_plan.RESERVED); a run that takes more is billed for what it takes, as nothing here sets a limit.
The same cut rendered at the same speed after (262 to 268 ms a frame on a T4) for $0.013 against $0.017. Blender's
containers keep 4 and 16, unmeasured. Each job's last line now says the most cores busy and the biggest process of
its runs, so the next change is made from the jobs' own logs. Deployed 11-29.
2026-11-29 09:34:31 -08:00
shinyobjectz 7d79a24f33 Merge branch 'farm-version' 2026-11-29 09:27:03 -08:00
shaneandshinyobjectz 6af8bfa5bb Cut checks a box can fail on: raea sound check, text placement from the farm's scene read, and full render manifests (#267)
Shane on Dutch (11-29): words faded and cut in two, lines too quiet to hear, effects no one hears, and text laid
over the people and the dog the shot is about.

- raea sound check VIDEO (server/sound.ts): each voice clip's edit points against the take's words and its sound.
  A cut inside a word or on a word's sound is an error, and the message names the pause (or the boundary) to move
  it to. Lines more than 6 dB from the cut's median are an error, with the gainDb that evens them. An effect 10 dB
  or more under the voice is an error, since no one hears it. Buried or fighting music is a warning. offload.ts runs
  it after every render that has a manifest.
- The farm's POST /v1/scene (deploy/modal/farm_scene.py) reads a frame: people as a mask, faces, COCO's things,
  and words in the shot (four small OpenCV zoo models on the CPU, each pinned by its hash).
- server/place.ts turns a scene into costs. raea frames check now fails text over a face, a dog or a person when a
  clear place of its size exists, and names that place. raea frames place FILE lists the clear places in a take.
  Stacked lines move as one block, our own text isn't counted as the shot's words, and passers-by's small faces
  don't count.
- The farm wrote a split render's probe manifest (frame 0 only) as the render's. Each run now writes its own and
  the farm joins them, so the checks see every frame and every clip.

Tests: test/sound.ts (7), test/place.ts (4, on scene reads of three interview frames, boxes only),
test/farm_plan.py (the joined manifest).

Co-authored-by: shinyobjectz <[email protected]>
2026-11-29 09:20:52 -08:00
shinyobjectz 4b2225163e The farm renders with raea's newest release, and says which one it holds
farm.py took RAEA_VERSION or 0.1.6, and no deploy set the variable: on 11-29 the farm's health said 0.1.6 while the
boxes that send it their compositions ran 0.1.12. A container never had the variable either, so health said the
default whatever the image was built with. A deploy now takes the newest full release (GitHub's releases/latest, as
box.sh does) unless RAEA_VERSION pins one, with 0.1.12 when GitHub can't be asked, and the image carries the
version it was built with for its containers. Not deployed: the next modal deploy of raea-farm brings it.
2026-11-29 09:13:24 -08:00
14 changed files with 1173 additions and 32 deletions

No files matched your search

+2 -2
View File
@@ -139,8 +139,8 @@ Feature: The Linux engine, as fast as it can be in the cloud
Scenario: LX7. The clipping check never makes a render wait
Given the plan
| crate | file | lines | job |
| raea-sys-contact | systems/contact/src/broad.rs | 160 | a broad phase before the voxels: parts whose boxes don't touch on a frame are never voxelized or tested; a part's voxels kept by its shape and scale, so an unchanged part is voxelized once a render |
| raea-sys-contact | systems/contact/src/clip.rs | 178 | the frames checked on the cores the render leaves idle: Clipping takes each frame as it's drawn since SG4a (docs/stage-guards.feature), so off the render's thread |
| raea-sys-clip | systems/clip/src/broad.rs | 160 | a broad phase before the voxels: parts whose boxes don't touch on a frame are never voxelized or tested; a part's voxels kept by its shape and scale, so an unchanged part is voxelized once a render |
| raea-sys-clip | systems/clip/src/lib.rs | 178 | the frames checked on the cores the render leaves idle: Clipping takes each frame as it's drawn since SG4a (docs/stage-guards.feature), so off the render's thread. The clipping check moves here from raea-sys-contact's clip.rs (11-29: contact plus a broad phase would pass 2000 lines), using contact's deepest, Hit and solid cache as its public interface |
Then edit.tsx's clipping check takes at most its frames' own time (from 96.1 s), and RR0's film's at most 300 ms
And a render's wall with the check on is within 3% of RAEA_CLIP_CHECK=0
And the findings are identical on the RR0 film, edit.tsx and the contact fixtures (systems/contact's tests)
+111 -10
View File
@@ -29,6 +29,7 @@ import contextlib
import json
import os
import re
import resource
import shutil
import subprocess
import time
@@ -38,7 +39,36 @@ import modal
HERE = os.path.dirname(os.path.abspath(__file__))
CLOUD = os.path.dirname(os.path.dirname(HERE))
RAEA = os.environ.get("RAEA_VERSION", "0.1.6")
def raea_version(env=os.environ, local=None, latest=None):
"""The raea the farm renders with: RAEA_VERSION when it's set (a deploy that pins one, and every container, whose
image carries the version it was built with), else, at a deploy, raea's newest release, as the boxes take
(deploy/sprites/box.sh). Until 11-29 this was "0.1.6" unless a deploy remembered the variable, and none did: the
farm drew 0.1.12 boxes' compositions with a raea six releases old, and a container, which never had the variable,
said 0.1.6 in /v1/health whatever its image held."""
if env.get("RAEA_VERSION"):
return env["RAEA_VERSION"]
if modal.is_local() if local is None else local:
try:
v = (latest or _latest_release)()
if re.fullmatch(r"\d+\.\d+\.\d+", v or ""):
return v
except Exception: # no network at a deploy: the fallback below, and the deploy's own log says which
pass
return RAEA_FALLBACK
def _latest_release():
import urllib.request
# releases/latest answers with a redirect to the newest full release's tag (never a pre-release)
with urllib.request.urlopen("https://github.com/shinyobjectz/raea/releases/latest", timeout=20) as r:
return r.geturl().rstrip("/").rsplit("/v", 1)[-1]
RAEA_FALLBACK = "0.1.12"
RAEA = raea_version()
BLENDER = os.environ.get("RAEA_FARM_BLENDER", "5.3.0")
# The GPUs each kind of job takes, the first Modal has free (bench/gpus.py, 11-17): raea's frames are bound by its CPU
# (React on QuickJS), so a T4 or an A10 draws them for the least a frame; Cycles gets the most samples a dollar on an
@@ -65,6 +95,8 @@ image = (
f"set -e; v={BLENDER}; curl -fsSL https://download.blender.org/release/Blender${{v%.*}}/blender-$v-linux-x64.tar.xz "
"| tar -xJ -C /opt && ln -s /opt/blender-$v-linux-x64/blender /usr/local/bin/blender && blender -b --version | head -1",
)
# what this image holds, for the containers: /v1/health says it, and the module agrees with the deploy that built it
.env({"RAEA_VERSION": RAEA})
.pip_install("fastapi[standard]==0.121.2")
# /v1/faces: OpenCV's YuNet face detector (232 KB, CPU), for the boxes' frames check (server/frames.ts): a box has
# no vision backend of its own (raea-perceive isn't in raea's Linux build), so a face cut by a 9:16 crop went unseen
@@ -74,6 +106,17 @@ image = (
"face_detection_yunet/face_detection_yunet_2023mar.onnx "
"&& echo '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 /opt/yunet.onnx' | sha256sum -c"
)
# /v1/scene (11-29): what's in a frame, for the boxes' text placement (farm_scene.py, server/place.ts): people as a
# mask, COCO's things, words in the shot, beside YuNet's faces. Three more of OpenCV's zoo, Apache-2.0, on the CPU
.run_commands(
"set -e; z=https://media.githubusercontent.com/media/opencv/opencv_zoo/main/models; "
"curl -fsSL -o /opt/pphumanseg.onnx $z/human_segmentation_pphumanseg/human_segmentation_pphumanseg_2023mar.onnx; "
"curl -fsSL -o /opt/yolox_s.onnx $z/object_detection_yolox/object_detection_yolox_2022nov.onnx; "
"curl -fsSL -o /opt/ppocr_det.onnx $z/text_detection_ppocr/text_detection_en_ppocrv3_2023may.onnx; "
"printf '%s %s\\n' 552d8a984054e59b5d773d24b9b12022b22046ceb2bbc4c9aaeaceb36a9ddf24 /opt/pphumanseg.onnx "
"c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063 /opt/yolox_s.onnx "
"03f550c6b406fda8bf54bd8327815f6c7e2edd98cea02348c93d879254366587 /opt/ppocr_det.onnx | sha256sum -c"
)
.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True)
.env({"WGPU_BACKEND": "vulkan", "NVIDIA_DRIVER_CAPABILITIES": "all", "RAEA_CLIP_CHECK": "0", "RAEA_AUDIO_MUTE": "1",
"RAEA_MODELS": "/models/raea", "RAEA_FEED_MODELS": "/models/feed", "RAEA_LIBRARY_MODELS": "/models/library",
@@ -83,7 +126,7 @@ image = (
"RAEA_TOKENSYNTH": "/models/tokensynth", "RAEA_TOKENSYNTH_DEVICE": "cuda", "RAEA_AUDIO_AUTOSETUP": "0",
# Stable Audio Open small on ONNX Runtime with CUDA, as deploy/modal/sao.py installs it (CR25)
"RAEA_SAO": "/models/sao"})
.add_local_python_source("farm_plan", "farm_media", "prices")
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene")
)
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
@@ -104,20 +147,32 @@ CACHES = {"__GL_SHADER_DISK_CACHE": "1", "__GL_SHADER_DISK_CACHE_PATH": f"{ROOT}
"__GL_SHADER_DISK_CACHE_SIZE": str(4 << 30), "XDG_CACHE_HOME": f"{ROOT}/cache/xdg"}
# the scene reader's models, loaded once a container (/v1/scene)
SCENE = None
# when this container's Python started, for the job's bill (farm_plan.Bill)
BOOTED = time.time()
# what this container's last run used: cores busy on average (its processes' CPU time over the run's time) and the
# biggest of them at its peak, for the job's last line (farm_plan.Bill), so what a GPU container reserves
# (farm_plan.RESERVED) is held against what renders take (11-29: CPU and memory were 65% on top of the farm's GPU bill)
USED = {}
def life():
return {"task": os.environ.get("MODAL_TASK_ID", ""), "boot": BOOTED, "end": time.time()}
return {"task": os.environ.get("MODAL_TASK_ID", ""), "boot": BOOTED, "end": time.time(), **USED}
def run(cmd, cwd=None, env=None, timeout=6 * 3600):
t = time.time()
for d in (CACHES["__GL_SHADER_DISK_CACHE_PATH"], CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
u0 = resource.getrusage(resource.RUSAGE_CHILDREN)
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **CACHES, **(env or {})}, timeout=timeout)
return r.returncode, r.stdout + r.stderr, time.time() - t
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
USED.update(cores=round((u1.ru_utime + u1.ru_stime - u0.ru_utime - u0.ru_stime) / max(s, 0.001), 2), peak_mb=round(u1.ru_maxrss / 1024))
return r.returncode, r.stdout + r.stderr, s
def snapshot(d):
@@ -152,8 +207,15 @@ class Log:
SCALEDOWN = 2
def on(gpus):
return dict(gpu=gpus, cpu=4, memory=16384, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN)
def on(gpus, job):
import sys
if HERE not in sys.path: # at a deploy this file is loaded by path; in a container the image carries the module
sys.path.insert(0, HERE)
import farm_plan
cpu, gib = farm_plan.RESERVED[job]
return dict(gpu=gpus, cpu=cpu, memory=gib * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=GPUS, scaledown_window=SCALEDOWN)
def kind():
@@ -164,7 +226,7 @@ def kind():
return prices.kind_of(name)
@app.function(**on(RAEA_GPUS))
@app.function(**on(RAEA_GPUS, "raea"))
def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False) -> dict:
"""raea ARGS in the job's folder. With `frames`: those frames to the job's frames/ folder, from frame `first` on,
as one H.264 run (frames/run-FIRST.mp4, joined by the coordinator without encoding again) when `video`, else PNGs.
@@ -185,12 +247,19 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
os.makedirs(dest, exist_ok=True)
if video:
seg = f"/tmp/run-{first:05d}.mp4"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg], cwd=work)
# the run's own manifest (its frames, each sound cut to them): the coordinator joins the runs' into the render's
# (farm_plan.joined), so a cut's whole edit comes back, not frame 0's alone (11-29, Dutch)
man = f"/tmp/run-{first:05d}.json"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work)
if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit()
ms = re.search(r"([\d.]+) ms a frame", out)
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "ms": float(ms.group(1)) if ms else None, "kind": kind(), **life()}
try:
m = json.load(open(man))
except Exception:
m = None
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "ms": float(ms.group(1)) if ms else None, "kind": kind(), "manifest": m, **life()}
tmp = f"/tmp/{uuid.uuid4().hex}"
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp], cwd=work)
# raea names --at's stills in order (frame-00000.png is the first frame asked for), beside its manifest
@@ -224,7 +293,7 @@ print("RAEA_INFO " + json.dumps({"start": s.frame_start, "end": s.frame_end, "fp
"""
@app.function(**on(BLENDER_GPUS))
@app.function(**on(BLENDER_GPUS, "blender"))
def blender_run(id: str, blend: str, start: int, end: int, opts: dict) -> dict:
vol.reload()
work = f"{JOBS}/{id}/work"
@@ -431,6 +500,38 @@ def api():
"seams": seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))})
return {"model": "yunet-2023mar", "frames": out}
@web.post("/v1/scene")
async def scene(req: Request):
"""what's in a video's frames, for the boxes' frames check and `raea frames place` (farm_scene.py): the body is
{"frames": [base64 JPEG, ...]} (at most 400), the answer each frame's size, its faces and split-screen seams
(as /v1/faces gives them, each face [x, y, w, h, "face", score]), a grid of where people are, and its things
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], in that frame's pixels"""
import base64
import cv2
import numpy as np
import farm_scene
check(req)
body = await req.json()
frames = body.get("frames") if isinstance(body, dict) else None
if not isinstance(frames, list) or not frames:
raise HTTPException(400, 'the body is {"frames": [base64 JPEG, ...]}')
if len(frames) > 400:
raise HTTPException(413, "at most 400 frames a call")
global SCENE
if SCENE is None:
SCENE = farm_scene.Scene()
out = []
for b64 in frames:
im = cv2.imdecode(np.frombuffer(base64.b64decode(b64), np.uint8), cv2.IMREAD_COLOR)
if im is None:
out.append(None)
continue
r = SCENE.read(im)
r["seams"] = seams(cv2.cvtColor(im, cv2.COLOR_BGR2GRAY).astype(np.int16))
out.append(r)
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar", "frames": out}
@web.post("/v1/words")
async def words(req: Request):
import base64
+67 -11
View File
@@ -87,7 +87,13 @@ def runs(first, last, k, warm=0):
return out
def price(kind, seconds, cpu=4, memory_gib=16):
# What a GPU container reserves beside its GPU, billed whether used or not; a run that takes more is billed for what
# it takes (Modal has no limit set here), so these are floors, not caps. raea's were 4 cores and 16 GiB until 11-29,
# when a 1080p cut measured 1.4 cores busy and 2.7 GB (the job's last line says each job's); Blender's is unmeasured.
RESERVED = {"raea": (2, 8), "blender": (4, 16)}
def price(kind, seconds, cpu=RESERVED["raea"][0], memory_gib=RESERVED["raea"][1]):
return prices.cost(kind, cpu=cpu, memory_gib=memory_gib, seconds=seconds)
@@ -97,21 +103,24 @@ BOOT = 3 # s a container is billed before its Python starts: the bench's cold s
class Bill:
"""What Modal bills for a job's GPU containers: each one's life from its boot (or the job's start, for one an
earlier job left up) to its last run's end, plus BOOT and SCALEDOWN, at its kind's price with 4 cores and 16 GiB."""
earlier job left up) to its last run's end, plus BOOT and SCALEDOWN, at its kind's price with what `job` ("raea", "blender") reserves."""
def __init__(self):
self.t0, self.tasks = time.time(), {}
def __init__(self, job="raea"):
self.t0, self.tasks, self.cores, self.peak_mb, self.cpu, self.gib = time.time(), {}, 0.0, 0, *RESERVED[job]
def add(self, r):
if isinstance(r, dict) and r.get("task"):
b, e = max(r["boot"], self.t0), r["end"]
k, b0, e0 = self.tasks.get(r["task"], (r.get("kind"), b, e))
self.tasks[r["task"]] = (k or r.get("kind"), min(b, b0), max(e, e0))
self.cores, self.peak_mb = max(self.cores, r.get("cores") or 0), max(self.peak_mb, r.get("peak_mb") or 0)
return r
def line(self):
up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e in self.tasks.values()]
return f"raea farm: billed about ${sum(price(k, s) for k, s in up):.3f}: {len(up)} GPU containers up {sum(s for _, s in up):.0f} s in all"
# the busiest run's cores and biggest process, against what each container reserves (farm.py on())
used = f"; at most {self.cores:.1f} of {self.cpu} cores busy and {self.peak_mb / 1024:.1f} of {self.gib} GB in one process" if self.cores else ""
return f"raea farm: billed about ${sum(price(k, s, self.cpu, self.gib) for k, s in up):.3f}: {len(up)} GPU containers up {sum(s for _, s in up):.0f} s in all{used}"
def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
@@ -145,9 +154,10 @@ def keep(frames_dir, out, start=0):
shutil.move(os.path.join(frames_dir, name), os.path.join(out, f"frame-{i:05d}.png"))
def spread(fn, kind, calls, log, what, bill=None, most=None):
def spread(fn, kind, calls, log, what, bill=None, most=None, got=None):
"""`calls` on `fn`, at most `most` GPUs at once when there are more calls than that (each GPU takes the next call
as it finishes one); each finished run said in the log as it lands. The first failure's code, else 0."""
as it finishes one); each finished run said in the log as it lands, and kept in `got` when given. The first
failure's code, else 0."""
code = 0
if most and len(calls) > most:
fn = fn.with_options(max_containers=most)
@@ -158,6 +168,8 @@ def spread(fn, kind, calls, log, what, bill=None, most=None):
continue
if bill:
bill.add(r)
if got is not None:
got.append(r)
log(f"raea farm: {r.get('frames')} {what} on a {r.get('kind') or kind} in {r['s']:.1f} s")
if r["code"]:
log(r["out"], err=True)
@@ -205,7 +217,8 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
return 3
# a video's runs can't drop warm-up frames without encoding again, so they have none
warm = 0 if video else opts.get("warm", 0)
code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k) if left else 0
got = [r0]
code = spread(render, kind, [(id, rest, f, at, False, video) for f, at in runs(n0, length - 1, k * m, warm)], log, "frames", bill, k, got) if left else 0
if code:
return code
# the sound's run finished first: its open files in the job's folder refuse the reload that brings the other
@@ -219,7 +232,7 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
with open(path, "w") as f:
json.dump(p["manifest"], f, indent=2)
json.dump(joined(p["manifest"], [r.get("manifest") for r in got]), f, indent=2)
if video:
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
c, o, s = join(frames, dest, sound, run)
@@ -229,6 +242,49 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
return 0
def joined(probe, parts):
"""The render's manifest from its runs' own (each holds its frames, and each sound cut to them, a clip's `at` its
source time at the run's first frame): every frame, and each clip made whole again where one run's piece ends on the
frame the next one's starts, at the source time it should. Frame 0's (the probe's) when no run brought one.
11-29 (Dutch): frame 0's alone was written, so a cut's edit was lost and nothing could check its edit points."""
parts = [m for m in parts if m]
if not parts:
return probe
out = {**probe, **{k: v for k, v in parts[0].items() if k not in ("frames", "sounds", "findings")}}
frames = {}
for m in parts:
for f in m.get("frames") or []:
frames.setdefault(f.get("frame"), f)
out["frames"] = [frames[k] for k in sorted(frames, key=lambda x: (x is None, x))]
seen, found = set(), []
for m in [probe, *parts]:
for x in m.get("findings") or []:
key = json.dumps(x, sort_keys=True)
if key not in seen:
seen.add(key)
found.append(x)
out["findings"] = found
snd = [m.get("sounds") for m in parts if isinstance(m.get("sounds"), dict)]
if snd:
fps = snd[0].get("fps") or out.get("fps") or 30
pieces = sorted((c for s in snd for c in s.get("clips") or []), key=lambda c: (c.get("from", 0), str(c.get("key"))))
clips = []
for c in pieces:
prev = next((p for p in reversed(clips) if p.get("key") == c.get("key") and p.get("src") == c.get("src") and p.get("to") == c.get("from")), None)
if prev is not None and abs(prev.get("at", 0) + (prev["to"] - prev["from"]) / fps - c.get("at", 0)) < 1.5 / fps:
prev["to"] = c["to"]
if "fadeOut" in c:
prev["fadeOut"] = c["fadeOut"]
continue
clips.append(dict(c))
notes, lines = [], []
for s in snd:
notes += [n for n in s.get("notes") or [] if n not in notes]
lines += [n for n in s.get("lines") or [] if n not in lines]
out["sounds"] = {**snd[0], "clips": clips, "notes": notes, "lines": lines}
return out
def blender_info(blend, work, run):
c, o, _ = run(["blender", "-b", blend, "--python-expr", BLENDER_INFO], cwd=work)
m = re.search(r"RAEA_INFO (\{.*\})", o)
@@ -275,7 +331,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
left = last - first
k = gpus_for(left, frame_s, start_s, opts["gpus"])
m = parts_per_gpu(left, k, frame_s, start_s)
cost = price(kind, r0["s"] + k * m * start_s + left * frame_s)
cost = price(kind, r0["s"] + k * m * start_s + left * frame_s, *RESERVED["blender"])
parts = f" in {k * m} parts" if m > 1 else ""
log(f"raea farm: frame {first} on a {kind} in {r0['s']:.1f} s ({frame_s:.1f} s rendering); {left} left on {k} {kind}s{parts}, about ${cost:.3f} in all")
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
@@ -302,7 +358,7 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
if opts.get("gpu"):
render, blender_render = (f.with_options(gpu=opts["gpu"]) for f in (render, blender_render))
if args and args[0] == "blender":
bill = Bill()
bill = Bill("blender")
code = blender(args, opts, work, log, blender_render, run, reload, bill)
log(bill.line())
return code
+143
View File
@@ -0,0 +1,143 @@
"""What's in a frame, for the boxes' text checks (server/frames.ts): where people are (a mask, hands and arms included),
their faces, and the things a person holds or a shot is about (a dog, a phone, a cup), so text isn't laid over them and
a clear place for it can be found (11-29, Shane on Dutch: "text being weirdly placed over footage where it blocks a
person or place, dont we have methods of correctly guessing where text needs to go based on the scene?").
Four small ONNX models from OpenCV's zoo, on the CPU through cv2.dnn, each pinned by its hash in farm.py's image:
PP-HumanSeg (2023mar, Apache-2.0): people, as a mask, at 192x192
YOLOX-S (2022nov, Apache-2.0): COCO's 80 things, as boxes, at 640x640
PP-OCRv3 DB (2023may, Apache-2.0): words in the shot (a sign someone holds, a shop's name), as boxes labelled "text"
YuNet (2023mar, MIT): faces, as boxes (the frames check's own)
A frame's answer: its size, a grid of how much of each cell is a person (0-9, a cell ~1/27 of the shorter side), the
faces and the things as [x, y, w, h, label, score] in the frame's pixels."""
import numpy as np
SEG = "/opt/pphumanseg.onnx"
DET = "/opt/yolox_s.onnx"
WORDS = "/opt/ppocr_det.onnx"
FACE = "/opt/yunet.onnx"
# COCO's classes, YOLOX's order
COCO = ("person bicycle car motorcycle airplane bus train truck boat traffic_light fire_hydrant stop_sign parking_meter "
"bench bird cat dog horse sheep cow elephant bear zebra giraffe backpack umbrella handbag tie suitcase frisbee skis "
"snowboard sports_ball kite baseball_bat baseball_glove skateboard surfboard tennis_racket bottle wine_glass cup "
"fork knife spoon bowl banana apple sandwich orange broccoli carrot hot_dog pizza donut cake chair couch "
"potted_plant bed dining_table toilet tv laptop mouse remote keyboard cell_phone microwave oven toaster sink "
"refrigerator book clock vase scissors teddy_bear hair_drier toothbrush").split()
# what a shot is about or a person holds: text over these hides them. Furniture, vehicles and the like are the place
KEEP = {"person", "bird", "cat", "dog", "horse", "backpack", "umbrella", "handbag", "tie", "suitcase", "frisbee",
"sports_ball", "bottle", "wine_glass", "cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich",
"orange", "broccoli", "carrot", "hot_dog", "pizza", "donut", "cake", "laptop", "mouse", "remote", "keyboard",
"cell_phone", "book", "clock", "vase", "scissors", "teddy_bear", "hair_drier", "toothbrush"}
# grid cells along the frame's shorter side (40 px cells in a 1080-wide frame)
CELLS = 27
class Scene:
def __init__(self, seg=SEG, det=DET, face=FACE, words=WORDS):
import cv2
self.cv2 = cv2
self.seg = cv2.dnn.readNet(seg)
self.det = cv2.dnn.readNet(det)
self.words_model = cv2.dnn_TextDetectionModel_DB(words)
self.words_model.setBinaryThreshold(0.3)
self.words_model.setPolygonThreshold(0.5)
self.words_model.setMaxCandidates(200)
self.words_model.setUnclipRatio(2.0)
self.face_path = face
self.face, self.face_size = None, None
def people(self, im):
"""the share of each pixel that's a person, at the frame's size (PP-HumanSeg: RGB, 192x192, (x/255 - 0.5)/0.5)"""
cv2 = self.cv2
h, w = im.shape[:2]
x = cv2.resize(cv2.cvtColor(im, cv2.COLOR_BGR2RGB), (192, 192)).astype(np.float32) / 255.0
x = (x - 0.5) / 0.5
self.seg.setInput(x.transpose(2, 0, 1)[None])
out = self.seg.forward()[0] # [2, 192, 192], logits of background and person
e = np.exp(out - out.max(axis=0, keepdims=True))
p = e[1] / e.sum(axis=0)
return cv2.resize(p, (w, h), interpolation=cv2.INTER_LINEAR)
def things(self, im, least=0.35):
"""COCO things as [x, y, w, h, label, score] (YOLOX-S: BGR as is, letterboxed into 640x640 on grey 114)"""
cv2 = self.cv2
h, w = im.shape[:2]
r = min(640 / h, 640 / w)
pad = np.full((640, 640, 3), 114, np.uint8)
pad[: int(h * r), : int(w * r)] = cv2.resize(im, (int(w * r), int(h * r)))
self.det.setInput(pad.transpose(2, 0, 1)[None].astype(np.float32))
out = self.det.forward()[0] # [8400, 85]: x, y, w, h, objectness, 80 classes, on the strides' grids
grids, strides = [], []
for s in (8, 16, 32):
n = 640 // s
yv, xv = np.meshgrid(np.arange(n), np.arange(n), indexing="ij")
grids.append(np.stack((xv, yv), 2).reshape(-1, 2))
strides.append(np.full((n * n, 1), s))
grids, strides = np.concatenate(grids), np.concatenate(strides)
xy = (out[:, :2] + grids) * strides
wh = np.exp(out[:, 2:4]) * strides
scores = out[:, 4:5] * out[:, 5:]
cls = scores.argmax(1)
best = scores[np.arange(len(cls)), cls]
keep = best > least
boxes = np.concatenate([xy - wh / 2, wh], 1)[keep] / r
cls, best = cls[keep], best[keep]
idx = cv2.dnn.NMSBoxes(boxes.tolist(), best.tolist(), least, 0.45)
found = []
for i in np.array(idx).flatten() if len(idx) else []:
label = COCO[int(cls[i])]
if label not in KEEP:
continue
x, y, bw, bh = boxes[i]
x0, y0 = max(0.0, x), max(0.0, y)
found.append([round(float(x0), 1), round(float(y0), 1), round(float(min(w, x + bw) - x0), 1), round(float(min(h, y + bh) - y0), 1), label, round(float(best[i]), 3)])
return found
def words(self, im, least=0.6):
"""words in the shot as [x, y, w, h, "text", score] (PP-OCRv3 DB at the frame's size, rounded to 32s)"""
cv2 = self.cv2
h, w = im.shape[:2]
size = (max(32, round(w / 32) * 32), max(32, round(h / 32) * 32))
self.words_model.setInputParams(1.0 / 255.0, size, (122.67891434, 116.66876762, 104.00698793))
boxes, conf = self.words_model.detect(im)
out = []
for b, c in zip(boxes, conf):
if float(c) < least:
continue
x, y, bw, bh = cv2.boundingRect(np.array(b, np.int32))
out.append([float(max(0, x)), float(max(0, y)), float(bw), float(bh), "text", round(float(c), 3)])
return out
def faces(self, im):
cv2 = self.cv2
h, w = im.shape[:2]
if self.face is None or self.face_size != (w, h):
self.face, self.face_size = cv2.FaceDetectorYN.create(self.face_path, "", (w, h), 0.6, 0.3, 5000), (w, h)
_, found = self.face.detect(im)
return [[round(float(f[0]), 1), round(float(f[1]), 1), round(float(f[2]), 1), round(float(f[3]), 1), "face", round(float(f[14]), 3)] for f in (found if found is not None else [])]
def read(self, im):
h, w = im.shape[:2]
p = self.people(im)
return {"w": w, "h": h, "grid": grid(p, w, h), "things": self.things(im) + self.words(im), "faces": self.faces(im)}
def grid(p, w, h):
"""a person mask (0-1 a pixel) as a grid of digits, a row a string: how much of each cell is a person, 0-9"""
cell = min(w, h) / CELLS
cols, rows = max(1, round(w / cell)), max(1, round(h / cell))
out = []
for r in range(rows):
y0, y1 = int(r * h / rows), int((r + 1) * h / rows)
row = ""
for c in range(cols):
x0, x1 = int(c * w / cols), int((c + 1) * w / cols)
v = float(p[y0:y1, x0:x1].mean()) if y1 > y0 and x1 > x0 else 0.0
row += str(min(9, int(v * 10)))
out.append(row)
return {"cols": cols, "rows": rows, "people": out}
+4 -1
View File
@@ -187,7 +187,10 @@ server_image = indexer_image_for(None)
# one file indexed as a job (tools/library-index cloud-cli.ts), for a file of any length: raea cloud submits it through
# the API's POST /v1/index-jobs and collects it with GET /v1/index-jobs/ID on its next alarm (index-run.ts)
@app.function(image=indexer_image, gpu=GPU, cpu=4, memory=16384, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=120)
# 2 cores and 8 GiB reserved (4 and 16 until 11-29): a 52 s clip measured 1.9 cores busy and 4.9 GB across its
# processes, and from 11-17 to 11-29 the app's CPU and memory cost more than its GPU. A job that takes more is billed
# for what it takes: these are floors, with no limit set
@app.function(image=indexer_image, gpu=GPU, cpu=2, memory=8192, secrets=[secret], timeout=3600, max_containers=12, scaledown_window=120)
def index_job(url: str, name: str, kind: str) -> dict:
import json
import subprocess as sp
+3
View File
@@ -13,5 +13,8 @@ case "${1:-}" in
words|transcribe) exec node /opt/raea-cloud/server/words.ts "$@" ;;
# faces cut by the frame or a seam, text too small (server/frames.ts, the farm's face detector)
frames) exec node /opt/raea-cloud/server/frames.ts "$@" ;;
# edit points inside words or on sound, lines too quiet to hear, effects no one hears (server/sound.ts, against each
# take's own words and sound); `raea sound` alone is raea's
sound) if [ "${2:-}" = check ]; then exec node /opt/raea-cloud/server/sound.ts "$@"; fi ;;
esac
exec /opt/raea/bin/raea "$@"
+105 -6
View File
@@ -9,6 +9,12 @@
// text: each text the render's manifest shows (raea render --manifest; a .tsx render through raea cloud writes
// VIDEO.render.json by itself), its font size in pixels of a 1080-wide frame: under 40 px is an error (no one
// reads it on a phone), under 48 px a warning (small for anything but a badge or small print).
// placement (11-29): each text against what's under it (the farm's POST /v1/scene: people, faces, the things a
// shot is about, words in the shot like a sign): text over a face, a thing or a person, where a clear place of
// its size exists, is said with that place (server/place.ts).
// raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// the clearest places in FILE (a take or an export, a picture or a video, at those seconds) for a box WxH in a
// 1080-wide frame (a caption, 840x110, by default): read the takes with it before laying text over them.
// Exit 1 on any error. A face at the edge that's meant (someone walking out of shot) is said, with its reason, in
// VIDEO.despite.txt beside the video: its findings are then warnings.
import { spawnSync } from "node:child_process"
@@ -16,6 +22,7 @@ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSy
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { placeReport, textOver, type Scene } from "./place.ts"
/** frames sampled a second, and the width they're read at (a face's place is in shares of the picture) */
const RATE = 2
@@ -27,7 +34,7 @@ export const FACE_MIN = 0.05
export const TEXT_ERROR = 40
export const TEXT_WARN = 48
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small"; at: number | null; until?: number; says: string }
export type Finding = { level: "error" | "warn"; kind: "face-cut" | "split" | "text-small" | "text-over"; at: number | null; until?: number; says: string }
/** a line where the picture jumps across nearly the whole frame (the farm's): its axis (h, a row), where, and its share */
export type Seam = [string, number, number]
export type Faces = { w: number; h: number; faces: number[][]; seams?: Seam[] } | null
@@ -149,6 +156,58 @@ function ffmpeg(args: string[]) {
if (r.status !== 0) throw new Error(`ffmpeg: ${(r.stderr ?? "").slice(-400)}`)
}
/** what the farm reads in a file's frames (`at`: those seconds, else RATE a second), from its POST /v1/scene, or from
* /v1/faces alone on a farm without it (then each scene is null) */
export async function scenes(file: string, at?: number[], f: typeof fetch = fetch): Promise<{ faces: Faces[]; scenes: Scene[] }> {
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN ?? ""
if (!url) throw new Error("the frames check needs the farm (RAEA_CLOUD_GPU_URL); this box has none set")
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-frames-"))
try {
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
if (/\.(png|jpe?g|webp)$/i.test(file)) ffmpeg(["-v", "error", "-y", "-i", file, "-vf", scale, "-q:v", "4", path.join(dir, "f00001.jpg")])
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
const outF: Faces[] = []
const outS: Scene[] = []
let scene = true
for (let i = 0; i < jpgs.length; i += 300) {
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
const call = async (route: string) => {
let r: Response | undefined
let why = ""
for (let k = 0; k < 4; k++) {
r = await f(`${url.replace(/\/$/, "")}${route}`, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, body, signal: AbortSignal.timeout(600_000) })
if (r.ok || r.status === 404) break
why = `${r.status} ${(await r.text()).slice(0, 300)}`
if (r.status < 500) break
await new Promise((ok) => setTimeout(ok, 1000 * 2 ** k))
}
return { r, why }
}
let { r, why } = scene ? await call("/v1/scene") : { r: undefined as Response | undefined, why: "" }
if (scene && r?.status === 404) scene = false
if (!scene) ({ r, why } = await call("/v1/faces"))
if (!r?.ok) throw new Error(`the farm couldn't look at ${path.basename(file)}: ${why || r?.status}`)
const got = ((await r.json()) as { frames: (Record<string, unknown> | null)[] }).frames
for (const g of got) {
if (!g) {
outF.push(null)
outS.push(null)
continue
}
const fs = (g.faces as unknown[][]) ?? []
outF.push({ w: g.w as number, h: g.h as number, faces: fs.map((x) => (typeof x[4] === "string" ? [x[0], x[1], x[2], x[3], x[5]] : x) as number[]), seams: g.seams as Seam[] | undefined })
outS.push(scene && g.grid ? ({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs.map((x) => (typeof x[4] === "string" ? x : [x[0], x[1], x[2], x[3], "face", x[4]])) } as Scene) : null)
}
}
return { faces: outF, scenes: outS }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** VIDEO's faces, two frames a second, by the farm */
export async function faces(file: string, f: typeof fetch = fetch): Promise<Faces[]> {
const url = process.env.RAEA_CLOUD_GPU_URL
@@ -187,7 +246,40 @@ function flag(args: string[], name: string): string | undefined {
/** the manifest a render of VIDEO wrote: --manifest, or VIDEO.render.json beside it */
export const manifestOf = (video: string) => `${video.slice(0, video.length - path.extname(video).length)}.render.json`
/** `raea frames place FILE [--at S,...] [--box WxH]` */
async function place(a: string[]): Promise<number> {
const file = a.find((x, i) => !x.startsWith("-") && !["--at", "--box", "-o"].includes(a[i - 1] ?? ""))
if (!file || !existsSync(file)) {
console.error("usage: raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json] (the clearest places in a take or an export for a box WxH in a 1080-wide frame; a caption, 840x110, by default)")
return 2
}
const box = (flag(a, "--box") ?? "840x110").split("x").map(Number) as [number, number]
if (box.length !== 2 || !box.every((v) => v > 0)) {
console.error("raea frames place: --box is WxH in a 1080-wide frame's pixels, like 840x110")
return 2
}
let at = flag(a, "--at")?.split(",").map(Number).filter(Number.isFinite)
if (!at?.length && !/\.(png|jpe?g|webp)$/i.test(file)) {
const r = spawnSync("ffprobe", ["-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", file], { encoding: "utf8" })
const len = Number.parseFloat(r.stdout) || 1
const n = Math.min(12, Math.max(1, Math.floor(len)))
at = Array.from({ length: n }, (_, i) => Math.round(((i + 0.5) * len * 100) / n) / 100)
}
const { scenes: ss } = await scenes(file, at)
if (!ss.some(Boolean)) {
console.error("raea frames place: the farm has no scene reader yet (POST /v1/scene): nothing to place by")
return 1
}
const rep = placeReport(file, ss, box)
console.log(`${path.basename(file)}${at?.length ? ` at ${at.join(", ")} s` : ""}: the clearest places for a ${box[0]}x${box[1]} box in a ${rep.frame?.join("x")} frame, best first`)
for (const p of rep.places) console.log(` left ${p.left} px, top ${p.top} px (${p.at}) cost ${p.cost}${p.covers.length ? ` covers ${p.covers.join(", ")}` : " clear"}`)
const o = flag(a, "-o")
if (o) writeFileSync(o, JSON.stringify(rep, null, 1))
return 0
}
export async function main(args: string[]): Promise<number> {
if (args[0] === "place") return place(args.slice(1))
const a = args[0] === "check" ? args.slice(1) : args
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
if (!video || !existsSync(video)) {
@@ -197,14 +289,21 @@ export async function main(args: string[]): Promise<number> {
const m = flag(a, "--manifest") ?? manifestOf(video)
const found: Finding[] = []
let looked = 0
const man = existsSync(m) ? JSON.parse(readFileSync(m, "utf8")) : null
let placed: number | null = null
try {
const fr = await faces(video)
looked = fr.length
found.push(...cutFaces(fr))
const got = await scenes(video)
looked = got.faces.length
found.push(...cutFaces(got.faces))
if (man && got.scenes.some(Boolean)) {
const over = textOver(man, got.scenes, RATE)
placed = over.length
found.push(...over)
}
} catch (e) {
console.log(`WARN the faces check couldn't run: ${(e as Error).message}`)
}
const texts = existsSync(m) ? smallText(JSON.parse(readFileSync(m, "utf8"))) : null
const texts = man ? smallText(man) : null
if (texts) found.push(...texts)
const despite = `${video.slice(0, video.length - path.extname(video).length)}.despite.txt`
const why = existsSync(despite) ? readFileSync(despite, "utf8").trim() : ""
@@ -212,7 +311,7 @@ export async function main(args: string[]): Promise<number> {
for (const x of out) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(1)} s `}${x.says}`)
const errors = out.filter((x) => x.level === "error").length
const report = flag(a, "-o") ?? `${video.slice(0, video.length - path.extname(video).length)}.frames-check.json`
writeFileSync(report, JSON.stringify({ video, looked_at: looked, text_checked: texts !== null, findings: out }, null, 1))
writeFileSync(report, JSON.stringify({ video, looked_at: looked, text_checked: texts !== null, placement_checked: placed !== null, findings: out }, null, 1))
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${looked} frames looked at for faces, ${texts === null ? "no manifest for its text" : `${new Set(texts.map((t) => t.says)).size} small texts`}, ${errors} errors, ${out.length - errors} warnings; ${path.basename(report)}`)
return errors ? 1 : 0
}
+16 -1
View File
@@ -192,6 +192,21 @@ async function main() {
const code = await afterRender(made, say)
if (code) process.exitCode = code
}
// what its sound gets wrong (sound.ts), from the render's manifest against each take's own words and sound: an edit
// point inside a word or on its sound, a line too quiet to hear, an effect no one hears (11-29, Shane on Dutch)
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_SOUND !== "0") {
const mi = args.indexOf("--manifest")
const man = mi >= 0 ? path.resolve(process.cwd(), args[mi + 1] ?? "") : ""
if (man && existsSync(man)) {
const { main: sound } = await import("./sound.ts")
say(`the sound check: ${path.basename(made)}'s edit points, line levels and effects`)
const code = await sound(["check", made, "--manifest", man]).catch((e) => (say(`the sound check couldn't run: ${(e as Error).message}`), 0))
if (code) {
say(`${path.basename(made)}'s sound has faults a listener hears: fix every ERROR above (move each cut to the pause or boundary it names, set the gainDb it gives), then render again`)
process.exitCode = code
}
}
}
// what its pictures get wrong (frames.ts): faces cut by the frame or a split screen's seam, text too small to read
// (11-25, Shane: "it cuts out faces all the time", "it makes text too small")
if (!exit && /\.(mp4|mov|m4v|webm)$/i.test(made) && existsSync(made) && process.env.RAEA_CLOUD_FRAMES !== "0") {
@@ -200,7 +215,7 @@ async function main() {
const mi = args.indexOf("--manifest")
const code = await frames(["check", made, ...(mi >= 0 ? ["--manifest", path.resolve(process.cwd(), args[mi + 1] ?? "")] : [])]).catch((e) => (say(`the frames check couldn't run: ${(e as Error).message}`), 0))
if (code) {
say(`${path.basename(made)} has a face cut or text too small: fix every ERROR above (reframe on the person, make the text bigger), then render again. A face at the edge that's meant goes in ${path.basename(made, path.extname(made))}.despite.txt with why`)
say(`${path.basename(made)} has a face cut, text too small, or text over what the shot shows: fix every ERROR above (reframe on the person, make the text bigger, move the text to the place it names; raea frames place TAKE shows a take's clear places), then render again. A face at the edge that's meant goes in ${path.basename(made, path.extname(made))}.despite.txt with why`)
process.exitCode = code
}
}
+284
View File
@@ -0,0 +1,284 @@
// Where text can go in a shot, and text laid where it hides what the shot is about (11-29, Shane on Dutch: "text being
// weirdly placed over footage where it blocks a person or place, dont we have methods of correctly guessing where text
// needs to go based on the scene? ... the rule of thirds, and placement of things over the scene").
//
// A frame's scene (the farm's POST /v1/scene: a person mask as a grid, faces, and the things a shot is about, a dog, a
// phone, a cup) becomes a cost for each grid cell: a face most, then a thing, then a person in the shot (the body
// itself, and the box around them a little), then the edges a phone's own buttons and captions cover; open ground is
// free. A text's cost is the mean of the cells it covers. A text is badly placed when it covers a face or a thing, or
// a person, and a place of the same size costs much less; that place is what's said.
//
// raea frames place FILE [--at S[,S...]] [--box WxH] [-o REPORT.json]
// FILE (a take or an export, a picture or a video) read at those seconds (a video: one a second, at most 12):
// the clearest places for a box WxH (in a 1080-wide frame; a caption, 840x110, by default), best first, as its
// top-left in pixels and in shares of the frame, and what each covers.
import path from "node:path"
/** a frame's scene, as the farm reads it (deploy/modal/farm_scene.py), in the pixels of the frame it was sent */
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[] } | null
/** [x, y, w, h, label, score] */
export type Thing = [number, number, number, number, string, number]
/** a box in shares of the frame: x, y, w, h */
export type Box = [number, number, number, number]
/** what each covered cell costs */
const COST = { face: 10, thing: 6, body: 4, subject: 2, crowd: 0.5, edge: 5 }
/** a person whose box is this share of the frame's height or more is in the shot; smaller ones are passers-by */
const SUBJECT_MIN = 0.25
/** a face this share of the frame's height or more is someone in the shot (frames.ts FACE_MIN); smaller, a passer-by */
const FACE_IN_SHOT = 0.05
/** a thing this share of the frame's area or more is what the shot shows (a dog at someone's feet, a phone held up) */
const THING_MIN = 0.006
/** a text is badly placed when it costs this much or more, and a clear place costs this much less */
export const BAD = 1.6
export const BETTER = 1.2
/** the edges a phone's own interface covers on a tall frame (Reels and TikTok: the header, the buttons on the right,
* the caption and the bar at the bottom), in shares; a wide or square frame keeps a 5% margin all round */
export function safe(w: number, h: number): { top: number; bottom: number; left: number; right: number } {
return h / w > 1.5 ? { top: 0.07, bottom: 0.2, left: 0.04, right: 0.12 } : { top: 0.05, bottom: 0.05, left: 0.05, right: 0.05 }
}
export type Cost = { cols: number; rows: number; cost: Float32Array; why: Uint8Array }
/** why a cell costs what it does: 0 open, 1 crowd, 2 a person's box, 3 a body, 4 a thing, 5 a face, 6 the edge */
export const WHY = ["open ground", "passers-by", "a person in the shot", "a person in the shot", "", "a face", "the phone's own interface", "other text on screen"]
/** a box (shares) overlapping another by this share of the smaller one is the same place */
const overlaps = (a: Box, b: Box, share: number) => {
const ix = Math.max(0, Math.min(a[0] + a[2], b[0] + b[2]) - Math.max(a[0], b[0]))
const iy = Math.max(0, Math.min(a[1] + a[3], b[1] + b[3]) - Math.max(a[1], b[1]))
return ix * iy > share * Math.min(a[2] * a[3], b[2] * b[3])
}
const shareOf = (s: NonNullable<Scene>, t: Thing): Box => [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
/** a scene as a cost per grid cell, and what each cell holds. `ours`: the render's own texts on this frame (the words
* the farm read there are ours, not the shot's); `others`: the ones a place must also stay off */
export function costs(s: NonNullable<Scene>, ours: Box[] = [], others: Box[] = []): Cost {
const { cols, rows, people } = s.grid
const cost = new Float32Array(cols * rows)
const why = new Uint8Array(cols * rows)
const set = (c: number, r: number, v: number, k: number) => {
if (c < 0 || r < 0 || c >= cols || r >= rows) return
const i = r * cols + c
if (v > cost[i]) {
cost[i] = v
why[i] = k
}
}
const cells = (t: Thing, pad = 0, inset = 0) => {
const [x, y, w, h] = t
const c0 = Math.floor(((x + w * inset) / s.w) * cols) - pad
const c1 = Math.ceil(((x + w * (1 - inset)) / s.w) * cols) - 1 + pad
const r0 = Math.floor((y / s.h) * rows) - pad
const r1 = Math.ceil(((y + h) / s.h) * rows) - 1 + pad
const out: [number, number][] = []
for (let r = r0; r <= r1; r++) for (let c = c0; c <= c1; c++) out.push([c, r])
return out
}
const persons = s.things.filter((t) => t[4] === "person")
for (const p of persons) {
const inShot = p[3] >= s.h * SUBJECT_MIN
// a person's box is loose around the body (the air between arms and legs): its middle costs more than its sides
for (const [c, r] of cells(p)) set(c, r, inShot ? COST.subject : COST.crowd, inShot ? 2 : 1)
if (inShot) for (const [c, r] of cells(p, 0, 0.15)) set(c, r, COST.subject + 1, 2)
}
// the body itself, where the mask sees it (a light coat it can miss; a card laid over it hides it, hence the box)
for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) if (Number(people[r]?.[c] ?? 0) >= 4) set(c, r, COST.body, 3)
for (const t of s.things) {
if (t[4] === "person") continue
if (t[4] === "text" ? ours.some((o) => overlaps(o, shareOf(s, t), 0.4)) : (t[2] * t[3]) / (s.w * s.h) < THING_MIN) continue
for (const [c, r] of cells(t)) set(c, r, COST.thing, 4)
}
for (const o of others) for (const [c, r] of cells([o[0] * s.w, o[1] * s.h, o[2] * s.w, o[3] * s.h, "overlay", 1])) set(c, r, COST.thing, 7)
// a face and a cell around it: hair, chin, the mic at the mouth
for (const f of s.faces) {
if (f[3] >= s.h * FACE_IN_SHOT) for (const [c, r] of cells(f, 1)) set(c, r, COST.face, 5)
else for (const [c, r] of cells(f)) set(c, r, COST.crowd + 1, 1)
}
const sf = safe(s.w, s.h)
for (let r = 0; r < rows; r++)
for (let c = 0; c < cols; c++) {
const x = (c + 0.5) / cols
const y = (r + 0.5) / rows
if (y < sf.top || y > 1 - sf.bottom || x < sf.left || x > 1 - sf.right) set(c, r, COST.edge, 6)
}
return { cols, rows, cost, why }
}
/** labels of the things that make cells cost, for saying what a text covers */
function thingsUnder(s: NonNullable<Scene>, b: Box, ours: Box[] = []): string[] {
const out = new Set<string>()
for (const t of [...s.faces, ...s.things]) {
if (t[4] === "text" && ours.some((o) => overlaps(o, shareOf(s, t), 0.4))) continue
if (t[4] === "person" && t[3] < s.h * SUBJECT_MIN) continue
if (t[4] === "face" && t[3] < s.h * FACE_IN_SHOT) continue
if (t[4] !== "person" && t[4] !== "face" && (t[2] * t[3]) / (s.w * s.h) < THING_MIN) continue
const [x, y, w, h] = [t[0] / s.w, t[1] / s.h, t[2] / s.w, t[3] / s.h]
const ix = Math.max(0, Math.min(b[0] + b[2], x + w) - Math.max(b[0], x))
const iy = Math.max(0, Math.min(b[1] + b[3], y + h) - Math.max(b[1], y))
if (ix * iy > 0.12 * Math.min(w * h, b[2] * b[3])) out.add(t[4] === "person" ? "a person in the shot" : t[4] === "face" ? "a face" : t[4] === "text" ? "words in the shot (a sign)" : `a ${t[4].replace(/_/g, " ")}`)
}
return [...out]
}
/** the mean cost of the cells a box covers (each cell weighted by how much of it the box covers) */
export function boxCost(k: Cost, b: Box): number {
let sum = 0
let area = 0
const c0 = Math.max(0, Math.floor(b[0] * k.cols))
const c1 = Math.min(k.cols - 1, Math.ceil((b[0] + b[2]) * k.cols) - 1)
const r0 = Math.max(0, Math.floor(b[1] * k.rows))
const r1 = Math.min(k.rows - 1, Math.ceil((b[1] + b[3]) * k.rows) - 1)
for (let r = r0; r <= r1; r++)
for (let c = c0; c <= c1; c++) {
const ox = Math.min(b[0] + b[2], (c + 1) / k.cols) - Math.max(b[0], c / k.cols)
const oy = Math.min(b[1] + b[3], (r + 1) / k.rows) - Math.max(b[1], r / k.rows)
const a = Math.max(0, ox) * Math.max(0, oy)
sum += a * k.cost[r * k.cols + c]
area += a
}
return area ? sum / area : 0
}
/** where a box of this size costs least, over several frames together (a text's whole time on screen): candidates
* every 2% down and, for a box narrower than the frame's safe width, across too; a box on a third line (the rule of
* thirds) wins a tie */
export function places(ks: Cost[], w: number, h: number, size: [number, number], n = 3): { box: Box; cost: number }[] {
const sf = safe(w, h)
const out: { box: Box; cost: number }[] = []
const xs: number[] = []
const span = 1 - sf.left - sf.right - size[0]
if (span <= 0.02) xs.push(Math.max(0, (1 - size[0]) / 2))
else for (let x = sf.left; x <= sf.left + span + 1e-9; x += span / 4) xs.push(x)
for (let y = sf.top; y + size[1] <= 1 - sf.bottom + 1e-9; y += 0.02)
for (const x of xs) {
const b: Box = [x, y, size[0], size[1]]
const c = ks.reduce((s, k) => s + boxCost(k, b), 0) / ks.length
const mid = y + size[1] / 2
const third = Math.min(Math.abs(mid - 1 / 3), Math.abs(mid - 2 / 3))
// a wide box (a caption, a card) reads best centred; a narrow one may sit to a side
const centre = size[0] > 0.4 ? Math.abs(x + size[0] / 2 - (sf.left + (1 - sf.right)) / 2) * 1.5 : 0
out.push({ box: b, cost: c + third * 0.3 + centre })
}
out.sort((a, b) => a.cost - b.cost)
// the best few, apart from each other
const picked: { box: Box; cost: number }[] = []
for (const o of out) {
if (picked.some((p) => Math.abs(p.box[1] - o.box[1]) < size[1] && Math.abs(p.box[0] - o.box[0]) < size[0])) continue
picked.push(o)
if (picked.length >= n) break
}
return picked
}
export type Finding = { level: "error" | "warn"; kind: "text-over"; at: number | null; until?: number; says: string }
const px = (v: number, dim: number) => Math.round(v * dim)
/** each text the render's manifest shows, against the scenes of the frames it's on (sampled `rate` a second): one
* finding a text, when it covers a face, a thing or a person and a clearer place of its size exists */
export function textOver(manifest: any, scenes: Scene[], rate: number): Finding[] {
const W = Number(manifest?.width) || 1080
const H = Number(manifest?.height) || 1920
const fps = Number(manifest?.fps) || 30
// each text: its box (the ink with a margin, or the laid-out box when that's no bigger than twice the ink: a card's
// own box), and the sampled frames it's on
type On = { text: string; box: Box; from: number; to: number; frames: number[] }
// every text's box on each sampled frame
const onFrame = new Map<number, Box[]>()
const texts = new Map<string, On>()
for (const fr of (manifest?.frames ?? []) as any[]) {
const t0 = Number(fr?.frame ?? 0) / fps
const i = Math.round(t0 * rate)
if (Math.abs(i / rate - t0) > 0.5 / fps) continue
for (const t of (fr?.text ?? []) as any[]) {
const text = String(t?.text ?? "").trim()
if (!text || (t?.opacity ?? 1) <= 0.3) continue
const ink = (t?.ink ?? t?.box) as number[] | undefined
const lay = t?.box as number[] | undefined
if (!ink || ink.length < 4) continue
const useBox = lay && lay[2] * lay[3] <= 2 * ink[2] * ink[3]
const b = useBox ? lay! : [ink[0] - 12, ink[1] - 8, ink[2] + 24, ink[3] + 16]
const box: Box = [b[0] / W, b[1] / H, b[2] / W, b[3] / H]
const key = `${text}@${box.map((v) => v.toFixed(2)).join(",")}`
onFrame.set(i, [...(onFrame.get(i) ?? []), box])
const on = texts.get(key) ?? { text, box, from: t0, to: t0, frames: [] }
on.to = t0
if (!on.frames.includes(i)) on.frames.push(i)
texts.set(key, on)
}
}
// lines stacked into one block (a checklist, a two-line caption, a card's title and its line) move together: texts on
// the same frames whose boxes touch or nearly touch, one under the other
const all = [...texts.values()].sort((p, q) => p.box[1] - q.box[1])
const blocks: (On & { lines: number })[] = []
for (const t of all) {
const near = blocks.find((b) => {
const shared = t.frames.filter((f) => b.frames.includes(f)).length
const gap = t.box[1] - (b.box[1] + b.box[3])
const ox = Math.min(b.box[0] + b.box[2], t.box[0] + t.box[2]) - Math.max(b.box[0], t.box[0])
return shared * 2 >= Math.min(t.frames.length, b.frames.length) && gap < 0.02 && gap > -t.box[3] && ox > 0
})
if (!near) {
blocks.push({ ...t, frames: [...t.frames], lines: 1 })
continue
}
const x0 = Math.min(near.box[0], t.box[0])
const y0 = Math.min(near.box[1], t.box[1])
const x1 = Math.max(near.box[0] + near.box[2], t.box[0] + t.box[2])
const y1 = Math.max(near.box[1] + near.box[3], t.box[1] + t.box[3])
near.box = [x0, y0, x1 - x0, y1 - y0]
near.from = Math.min(near.from, t.from)
near.to = Math.max(near.to, t.to)
near.lines++
}
const out: Finding[] = []
for (const on of blocks) {
// the scene's cost on each of the block's frames: our own texts there aren't the shot's words, and the other texts
// on screen are places it can't go
const costAt = (i: number) => {
const s = scenes[i]
if (!s) return null
const ours = onFrame.get(i) ?? []
return costs(s, ours, ours.filter((b) => !overlaps(b, on.box, 0.5)))
}
const ks = on.frames.map(costAt).filter((k): k is Cost => !!k)
if (!ks.length) continue
const here = ks.reduce((s, k) => s + boxCost(k, on.box), 0) / ks.length
if (here < BAD) continue
const best = places(ks, W, H, [on.box[2], on.box[3]], 1)[0]
const under = [...new Set(on.frames.flatMap((i) => (scenes[i] ? thingsUnder(scenes[i]!, on.box, onFrame.get(i) ?? []) : [])))]
const what = under.length ? under.join(", ") : "what the shot shows"
const q = `${on.text.length > 40 ? `“${on.text.slice(0, 40)}...”` : `“${on.text}”`}${on.lines > 1 ? ` (and the ${on.lines - 1} line${on.lines > 2 ? "s" : ""} under it)` : ""}`
const when = on.to - on.from < 0.5 ? `at ${on.from.toFixed(1)} s` : `from ${on.from.toFixed(1)} s to ${on.to.toFixed(1)} s`
if (best && best.cost <= here - BETTER) {
const face = under.includes("a face")
out.push({ level: face || here >= BAD + 1.5 ? "error" : "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}: move it to left ${px(best.box[0], W)} px, top ${px(best.box[1], H)} px (${Math.round(best.box[1] * 100)}% down), which is clear there. raea frames place shows the clear places in a shot` })
} else if (under.includes("a face")) {
out.push({ level: "error", kind: "text-over", at: on.from, until: on.to, says: `${q} covers a face ${when} and no place of its size is clear: make it smaller, put it on a shot with room, or cut to one` })
} else if (here >= BAD + 1.5) {
out.push({ level: "warn", kind: "text-over", at: on.from, until: on.to, says: `${q} covers ${what} ${when}, and no place of its size is clear in this shot: make it smaller, show it on a shot with room (a wider one, a cutaway), or as a card of its own` })
}
}
return out.sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
}
/** `raea frames place`'s answer for a set of scenes and a box size (in a 1080-wide frame's pixels) */
export function placeReport(file: string, scenes: Scene[], size: [number, number]) {
const ss = scenes.filter((s): s is NonNullable<Scene> => !!s)
if (!ss.length) return { file, places: [] }
const w = ss[0].w
const h = ss[0].h
const scale = 1080 / Math.min(w, h)
const W = w * scale
const H = h * scale
const share: [number, number] = [size[0] / W, size[1] / H]
const ks = ss.map((s) => costs(s))
const ps = places(ks, w, h, share, 3)
return {
file: path.basename(file),
frame: [Math.round(W), Math.round(H)],
box: size,
places: ps.map((p) => ({ left: px(p.box[0], W), top: px(p.box[1], H), at: `${Math.round(p.box[1] * 100)}% down`, cost: Math.round(p.cost * 100) / 100, covers: [...new Set(ss.flatMap((s) => thingsUnder(s, p.box)))] })),
}
}
+298
View File
@@ -0,0 +1,298 @@
// `raea sound check` on a raea cloud box: what a cut's sound gets wrong that a listener hears at once, measured from the
// edit itself (its render manifest) against each source take's own words and sound, so it can't be passed by editing
// what the cut is "meant" to say (11-29, Shane on Dutch: "a lot of it is audio cuts, fading out words, putting in audio
// that is too low to hear but whisper picks up ... i dont really hear any sound effects being used").
//
// raea sound check VIDEO [--manifest RENDER.json] [-o REPORT.json]
// edit points: each voice clip's in and out against its take's words (TAKE.words.json beside the take; heard by
// the farm's Whisper when it has none) and its take's own level every 10 ms. A clip that starts or ends inside
// a word, or on sound (a word's tail, its first consonant), is an error, with the nearest gap to move it to.
// levels: each voice clip's speech level (its take's, plus its gainDb) against the cut's other lines: 6 dB or
// more apart is an error (a line too quiet to hear, that a transcriber still hears), 4 dB a warning; the
// gainDb that evens it is said.
// effects and music: an effect 10 dB or more under the voice is an error (no one hears it); music more than
// 26 dB under the voice, or within 6 dB of it, a warning.
// Exit 1 on any error. The report is VIDEO.sound-check.json beside it.
import { spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { hear, levels, type Word } from "./words.ts"
/** a voice clip's speech level is its take's loud 10 ms frames (the 90th percentile) inside the clip */
const SPEECH_Q = 0.9
/** at a cut point, sound this close to the speech level (dB) is speech still going: a word's tail or first consonant */
const ON_SOUND = 10
/** a gap to cut in: 40 ms at least this far under the speech level (dB), or, in a noisy take (a street), within
* GAP_FLOOR of its own quietest sound, but never closer than GAP_LEAST to the speech */
const GAP = 18
const GAP_FLOOR = 6
const GAP_LEAST = 8
/** a take's floor: its quietest 10 ms frames (the 10th percentile) around the clip */
const FLOOR_Q = 0.1
/** how far either side of a cut point a gap is looked for (s) */
const NEAR = 0.4
/** lines this far apart (dB) are an error, a warning */
const LEVEL_ERROR = 6
const LEVEL_WARN = 4
/** an effect this far under the voice (dB) isn't heard */
const SFX_UNDER = 10
/** music: further under than this isn't heard, closer than this fights the words */
const MUSIC_LOST = 26
const MUSIC_FIGHTS = 6
export type Finding = { level: "error" | "warn"; kind: "edit-in-word" | "edit-on-sound" | "level" | "effect-unheard" | "music" | "manifest"; at: number | null; says: string }
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
export type Manifest = { fps?: number; length?: number; frames?: unknown[]; sounds?: { fps?: number; clips?: Clip[] } }
/** a take's level every 10 ms (dB) from `start` s on */
export type Levels = { start: number; db: number[] }
const MUSIC = /music|bed|score/i
const SFX = /sfx|fx|effect|foley|sting/i
export const busOf = (c: Clip): "voice" | "music" | "sfx" => (c.bus && MUSIC.test(c.bus) ? "music" : c.bus && SFX.test(c.bus) ? "sfx" : c.bus === "voice" || !c.bus ? (SFX.test(path.basename(c.src)) ? "sfx" : MUSIC.test(path.basename(c.src)) ? "music" : "voice") : "voice")
const pct = (xs: number[], q: number) => {
if (!xs.length) return -100
const s = [...xs].sort((a, b) => a - b)
return s[Math.min(s.length - 1, Math.floor(q * s.length))]
}
const at = (l: Levels, t: number) => l.db[Math.round((t - l.start) * 100)] ?? -100
/** the loudest 10 ms frame in [a, b] */
const peak = (l: Levels, a: number, b: number) => {
let m = -100
for (let t = a; t <= b + 1e-9; t += 0.01) m = Math.max(m, at(l, t))
return m
}
const secs = (t: number) => `${t.toFixed(2)} s`
/** the speech level of a clip's stretch of its take: its loud frames, inside its words when it has any */
export function speechLevel(l: Levels, a: number, b: number, words: Word[]): number {
const inWords = words.filter((w) => w.end > a && w.start < b)
const frames: number[] = []
for (let t = a; t < b; t += 0.01) if (!inWords.length || inWords.some((w) => t >= w.start && t <= w.end)) frames.push(at(l, t))
return pct(frames, SPEECH_Q)
}
/** the nearest time to `t` (within NEAR, never past `limit` on the clip's inside) that is a gap: 40 ms around it at
* least GAP dB under the speech level and inside no word */
/** the level under which a take is quiet enough to cut in: GAP under the speech, or near the take's own floor */
export const quietUnder = (l: Levels, ref: number) => Math.min(ref - GAP_LEAST, Math.max(ref - GAP, pct(l.db, FLOOR_Q) + GAP_FLOOR))
export function nearestGap(l: Levels, t: number, ref: number, words: Word[], inside: 1 | -1, limit: number): number | null {
const under = quietUnder(l, ref)
const quiet = (c: number) => (inside === 1 ? c <= limit : c >= limit) && peak(l, c - 0.02, c + 0.02) <= under && !words.some((w) => c > w.start - 0.01 && c < w.end + 0.01)
for (let d = 0; d <= NEAR + 1e-9; d += 0.01) {
for (const s of d ? [-1, 1] : [1]) {
const c = t + s * d
if (!quiet(c)) continue
// the middle of the gap it's in (a cut at a gap's edge takes a breath or a consonant with it), kept near t
let a = c
let b = c
while (a - 0.01 >= t - NEAR && quiet(a - 0.01)) a -= 0.01
while (b + 0.01 <= t + NEAR && quiet(b + 0.01)) b += 0.01
return Math.round(((a + b) / 2) * 100) / 100
}
}
return null
}
/** how close (s) a cut is to a boundary between two words that run together to count as on it (word timings are good
* to about 30 ms) */
const SEAM = 0.03
/** boundaries between words with no pause (under 80 ms) between them */
export function seams(words: Word[]): { at: number; before: string; after: string }[] {
const out: { at: number; before: string; after: string }[] = []
for (let i = 1; i < words.length; i++) {
const a = words[i - 1]
const b = words[i]
if (b.start - a.end < 0.08) out.push({ at: Math.round(((a.end + b.start) / 2) * 1000) / 1000, before: a.text, after: b.text })
}
return out
}
/** a voice clip's in and out: inside a word, or on sound */
export function editPoints(c: Clip, fps: number, words: Word[], l: Levels): Finding[] {
const out: Finding[] = []
const dur = (c.to - c.from) / fps
const tin = c.at
const tout = c.at + dur
const ref = speechLevel(l, tin, tout, words)
const name = path.basename(c.src)
for (const [edge, t, cutAt, inside] of [["in", tin, c.from / fps, 1], ["out", tout, c.to / fps, -1]] as const) {
const where = `the ${edge === "in" ? "start" : "end"} of the clip at ${secs(cutAt)} (${name} ${secs(t)})`
// speech that runs on with no pause still has its boundaries between words: a cut on one is tight, not a cut word
const seam = seams(words).find((x) => Math.abs(x.at - t) <= SEAM)
if (seam) {
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
if (here >= ref - ON_SOUND)
out.push({ level: "warn", kind: "edit-on-sound", at: cutAt, says: `${where} is between “${seam.before}” and “${seam.after}” with no pause: a tight cut. Look at it on the waveform, or move it to a pause if one is near` })
continue
}
const word = words.find((w) => w.start + 0.02 < t && w.end - 0.02 > t)
const gap = nearestGap(l, t, ref, words, inside, inside === 1 ? tout - 0.1 : tin + 0.1)
const ms = (x: number) => `${x >= t ? "+" : ""}${Math.round((x - t) * 1000)} ms`
const bound = gap === null ? seams(words).filter((x) => Math.abs(x.at - t) <= NEAR && (inside === 1 ? x.at < tout - 0.1 : x.at > tin + 0.1)).sort((p, q) => Math.abs(p.at - t) - Math.abs(q.at - t))[0] : undefined
const move =
gap !== null
? `move it to ${secs(gap)} in ${name} (${ms(gap)}), the gap ${edge === "in" ? "before" : "after"} the words`
: bound
? `there's no pause within ${NEAR * 1000} ms; the nearest boundary between words is ${secs(bound.at)} in ${name} (${ms(bound.at)}, between “${bound.before}” and “${bound.after}”): cut there, or at another pause`
: `no pause or word boundary within ${NEAR * 1000} ms: cut at another pause, or take another line`
if (word) {
out.push({ level: "error", kind: "edit-in-word", at: cutAt, says: `${where} cuts “${word.text}” (${secs(word.start)}–${secs(word.end)}) in two: ${move}` })
continue
}
// the 10 ms just inside the cut: a word's onset a frame or two after an in point is a tight cut, not a cut one
const here = edge === "in" ? peak(l, t, t + 0.01) : peak(l, t - 0.01, t)
if (here >= Math.max(ref - ON_SOUND, pct(l.db, FLOOR_Q) + GAP_FLOOR + 2)) {
const near = words.reduce<Word | null>((b, w) => (Math.min(Math.abs(w.start - t), Math.abs(w.end - t)) < (b ? Math.min(Math.abs(b.start - t), Math.abs(b.end - t)) : 9) ? w : b), null)
out.push({ level: "error", kind: "edit-on-sound", at: cutAt, says: `${where} lands on sound ${Math.max(0, ref - here).toFixed(0)} dB under the speech${near ? `, ${Math.round(Math.min(Math.abs(near.start - t), Math.abs(near.end - t)) * 1000)} ms from “${near.text}”` : ""}: the word's ${edge === "in" ? "first sound" : "tail"} is cut. ${move[0].toUpperCase()}${move.slice(1)}` })
}
}
return out
}
export type Heard = { clip: Clip; kind: "voice" | "music" | "sfx"; level: number }
/** each voice line against the cut's others; effects and music against the voice */
export function balance(heard: Heard[], fps: number): Finding[] {
const out: Finding[] = []
const voice = heard.filter((h) => h.kind === "voice" && (h.clip.to - h.clip.from) / fps >= 0.4)
if (!voice.length) return out
const mid = pct(voice.map((h) => h.level), 0.5)
for (const h of voice) {
const d = h.level - mid
if (Math.abs(d) < LEVEL_WARN) continue
const g = (h.clip.gainDb ?? 0) - d
out.push({ level: Math.abs(d) >= LEVEL_ERROR ? "error" : "warn", kind: "level", at: h.clip.from / fps, says: `the line at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)} ${secs(h.clip.at)}) is ${Math.abs(d).toFixed(0)} dB ${d < 0 ? "under" : "over"} the cut's other lines${d < 0 ? ": too quiet to hear, though a transcriber still hears it" : ""}. Set its gainDb to ${g.toFixed(1)} (now ${(h.clip.gainDb ?? 0).toFixed(1)})` })
}
for (const h of heard.filter((x) => x.kind === "sfx")) {
const d = h.level - mid
if (d <= -SFX_UNDER)
out.push({ level: "error", kind: "effect-unheard", at: h.clip.from / fps, says: `the effect at ${secs(h.clip.from / fps)} (${path.basename(h.clip.src)}) peaks ${(-d).toFixed(0)} dB under the voice: no one hears it. Set its gainDb to about ${((h.clip.gainDb ?? 0) - d - 4).toFixed(1)} (4 dB under the voice), or cut it` })
}
for (const h of heard.filter((x) => x.kind === "music")) {
const d = h.level - mid
if (d < -MUSIC_LOST) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) sits ${(-d).toFixed(0)} dB under the voice: it's barely there. A bed under speech sits 12 to 20 dB under: gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
else if (d > -MUSIC_FIGHTS) out.push({ level: "warn", kind: "music", at: h.clip.from / fps, says: `the music (${path.basename(h.clip.src)}) is within ${MUSIC_FIGHTS} dB of the voice: it fights the words. gainDb about ${((h.clip.gainDb ?? 0) - d - 16).toFixed(1)}` })
}
return out
}
/** the take a manifest names, on this box: its own path, or the part after a farm job's work/ under the project */
export function onBox(src: string, roots: string[]): string | null {
if (existsSync(src)) return src
const rel = src.includes("/work/") ? src.slice(src.lastIndexOf("/work/") + 6) : src.replace(/^\/+/, "")
for (const r of roots) {
const p = path.resolve(r, rel)
if (existsSync(p)) return p
}
return null
}
const wordsOf = (file: string) => `${file.slice(0, file.length - path.extname(file).length)}.words.json`
async function takeWords(file: string): Promise<Word[]> {
for (const p of [wordsOf(file), `${file}.words.json`]) {
if (existsSync(p)) {
const raw = JSON.parse(readFileSync(p, "utf8")) as ({ text: string; start_ms: number; end_ms: number } | Word)[] | { words: { text: string; start_ms: number; end_ms: number }[] }
const list = Array.isArray(raw) ? raw : raw.words
return list.map((w) => ("start_ms" in w ? { text: w.text, start: w.start_ms / 1000, end: w.end_ms / 1000 } : w))
}
}
const heard = await hear(file)
writeFileSync(wordsOf(file), `${JSON.stringify(heard.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) })))}\n`)
return heard
}
/** a take's level every 10 ms over [a, b] */
function takeLevels(file: string, a: number, b: number): Levels {
const start = Math.max(0, a)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-sound-"))
try {
const raw = path.join(dir, "a.raw")
const r = spawnSync("ffmpeg", ["-v", "error", "-y", "-ss", String(start), "-t", String(Math.max(0.05, b - start)), "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", "-f", "s16le", raw], { encoding: "utf8" })
if (r.status !== 0 || !existsSync(raw)) return { start, db: [] }
const buf = readFileSync(raw)
return { start, db: levels(new Int16Array(buf.buffer, buf.byteOffset, Math.floor(buf.length / 2))) }
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
function flag(args: string[], name: string): string | undefined {
const i = args.indexOf(name)
return i >= 0 ? args[i + 1] : undefined
}
const stem = (v: string) => v.slice(0, v.length - path.extname(v).length)
/** the render's manifest: --manifest, else VIDEO.render.json (what raea cloud writes), else VIDEO.manifest.json */
export const manifestFor = (video: string, given?: string) => given ?? [`${stem(video)}.render.json`, `${stem(video)}.manifest.json`].find(existsSync) ?? `${stem(video)}.render.json`
export async function check(video: string, manifestPath: string, roots: string[]): Promise<{ findings: Finding[]; voice: number }> {
const m = JSON.parse(readFileSync(manifestPath, "utf8")) as Manifest
const fps = m.sounds?.fps ?? m.fps ?? 30
const found: Finding[] = []
const length = m.length ?? 0
const frames = m.frames?.length ?? 0
if (length > 1 && frames < length * 0.9)
found.push({ level: "error", kind: "manifest", at: null, says: `${path.basename(manifestPath)} holds ${frames} of the cut's ${length} frames, so its edit can't be checked: render the cut again (a render on raea cloud's GPUs before 11-29 kept frame 0's alone)` })
const clips = m.sounds?.clips ?? []
const heard: Heard[] = []
let voice = 0
for (const c of clips) {
const kind = busOf(c)
const file = onBox(c.src, roots)
if (!file) {
found.push({ level: "warn", kind: "manifest", at: c.from / fps, says: `${c.src} isn't on this box: its clip at ${secs(c.from / fps)} isn't checked` })
continue
}
const dur = (c.to - c.from) / fps
if (kind === "voice") {
voice++
const words = await takeWords(file)
const l = takeLevels(file, c.at - NEAR - 0.1, c.at + dur + NEAR + 0.1)
found.push(...editPoints(c, fps, words, l))
heard.push({ clip: c, kind, level: speechLevel(l, c.at, c.at + dur, words) + (c.gainDb ?? 0) })
} else {
const l = takeLevels(file, c.at, c.at + Math.min(dur, kind === "sfx" ? 2 : 20))
const level = kind === "sfx" ? pct(l.db, 0.98) : pct(l.db.filter((x) => x > -70), 0.5)
heard.push({ clip: c, kind, level: level + (c.gainDb ?? 0) })
}
}
found.push(...balance(heard, fps))
return { findings: found.sort((a, b) => (a.at ?? -1) - (b.at ?? -1)), voice }
}
export async function main(args: string[]): Promise<number> {
const a = args[0] === "check" ? args.slice(1) : args
const video = a.find((x, i) => !x.startsWith("-") && !["--manifest", "-o"].includes(a[i - 1] ?? ""))
if (!video || !existsSync(video)) {
console.error("usage: raea sound check VIDEO [--manifest RENDER.json] [-o REPORT.json] (edit points inside words or on sound, lines too quiet to hear, effects no one hears)")
return 2
}
const man = manifestFor(video, flag(a, "--manifest"))
if (!existsSync(man)) {
console.error(`raea sound check: no manifest for ${path.basename(video)} (${path.basename(man)}): render it with --manifest, or on raea cloud, which writes VIDEO.render.json`)
return 2
}
// the project the takes are under: here, and each folder above the video up to here
const roots = [process.cwd()]
for (let d = path.dirname(path.resolve(video)); d.startsWith(process.cwd()) && d !== process.cwd(); d = path.dirname(d)) roots.push(d)
const { findings, voice } = await check(video, man, roots)
for (const x of findings) console.log(`${x.level === "error" ? "ERROR" : "WARN "} ${x.at === null ? "" : `${x.at.toFixed(2)} s `}${x.says}`)
const errors = findings.filter((x) => x.level === "error").length
const report = flag(a, "-o") ?? `${stem(video)}.sound-check.json`
writeFileSync(report, `${JSON.stringify({ object: "sound.check", video, manifest: man, voice_clips: voice, passed: errors === 0, errors, warnings: findings.length - errors, findings }, null, 1)}\n`)
console.log(`${errors ? "FAILED" : "PASSED"} ${path.basename(video)}: ${voice} voice clips, ${errors} errors, ${findings.length - errors} warnings; ${path.basename(report)}`)
return errors ? 1 : 0
}
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const a = process.argv.slice(2)
main(a[0] === "sound" ? a.slice(1) : a).then(
(c) => process.exit(c),
(e) => (console.error(`raea sound: ${(e as Error).message}`), process.exit(1)),
)
}
+19 -1
View File
@@ -45,7 +45,17 @@ class FakeGpu:
if video:
# the run as one H.264 video, as raea render --at FRAMES -o run.mp4 writes it
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=gray:s=16x16:r=30", "-frames:v", str(len(frames)), "-c:v", "libx264", "-pix_fmt", "yuv420p", f"{dest}/run-{first:05d}.mp4"])
return {"code": 0, "out": "", "s": 12 + 0.5 * len(frames), "frames": len(frames), "ms": 500.0}
# and its manifest, as raea writes one for --at's frames: those frames, and each sound cut to them (a clip's
# `at` is its source time at the run's first frame). One voice clip over frames 0-39, another from 40
a, z = frames[0], frames[-1] + 1
clips = []
if a < 40:
clips.append({"key": "n3", "from": a, "to": min(z, 40), "src": "/w/media/take.mov", "at": 1.0 + a / 30, "gainDb": 0.0, "bus": "voice", **({"fadeIn": 0.012} if a == 0 else {})})
if z > 40:
f = max(a, 40)
clips.append({"key": "n8", "from": f, "to": z, "src": "/w/media/take.mov", "at": 9.0 + (f - 40) / 30, "gainDb": -2.0, "bus": "voice", **({"fadeOut": 0.012} if z == self.length else {})})
man = {"width": 1920, "height": 1080, "fps": 30, "length": self.length, "frames": [{"frame": f, "videos": [], "text": [{"text": f"t{f}"}]} for f in frames], "findings": [], "sounds": {"fps": 30, "clips": clips, "notes": [], "lines": []}}
return {"code": 0, "out": "", "s": 12 + 0.5 * len(frames), "frames": len(frames), "ms": 500.0, "manifest": man}
for f in frames:
if f >= first:
self.png(f"{dest}/frame-{f:05d}.png")
@@ -104,6 +114,14 @@ assert code == 0, lines
assert all("--manifest" not in a and "--quality" in a for a in m.args), m.args
assert json.load(open(os.path.join(root, "jobs", "jm", "work", "out", "a.render.json")))["length"] == 60
ok("a render's own --manifest isn't passed to the GPUs (the probe would lose the length), and is written at the end")
# 11-29 (Dutch): the manifest written was frame 0's alone, so a cut's edit (every clip, where it starts in its source) was
# lost and nothing could check its edit points. It's the runs' own manifests joined: every frame, each clip whole
man = json.load(open(os.path.join(root, "jobs", "jm", "work", "out", "a.render.json")))
assert [f["frame"] for f in man["frames"]] == list(range(60)), [f["frame"] for f in man["frames"]][:12]
clips = sorted(man["sounds"]["clips"], key=lambda c: c["from"])
assert [(c["key"], c["from"], c["to"]) for c in clips] == [("n3", 0, 40), ("n8", 40, 60)], clips
assert abs(clips[0]["at"] - 1.0) < 1e-6 and abs(clips[1]["at"] - 9.0) < 1e-6 and clips[0].get("fadeIn") == 0.012 and clips[1].get("fadeOut") == 0.012, clips
ok("a split render's manifest is its runs' joined: all 60 frames, and each clip whole with its source time")
lines.clear()
long = FakeGpu(root, length=1000)
+1
View File
@@ -0,0 +1 @@
{"a": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222456542222222222222", "222222246777763222222222222", "222222267777776322222222222", "222222277777777522222222222", "222222267777777732222222222", "222222267777777752222222222", "222222267777777773222222222", "222222247777777775222222222", "222222224677777777322222222", "222222222677777777522222222", "222223322677777777632222222", "222323323777777777732222222", "225533324777777777752222222", "224653224777777777763222222", "222554325777777777774222222", "222454435777777777776222222", "222444334777777777776222222", "222433333567777777777322222", "222223323445677777777422222", "222222322333345666666422222", "222222322333345666666422222", "222222232344445666664222222", "222222233344545556663222222", "222222223344444555553222222", "222222223334444444443222222", "222222222223332323332222222", "222222222223332222232222222", "222222222333333222232222222", "222222222333333222332222222", "222222222223322222322222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222"]}, "things": [[26.2, 134.5, 409.7, 600.0, "person", 0.887], [422.1, 49.1, 117.8, 310.0, "person", 0.87], [96.8, 73.6, 26.0, 77.0, "person", 0.752], [318.6, 59.3, 34.7, 64.6, "person", 0.682], [0.2, 95.0, 29.7, 92.3, "person", 0.575], [384.2, 56.3, 49.6, 71.9, "person", 0.566], [148.7, 94.7, 25.4, 35.7, "person", 0.49], [202.9, 65.2, 35.5, 71.9, "person", 0.479], [421.5, 57.1, 55.3, 213.8, "person", 0.377], [1.3, 65.8, 24.1, 46.5, "person", 0.357], [176.0, 878.0, 165.0, 76.0, "text", 0.978], [362.0, 844.0, 149.0, 57.0, "text", 0.94], [179.0, 816.0, 182.0, 65.0, "text", 0.978], [366.0, 776.0, 171.0, 62.0, "text", 0.987], [183.0, 742.0, 191.0, 80.0, "text", 0.986], [180.0, 677.0, 180.0, 35.0, "text", 0.993], [181.0, 611.0, 182.0, 36.0, "text", 0.99], [154.0, 573.0, 238.0, 25.0, "text", 0.991], [146.0, 529.0, 258.0, 25.0, "text", 0.989]], "faces": [[131.1, 174.9, 82.5, 143.1, "face", 0.878], [332.9, 60.6, 12.0, 15.0, "face", 0.788], [435.5, 67.1, 20.6, 23.9, "face", 0.711], [421.1, 61.4, 11.2, 13.5, "face", 0.678]]}, "b": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222234332222222222", "222222222223677764222222222", "222222222225777777322222222", "222222222227777777622222222", "222222222237777777732222222", "222222222227777777752222222", "222222222226777777762222222", "222222222225777777773222222", "222222222225777777775222222", "222222222456777777776322222", "222222224777777777777622222", "222222236667777777777732222", "222222256667777777777752222", "222222366666677777777762222", "222222366666677777777762222", "222222456666777777777762222", "222222466666777777777762222", "222223566666777777777763222", "222223566667777777777653222", "222223466667777777777543222", "222223356667777777777432222", "222223335666777777776332222", "222222335666666666764222222", "222222356556556554543222222", "222222365555444333332222222", "222222354443333333222222222", "222222343333222222222222222", "222222343322222222222222222", "222222333222222222222222222", "222222232222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222"]}, "things": [[112.8, 117.2, 356.1, 835.9, "person", 0.867], [145.0, 677.0, 252.0, 37.0, "text", 0.994]], "faces": [[216.5, 193.3, 78.6, 128.6, "face", 0.902], [138.4, 362.6, 54.1, 79.0, "face", 0.739]]}, "c": {"w": 540, "h": 960, "grid": {"cols": 27, "rows": 48, "people": ["222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222222222222222", "222222222222222332222222222", "222222222222225664222222222", "222222222222247777322222222", "222222222222257777522222222", "222222222222367777522222222", "222222222223677777522222222", "222222222236777777622222222", "222222222367777777622222222", "222222222577777777733Line truncated
+40
View File
@@ -0,0 +1,40 @@
// Text placement (server/place.ts) on three frames of street interviews, read by the farm's scene models
// (deploy/modal/farm_scene.py; the fixture holds only their boxes and grids): node test/place.ts
// 11-29 (Dutch): a caption laid over the dog the shot is about, a checklist on a woman's lap, beside a sign that is the
// ad's own hook
import assert from "node:assert/strict"
import { readFileSync } from "node:fs"
import { placeReport, textOver } from "../server/place.ts"
const ok = (m: string) => console.log(`ok ${m}`)
const sc = JSON.parse(readFileSync(new URL("./fixtures/scenes-interview.json", import.meta.url), "utf8"))
const t = (text: string, x: number, y: number, w: number, h: number) => ({ text, box: [x, y, w, h], ink: [x + 10, y + 6, w - 20, h - 12], opacity: 1, size: 48 })
const man = (texts: unknown[]) => ({ width: 1080, height: 1920, fps: 30, frames: [{ frame: 0, text: texts }] })
// c: a woman sitting with her dog; the caption on the dog, the hook over the crowd behind her
const c = textOver(man([t("$1,000 for one vet visit?", 116, 236, 848, 112), t("He hurt his little", 290, 1335, 630, 90)]), [sc.c], 1)
assert.equal(c.length, 1, JSON.stringify(c))
assert.equal(c[0].level, "error")
assert.match(c[0].says, /“He hurt his little” covers a dog/)
const top = Number(/top (\d+) px/.exec(c[0].says)?.[1])
assert.ok(top >= 1380, `moved below the dog, not ${top}`)
ok("a caption over the dog is an error, moved to the clear ground under it; the hook over passers-by is fine")
// a: a checklist on a woman's lap, a sign under her, a man standing behind: no clear place for a block that size
const a = textOver(man([t("✓ 24/7 virtual vet care", 256, 1044, 568, 80), t("✓ Price-matched Rx", 280, 1130, 520, 76), t("✓ Free delivery", 336, 1214, 410, 76)]), [sc.a], 1)
assert.equal(a.length, 1, "the checklist's three lines are one block")
assert.match(a[0].says, /and the 2 lines under it\) covers a person in the shot/)
assert.match(a[0].says, /no place of its size is clear/)
ok("a checklist on a person is said once for its block, and that no place its size is clear")
// the clearest places for a caption in a: never on the sign, which is the ad's hook
const pa = placeReport("a.jpg", [sc.a], [840, 110])
assert.ok(pa.places.length >= 2)
assert.ok(!pa.places[0].covers.includes("words in the shot (a sign)"), JSON.stringify(pa.places[0]))
assert.ok(pa.places[0].top < 400, JSON.stringify(pa.places[0]))
ok("raea frames place keeps a caption off the sign in the shot")
// b: a woman filling the frame; a caption over her coat is at most a warning
const b = textOver(man([t("Did you know you", 272, 1344, 536, 88)]), [sc.b], 1)
assert.ok(b.every((x) => x.level === "warn"), JSON.stringify(b))
ok("a caption over a person who fills the frame is at most a warning")
+80
View File
@@ -0,0 +1,80 @@
// `raea sound check`'s measures (server/sound.ts), on made-up takes: node test/sound.ts
// 11-29 (Dutch): words cut in two at a clip's edge, a guest's line 15 dB under the host's, effects 18 dB under the voice
import assert from "node:assert/strict"
import { balance, busOf, editPoints, nearestGap, type Clip, type Heard, type Levels } from "../server/sound.ts"
const ok = (m: string) => console.log(`ok ${m}`)
// a take: words at 1.00-1.40, 1.50-1.90 ("very" "loud") and 2.40-2.80 ("next"); speech at -20 dB, the street at -50
const words = [
{ text: "very", start: 1.0, end: 1.4 },
{ text: "loud", start: 1.5, end: 1.9 },
{ text: "next", start: 2.4, end: 2.8 },
]
const db: number[] = []
for (let t = 0; t < 4; t += 0.01) db.push(words.some((w) => t >= w.start - 0.005 && t <= w.end + 0.005) ? -20 : -50)
const take: Levels = { start: 0, db }
const fps = 30
const clip = (at: number, dur: number, extra: Partial<Clip> = {}): Clip => ({ key: "n1", from: 30, to: 30 + Math.round(dur * fps), src: "/w/work/media/raw/take.mov", at, gainDb: 0, bus: "voice", ...extra })
// cut in the gaps: 0.90 to 2.10 (both edges in silence)
assert.deepEqual(editPoints(clip(0.9, 1.2), fps, words, take), [])
ok("a clip cut in the gaps around its words passes")
// out at 1.70: inside "loud"
const inWord = editPoints(clip(0.9, 0.8), fps, words, take)
assert.equal(inWord.length, 1)
assert.equal(inWord[0].kind, "edit-in-word")
assert.match(inWord[0].says, /“loud”/)
assert.match(inWord[0].says, /move it to 1\.4\d s/)
ok("an out point inside a word is an error, with the gap before it to move to")
// in at 1.01: a hair past the start of "very" (inside the 20 ms grace), so it's on sound, not inside the word
const onSound = editPoints(clip(1.01, 1.0), fps, words, take)
assert.equal(onSound[0]?.kind, "edit-on-sound", JSON.stringify(onSound))
assert.match(onSound[0].says, /first sound/)
ok("an in point on a word's first sound is an error")
// "loud" and "next" run together with no pause: a cut on their boundary is tight (a warning), not a cut word
const run = [{ text: "say", start: 1.0, end: 1.4 }, { text: "so", start: 1.42, end: 1.7 }, { text: "then", start: 1.72, end: 2.0 }]
const runDb: number[] = []
for (let t = 0; t < 4; t += 0.01) runDb.push(t >= 0.995 && t <= 2.005 ? -20 : -50)
const tight = editPoints(clip(0.9, 0.81), fps, run, { start: 0, db: runDb })
assert.deepEqual(tight.map((x) => [x.level, x.kind]), [["warn", "edit-on-sound"]], JSON.stringify(tight))
assert.match(tight[0].says, /between “so” and “then”/)
const cutSo = editPoints(clip(0.9, 0.65), fps, run, { start: 0, db: runDb })
assert.equal(cutSo[0]?.level, "error")
assert.match(cutSo[0].says, /no pause within 400 ms; the nearest boundary between words is 1\.71 s/)
ok("a cut on the boundary of words that run together is a warning; inside one, the nearest boundary is said")
assert.equal(nearestGap(take, 1.7, -20, words, -1, 1.0), 1.45)
assert.equal(nearestGap({ start: 0, db: db.map(() => -20) }, 1.7, -20, [], -1, 0), null)
ok("the nearest gap is found, and a take with none says so")
// levels: three lines at -14, one guest at -29 (15 dB under: Gigi's hook B); an effect at -32; music at -50
const line = (from: number, level: number, extra: Partial<Clip> = {}): Heard => ({ clip: { ...clip(1, 2), from, to: from + 60, ...extra }, kind: "voice", level })
const heard: Heard[] = [
line(0, -14),
line(60, -29, { src: "/w/work/media/raw/guest.mov" }),
line(120, -15),
line(180, -13),
{ clip: { ...clip(0, 1), from: 90, to: 120, src: "/w/work/media/elevenlabs/sfx_pop.mp3", bus: "sfx", gainDb: -14 }, kind: "sfx", level: -32 },
{ clip: { ...clip(0, 20), from: 0, to: 600, src: "/w/work/media/elevenlabs/music.mp3", bus: "music", gainDb: -20 }, kind: "music", level: -50 },
]
const b = balance(heard, fps)
const quiet = b.find((x) => x.kind === "level")
assert.equal(quiet?.level, "error")
assert.match(quiet!.says, /guest\.mov/)
assert.match(quiet!.says, /15 dB under/)
assert.match(quiet!.says, /gainDb to 15\.0/)
assert.equal(b.filter((x) => x.kind === "level").length, 1, "the lines within 4 dB of each other pass")
const sfx = b.find((x) => x.kind === "effect-unheard")
assert.equal(sfx?.level, "error")
assert.match(sfx!.says, /18 dB under the voice/)
assert.equal(b.find((x) => x.kind === "music")?.level, "warn")
ok("a line 15 dB under the others is an error with the gain that evens it; an effect 18 dB under is unheard; buried music is said")
assert.equal(busOf({ ...clip(0, 1), bus: undefined, src: "/x/media/elevenlabs/sfx_tap.mp3" }), "sfx")
assert.equal(busOf({ ...clip(0, 1), bus: undefined, src: "/x/media/raw/Interview1.MOV" }), "voice")
assert.equal(busOf({ ...clip(0, 1), bus: "music", src: "/x/a.mp3" }), "music")
ok("a clip's kind from its bus, or its file's name when it has none")