Compare commits

...
Author SHA1 Message Date
shinyobjectz 4c5021b85e The farm draws a video with no 3D without a GPU, keeps its runs by their frames' keys, reads clips at the size they're drawn, and joins every frame
- A video whose frame 0 has no 3D is drawn on containers with no GPU (cpus, 8 by default; 0 keeps it on GPUs); a run
  that fails there or draws 3D is drawn again on a GPU.
- A run's frame is timed by raea's own clocks over the whole frame, a part's start planned at 5 s at least, 2 parts
  at most a container with no GPU.
- With render --keys, a video's runs are kept under their frames' keys in a store named for the raea, the arguments
  and the job's files; a job draws only the frames no kept run holds, and a sound-only change draws none and joins
  the kept pictures to the new sound. A 30 s ad drawn again unchanged: 46 s and $0.000; one caption word changed:
  148 frames, $0.011.
- A clip much larger than it's drawn is read from a copy at its drawn size (lanczos, CRF 12, sound, frame times and
  face track kept), made on containers with no GPU and kept by hash. The ad as a half-size draft: frames in 30-37 s
  from copies against 48-65 s. A master that needs its clips whole gets no copies.
- A piece with 3D asks its GPU runs for NVENC and NVDEC (RAEA_NV=1; needs raea with engine-render-cost, older raea
  ignores it).
- The join reads only the runs' video tracks and cuts at the piece's length: each run's AAC track moved the joined
  video 21 ms after the sound and -shortest then ended it 2 frames early (892 of 894 frames on every split render).
- deploy/modal/build.py builds a Linux raea from a source folder into the volume; a test farm deployed with
  RAEA_FARM_BUILD=NAME runs it. bench/job.ts times one job, bench/encode.py the encoders.
- An unknown GPU name is a GPU, not a CPU, in the bill; A10G is an A10.

Without --keys (raea 0.1.13 and older) a job runs as before, on GPUs or CPUs by its probe, with nothing kept.
2026-11-30 18:14:25 -08:00
shaneandshinyobjectz 95b2c01a24 raea goal check reads an export's captions and hears its voice (captions + voice packs; farm reads text) (#280)
* raea goal check reads an export's captions and hears its voice: captions and voice packs, and the farm reads text

Shane 11-30: "running a transcription and ocr pass on the final output ... catch if audio captions pick up something
else that's not supposed to be there or if we cut off words. as well we should be checking audio if it's too quiet
for dialogue". Elfster's cut 1 shipped hand-typed captions that dropped "when they get", "okay, this is" and
"organize your"; Body Shop's reaction cut buried the host 7 dB over its music. No check saw either.

captions (sdk/goal/src/packs/captions.ts): the farm's /v1/scene now reads each line of text (texts, RapidOCR
PP-OCRv4, Apache-2.0, about 0.13 s a 540-wide frame on CPU). A line is a caption when it fits what's said while
it's up with few edits (capitals, a badge's style, held stricter), lasts under 4.5 s, sits in a row with other
captions, in a frame with 3 lines or fewer, and the cut has a track of them (8 showings, 40% of the speech).
Shown-not-said: letters no word near it holds. Said-not-shown: words between captioned words that no caption has,
an error for 3 or more in a row where the captions are phrases; a line at a caption run's edge is a warning.
Calibrated on our 8 Elfster/Body Shop cuts and 4 shipped client refs: the refs' phrase captions pass clean but
one (Body Shop Video6's opening line under its hook card), and ours find what was found by hand.

voice (packs/voice.ts): on the export, the speech's level (80th percentile inside words) over the bed between
words: under 6 dB an error, under 10 a warning; each line against the typical line: 6 dB quieter an error, 4 a
warning. The 4 refs are clean; Elfster 2am (4.5 dB) and Body Shop edible (4.4) fail.

Both are in the cut and floor sets. The Scene type carries texts; media.ts passes them through. The farm needs a
deploy (rapidocr in the image) before captions reads anything; until then it notes the reader has no texts.

* raea goal check times on-screen text against its words: the reading pack

Shane 11-30: "the words on screen relative to duration ... if a wordy CTA or component or scene is meant to be fully
read or if it just adds glossable content or context, and if it's on screen long enough to be read."

From the farm's texts, every line that isn't a caption (nor words shown as they're said) is followed frame to frame;
lines that come up together are one block. A block needs 0.5 s plus 3 words a second: under that a warning, under 60%
of it an error. A block of 25 words or more, small text (under 54 px of 1080x1920) or a phone's screen (a status-bar
clock) is texture: a warning that asks whether it's meant to be read. Frames with more than 6 lines (a shelf of
labels, an app shot whole) and blocks of 3 words or fewer are left out. Every finding gives words, seconds and words
a second.

Calibrated on the 8 Elfster/Body Shop cuts and 4 shipped refs: it finds Elfster cut 2's 15-word hook card up 1 s and
Body Shop's reaction CTA card (11 words, 2 s); the refs give one error (an Elfster app screen up 1 s). In cut and floor.

* raea goal check holds every size the brief asks for at done (sizes-all)

Shane 11-30: "it will show completed but what about doing all the resizes". Dutch finished on its 9:16 masters alone:
the brief's 4:5, 1:1 and 16:9 were never made, because one-size-first was a rule against resizing early and nothing
asked for the other sizes at the end. At done, every ad's newest version (adOf, _v#) must be in every format its
brief names (cut `formats`, the brief's and each cut's), unless a person's answer to the open item about "sizes"
names fewer. The finding says which sizes are missing and the file name each takes. test/sizes.test.ts.

* raea ducks music under the talking by default, and goal check holds the hook and the air between words

Shane 11-30: the StreetTalk cuts' music was "about 4 or 5 decibels too loud ... make sure standards and measurements
correctly mix by default to move audio down in the mix, especially while talking, but a CTA with no audio is fine";
Elfster's Voted cut opened on 1.5 s of a silent whiteboard ("a hook really should have audio and video stimulation");
and "measuring and cutting air gaps safely ... it CANNOT destroy words".

- systems/mix: an edit with no Tone graph gets DEFAULT_GRAPH: footage and voice files on a `talk` bus, effects on the
  master, any other audio file on a `bed` bus ducked DEFAULT_DUCK_DB (-6) under the talking, released where nobody
  talks. The names aren't raea/tone's, so an edit's own buses never change; `bus="master"` opts a sound out. Offline
  bounce and live play pick it the same way (score.rs routes a bus-less sound by default_bus). Test: the music sits
  6 dB down under the talk and comes back after it.
- @raea/video airgaps: airGaps(words) and tighten(words, { levels }): the spans of a take to keep, gaps cut to 0.15 s
  in the hook and 0.25 s after, only between words, 80 ms kept either side, each cut pulled back while the take is
  still loud (a transcript's early word end).
- goal packs hook and airgaps (cut and floor): a first word over 1 s in with a quiet opening is an error (Voted:
  1.5 s, -15 dB); gaps over 0.5 s in the first 3 s are errors, over 0.3 s warnings, over 0.8 s after warnings.
- sound pack: bus-less files classed as the mixer routes them (a music file with any name is music, not a voice
  line), the default duck counted, and music within 10 dB of the voice warns (was 6), as the voice pack does.

* The voice check judges the bed only on enough gaps between words

Body Shop's host-hook cut read "1.5 dB above what's under it" off a single 0.34 s gap between two "Mmm"s, where the
speaker was still humming; the agent's own measure (pauses of 0.8 s and more) read 11.7 dB. A tightly cut take has few
gaps, so the bed is judged only on 3 or more gaps and 1 s of them in all.

* The default mix's graph moves to raea-sys-tone, and its test to its own file, so raea-sys-mix is under 2000 lines

CI's size gate: raea-sys-mix was 2048 lines and offline.rs 530. DEFAULT_GRAPH, DEFAULT_DUCK_DB and default_bus are
the default Tone graph, so they live with the graph format in raea-sys-tone (defaults.rs) and raea-sys-mix re-exports
them; the duck test is duck_test.rs.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 15:13:18 -08:00
shaneandshinyobjectz c81b4e8c23 The farm shares its GPUs and says when a render waits; it encodes with libx264 (#275)
* The farm gives a job 4 GPUs unless it asks for more, and says when a GPU run hasn't answered

A 1,150-frame cut took all 10 of the workspace's GPUs, each drawing 10-20 s, so every other render queued behind it,
and a queued run printed nothing: StreetTalk's agents read the silence as "stalled before frame 0" (11-30).
RAEA_FARM_JOB_GPUS (4) is a job's default; farm_plan.waited logs every 30 s while a probe, first run or whole job waits.

* The farm encodes a video's runs with libx264 at the quality's CRF, not openh264 at a bitrate

openh264's near-blacks stepped into blocks even at --quality master's 37.7 Mbps: raea check's blotching failed every
Dutch cut rendered on the farm, and its agent re-encoded each one with x264 CRF 14 afterwards (a second generation and
minutes a cut). RAEA_MEDIA=ffmpeg makes raea's encode the ffmpeg CLI's libx264 (master CRF 11); the runs still join
by stream copy, and the first run's x264 header tells raea check the darks were kept.

* The farm's GPU wait gives up on a run that ran out of its own time, as .remote() did

Modal's FunctionTimeoutError is a subclass of its TimeoutError, so waited() caught a run's own timeout as "no answer
yet" and asked again forever, logging "waiting" instead of failing the job. It now goes up as before. Test: a run that
timed out fails the job with no wait lines.

---------

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 07:50:06 -08:00
shaneandshinyobjectz 1430731bf3 The box server keeps a quiet stream open past Cloudflare's 100 s, and ends an agent silent both ways for 45 min (#277)
/v1/shell and /v1/run sent no headers until their command printed: raea goal check --json over Dutch's seven cuts
printed nothing for over 100 s, Cloudflare answered 524, and raea cloud's gate sent its Client sign-off stop back as
"raea goal check couldn't run". Their headers now go at once, then an empty line ({}) every 30 s, which readers skip.

An ACP socket whose caller went away without closing it (an API restart, the Sprite's proxy keeping the box's half
open) kept its agent forever: two Gemini agents sat on raea-3 for 2 h, counted as running, so box.sh latest would wait
on them. An agent that has said nothing and been sent nothing for 45 min (RAEA_CLOUD_IDLE_AGENT_MS; raea cloud ends a
turn quiet 30 min) is now ended with its process group.

Checked locally (a 32 s silent command gets {} at 30 s; an idle echo agent's socket is closed at the limit) and on
raea-3 through its public URL's stack.

Co-authored-by: shinyobjectz <[email protected]>
2026-11-30 07:41:35 -08:00
39 changed files with 2269 additions and 90 deletions

No files matched your search

+249
View File
@@ -0,0 +1,249 @@
# Where a farm run's seconds go, and what each encoder costs and keeps (docs/cloud-render.feature CR27, CR31): the same
# frames of one project rendered on a GPU container sized as the farm's (farm_plan.RESERVED), once to PNGs (no video
# encoder: the picture every encode is scored against) and once through each encoder, timed. From sdk/cloud:
#
# MODAL_PROFILE=raea modal run bench/encode.py --dir ../../bench/rerender --args "render film.tsx --composition cut" --frames 0-299
# ... --encoders x264,soft,nvenc --out bench/results/encode-film.json
# ... --gpu none --cpu 8 --gib 8 the same on a container with no GPU (lavapipe), sized as said: what a piece
# with no 3D costs where nothing waits on a graphics card
#
# Each encoder's row: s (the run's wall time), ms a frame over the run, cores busy on average, the file's MB, SSIM and
# PSNR against the PNGs (all frames, and the darkest tenth of them alone, where an encoder's blocks show), what
# `raea check` says of its picture (the blotching line), raea's own RAEA_TIMES line, and the ffmpeg command raea ran.
# png raea's frames as PNGs: the reference, and a run with no video encoder
# x264 RAEA_MEDIA=ffmpeg: libx264 medium at the quality's CRF on the container's cores (the farm today)
# soft raea's own portable encoder (openh264 at a bitrate): the farm before 11-30
# nvenc RAEA_MEDIA=ffmpeg with h264_nvenc in libx264's place (constant QP at the CRF's number), on the run's own GPU
# An ephemeral app: it never touches the deployed farm.
import json
import os
import sys
import modal
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "deploy", "modal"))
import farm # noqa: E402 the farm's image, so the bench measures what the farm runs
import farm_plan # noqa: E402
app = modal.App("raea-farm-encode-bench", image=farm.image.add_local_python_source("farm"))
CPU, GIB = farm_plan.RESERVED["raea"]
# ffmpeg in the encoder's place: raea's ffmpeg backend names libx264 itself (io/ffmpeg), so the bench swaps the encoder
# where raea calls it. RAEA_BENCH_ENCODER holds the arguments that replace "-c:v libx264 -preset medium -crf N" ({q} is N)
WRAP = r"""#!/usr/bin/env python3
import json, os, sys
a = sys.argv[1:]
said = os.environ.get("RAEA_BENCH_SAID", "/dev/null")
with open(said, "a") as f:
f.write(" ".join(a) + "\n")
enc = json.loads(os.environ.get("RAEA_BENCH_ENCODER") or "null")
if enc and "libx264" in a and "rawvideo" in a:
i = a.index("-c:v")
if "-crf" in a:
j = a.index("-crf") + 2
new = enc["crf"].format(q=a[j - 1])
else:
j = a.index("-bufsize") + 2
new = enc["rate"].format(b=a[a.index("-b:v") + 1], m=a[a.index("-maxrate") + 1], u=a[j - 1])
a = a[:i] + new.split() + a[j:]
with open(said, "a") as f:
f.write("-> " + " ".join(a) + "\n")
os.execv("/usr/bin/ffmpeg", ["ffmpeg", *a])
"""
# what replaces "-c:v libx264 -preset medium" and its rate arguments where raea calls ffmpeg: "crf" when the render
# names a quality ({q} the CRF), "rate" when it doesn't ({b}, {m}, {u}: the bitrate, its ceiling and the buffer)
NV = "-c:v h264_nvenc -preset {p} -tune hq -bf 2 -g 60 -spatial-aq 1 -temporal-aq 1"
ENCODERS = {
"x264": {"RAEA_MEDIA": "ffmpeg"},
"soft": {"RAEA_MEDIA": "soft"},
"nvenc": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": NV.format(p="p5") + " -rc constqp -qp {q}", "rate": NV.format(p="p5") + " -rc vbr -b:v {b} -maxrate {m} -bufsize {u}"})},
"nvenc-p7": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": NV.format(p="p7") + " -rc constqp -qp {q}", "rate": NV.format(p="p7") + " -rc vbr -b:v {b} -maxrate {m} -bufsize {u}"})},
"x264-fast": {"RAEA_MEDIA": "ffmpeg", "RAEA_BENCH_ENCODER": json.dumps({"crf": "-c:v libx264 -preset veryfast -crf {q}", "rate": "-c:v libx264 -preset veryfast -b:v {b} -maxrate {m} -bufsize {u}"})},
}
def _sample(stop, rows):
"""What the container's processes are doing while a render runs: every 2 s, each process's name and CPU seconds so
far (ps), so a run's cores can be put to raea's threads or to the ffmpeg children it starts."""
import subprocess
import time
while not stop.is_set():
o = subprocess.run(["ps", "-eLo", "pid,comm,time,args", "--no-headers"], capture_output=True, text=True).stdout
rows.append((time.time(), o))
stop.wait(2)
def _run(cmd, cwd, env, timeout=3600):
import resource
import subprocess
import time
for d in (farm.CACHES["__GL_SHADER_DISK_CACHE_PATH"], farm.CACHES["XDG_CACHE_HOME"]):
os.makedirs(d, exist_ok=True)
u0, t = resource.getrusage(resource.RUSAGE_CHILDREN), time.time()
r = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, env={**os.environ, "HOME": "/tmp/home", **farm.CACHES, **env}, timeout=timeout)
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
return r.returncode, r.stdout + r.stderr, s, round((u1.ru_utime + u1.ru_stime - u0.ru_utime - u0.ru_stime) / max(s, 0.001), 2)
def _score(video, pngs, first, fps, dark):
"""SSIM and PSNR of `video` against the PNGs: over every frame, and over the darkest tenth (`dark`: frame indexes)."""
import re
import subprocess
def one(select):
vf = f"[0:v]{select}format=yuv420p[a];[1:v]{select}format=yuv420p[b];[a][b]ssim;[0:v]{select}format=yuv420p[c];[1:v]{select}format=yuv420p[d];[c][d]psnr"
r = subprocess.run(["ffmpeg", "-hide_banner", "-i", video, "-framerate", str(fps), "-start_number", str(first), "-i", f"{pngs}/frame-%05d.png", "-lavfi", vf, "-f", "null", "-"], capture_output=True, text=True)
s, p = re.search(r"SSIM .*All:([\d.]+)", r.stderr), re.search(r"PSNR .*average:([\d.inf]+)", r.stderr)
return (float(s.group(1)) if s else None, float(p.group(1)) if p and p.group(1) != "inf" else None)
out = dict(zip(("ssim", "psnr"), one("")))
if dark:
sel = "select='" + "+".join(f"eq(n\\,{i})" for i in dark) + "',"
out |= dict(zip(("ssim_dark", "psnr_dark"), one(sel)))
return out
@app.function(gpu="T4", cpu=CPU, memory=GIB * 1024, volumes={farm.ROOT: farm.vol, "/models": farm.models}, timeout=3600)
def measure(folder: bytes, args: list[str], first: int, last: int, encoders: list[str], check: bool = True, media: list | None = None, cpu_only: bool = False, size: tuple = (CPU, GIB), extra: dict | None = None, png: bool = True) -> dict:
import re
import shutil
import subprocess
import tarfile
import io
import farm_media
say = lambda *a: print(*a, flush=True)
# the job's folder on the volume, where the farm's own jobs are: a media link into the cache resolves there
work = f"{farm.JOBS}/bench-{os.environ.get('MODAL_TASK_ID', 'x')}/work"
shutil.rmtree(work, ignore_errors=True)
os.makedirs(work)
tarfile.open(fileobj=io.BytesIO(folder)).extractall(work)
if media:
with open(f"{work}/{farm_media.MANIFEST}", "w") as f:
json.dump({"objects": media}, f)
farm_media.fetch(work, f"{farm.ROOT}/blobs", say)
base = dict(farm.CPU_ENV) if cpu_only else {}
extra = extra or {}
os.makedirs("/tmp/bin", exist_ok=True)
with open("/tmp/bin/ffmpeg", "w") as f:
f.write(WRAP)
os.chmod("/tmp/bin/ffmpeg", 0o755)
path = "/tmp/bin:" + os.environ["PATH"]
at = ",".join(map(str, range(first, last + 1)))
n = last - first + 1
res = {"gpu": "" if cpu_only else farm.kind(), "cores": size[0], "gib": size[1], "raea": farm.RAEA, "frames": n, "args": args,
"has": subprocess.run("ffmpeg -hide_banner -encoders 2>/dev/null | grep -E '264|hevc|av1' | awk '{print $2}'", shell=True, capture_output=True, text=True).stdout.split(),
"nvidia": subprocess.run(["nvidia-smi", "--query-gpu=name,driver_version", "--format=csv,noheader"], capture_output=True, text=True).stdout.strip(), "rows": {}}
# a first run nobody times: the shader caches, the models, the page's fonts
code, out, s, _ = _run(["raea", *args, "--at", f"{first},{first + 1}", "-o", "/tmp/warm"], work, {**base, "PATH": path})
say(f"warm-up: exit {code} in {s:.1f} s", out[-300:] if code else "")
pngs = "/tmp/png"
shutil.rmtree(pngs, ignore_errors=True)
code, out, s, cores = _run(["raea", *args, "--at", at, "-o", pngs], work, {**base, "PATH": path, "RAEA_TIMES": "1"}) if png else (0, "", 0.0, 0.0)
say(f"png: exit {code}, {n} frames in {s:.1f} s, {cores} cores busy")
made = sorted(x for x in os.listdir(pngs) if x.endswith(".png")) if os.path.isdir(pngs) else []
for i, name in enumerate(made): # named by their frame, as the encodes' frames are counted
os.rename(f"{pngs}/{name}", f"{pngs}/t-{first + i:05d}.png")
for i in range(len(made)):
os.rename(f"{pngs}/t-{first + i:05d}.png", f"{pngs}/frame-{first + i:05d}.png")
fps = 30
m = re.search(r"(\d+(?:\.\d+)?) fps", out)
if made:
# each frame's pixels as a hash, and a few frames whole, to hold one container's picture against another's
md5 = subprocess.run(["ffmpeg", "-v", "error", "-framerate", str(fps), "-start_number", str(first), "-i", f"{pngs}/frame-%05d.png", "-pix_fmt", "rgba", "-f", "framemd5", "-"], capture_output=True, text=True).stdout
res["frame_md5"] = [l.split(",")[-1].strip() for l in md5.splitlines() if l and not l.startswith("#")]
res["frame_png"] = {str(first + i): open(f"{pngs}/frame-{first + i:05d}.png", "rb").read() for i in sorted({0, len(made) // 2, len(made) - 1})} if extra.get("BENCH_KEEP") else {}
res["rows"]["png"] = {"code": code, "s": round(s, 2), "ms": round(1000 * s / n, 1), "cores": cores, "frames": len(made), "times": [l for l in out.splitlines() if " ms" in l][-12:], "out": out[-600:] if code else ""}
# the darkest tenth of the frames, by mean luma
dark = []
if made:
import cv2
lum = [(float(cv2.imread(f"{pngs}/frame-{first + i:05d}.png", cv2.IMREAD_GRAYSCALE)[::8, ::8].mean()), i) for i in range(len(made))]
dark = sorted(i for _, i in sorted(lum)[: max(1, len(lum) // 10)])
res["dark_luma"] = round(sorted(lum)[len(dark) - 1][0], 1)
for name in encoders:
env = {**base, "PATH": path, "RAEA_TIMES": "1", "RAEA_STARTUP_TRACE": "1", **extra, "RAEA_BENCH_SAID": f"/tmp/{name}.said", **ENCODERS[name]}
video = f"/tmp/{name}.mp4"
for p in (video, env["RAEA_BENCH_SAID"]):
if os.path.exists(p):
os.remove(p)
import threading
stop, snaps = threading.Event(), []
th = threading.Thread(target=_sample, args=(stop, snaps), daemon=True)
if extra.get("BENCH_DIAG"):
th.start()
code, out, s, cores = _run(["raea", *args, "--at", at, "-o", video], work, env)
stop.set()
row = {"code": code, "s": round(s, 2), "ms": round(1000 * s / n, 1), "cores": cores, "said_ms": (re.search(r"([\d.]+) ms a frame", out) or [None, None])[1],
"times": [l for l in out.splitlines() if " ms" in l or "raea startup" in l][-40:], "out": out[-800:] if code else ""}
if os.path.exists(env["RAEA_BENCH_SAID"]):
calls = [l for l in open(env["RAEA_BENCH_SAID"]).read().splitlines() if not l.startswith("->")]
row["ffmpeg"] = [l for l in open(env["RAEA_BENCH_SAID"]).read().splitlines() if "rawvideo" in l][-2:]
row["ffmpeg_calls"] = len(calls)
row["ffmpeg_decodes"] = len([l for l in calls if " -ss " in f" {l} "])
row["ffmpeg_decode_sample"] = [l[:260] for l in calls if " -ss " in f" {l} "][:6]
if snaps:
# the middle snapshot's processes, and how many distinct ffmpeg pids were seen over the run
pids = {l.split()[0] for _, o in snaps for l in o.splitlines() if " ffmpeg" in l[:40]}
mid = snaps[len(snaps) // 2][1].splitlines()
row["ps_ffmpeg_pids"] = len(pids)
row["ps_mid"] = sorted({" ".join(l.split()[1:3]) + " " + " ".join(l.split()[3:])[:120] for l in mid if l.split()[2] != "00:00:00"})[:40]
if os.path.exists(video):
row["mb"] = round(os.path.getsize(video) / 1e6, 2)
pr = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,codec_name,profile,r_frame_rate", "-of", "csv=p=0", video], capture_output=True, text=True).stdout.strip()
row["probe"] = pr
if made:
row |= _score(video, pngs, first, fps, dark)
if check:
c, o, cs, _ = _run(["raea", "check", video], work, {"PATH": os.environ["PATH"]})
row["check"] = {"code": c, "s": round(cs, 1), "lines": [l.strip() for l in o.splitlines() if re.search(r"blotch|flash|freez|FAIL|PASS|passed|failed", l)][:12]}
res["rows"][name] = row
say(f"{name}: exit {code}, {s:.1f} s, {cores} cores busy, {row.get('mb')} MB, ssim {row.get('ssim')} dark {row.get('ssim_dark')}")
shutil.rmtree(os.path.dirname(work), ignore_errors=True)
return res
@app.local_entrypoint()
def main(dir: str, args: str, frames: str = "0-299", encoders: str = "x264,soft,nvenc", out: str = "", check: bool = True, gpu: str = "T4", cpu: int = CPU, gib: int = GIB, env: str = "", png: bool = True):
import hashlib
import io
import tarfile
a, _, b = frames.partition("-")
# files of 4 MB and more go by hash from the farm's cache, where a box's render put them (server/media.ts
# farmInputs); one the farm doesn't hold fails the run, which says so
media = []
def keep(i):
if i.name.startswith(("./out", "./.git", "./ios")):
return None
if i.isfile() and i.size >= 4 << 20:
h = hashlib.sha256()
with open(os.path.join(dir, i.name), "rb") as f:
for blk in iter(lambda: f.read(1 << 20), b""):
h.update(blk)
media.append({"path": i.name[2:], "oid": h.hexdigest(), "size": i.size})
return None
return i
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as t:
t.add(dir, arcname=".", filter=keep)
fn = measure.with_options(gpu=None if gpu == "none" else gpu, cpu=cpu, memory=gib * 1024)
r = fn.remote(buf.getvalue(), args.split(), int(a), int(b or a), [e for e in encoders.split(",") if e], check, media, gpu == "none", (cpu, gib), dict(kv.split("=", 1) for kv in env.split(",") if kv), png)
for n, b in (r.pop("frame_png", None) or {}).items():
if out:
with open(f"{os.path.splitext(out)[0]}-{int(n):05d}.png", "wb") as f:
f.write(b)
print(json.dumps({**r, "frame_md5": len(r.get("frame_md5") or [])}, indent=2))
if out:
with open(out, "w") as f:
json.dump(r, f, indent=2)
+130
View File
@@ -0,0 +1,130 @@
// One farm job, measured (docs/cloud-render.feature CR27): a folder sent the way a CPU box sends one, its log timed
// from the submit, and what the farm said about it read back as numbers. RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN
// name the farm (~/.config/raea-cloud/farm.env), so the same job runs on the live farm and on a test deploy of it:
//
// node bench/job.ts DIR OUT.json [--gpus N] [--keep FILE] -- render film.tsx --composition cut -o out/film.mp4
//
// OUT.json: wall (s from the submit to the video here, on disk), sent and back (bytes), frames, w, h, frame_ms and
// start_s (the farm's timed first run), runs ([{frames, kind, s}]), join_s, billed_usd, up_s (its containers' life
// in all), cores and peak_gb (the busiest run's), first_s (when the first run of frames had landed), exit.
import { spawn, spawnSync } from "node:child_process"
import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { RaeaCloud } from "../src/index.ts"
/** What a farm job's log says, as numbers: `lines` are [seconds from the submit, the line]. */
export function read(lines: [number, string][]) {
const o: Record<string, unknown> = { runs: [] as { frames: number; kind: string; s: number; at: number }[] }
const num = (s: string) => Number(s)
for (const [at, l] of lines) {
let m: RegExpMatchArray | null
if ((m = l.match(/(\d+) frames at (\d+)x(\d+), ([\d.]+) fps; frame 0 on a (\S+) in ([\d.]+) s/))) Object.assign(o, { frames: num(m[1]), w: num(m[2]), h: num(m[3]), fps: num(m[4]), kind: m[5], probe_s: num(m[6]) })
else if ((m = l.match(/([\d.]+) ms a frame, ([\d.]+) s to start; (\d+) frames left on (\d+) (\S+?)s?(?: with no GPU \(no 3D in it\))?(?: in (\d+) parts)?, about \$([\d.]+)/))) Object.assign(o, { frame_ms: num(m[1]), start_s: num(m[2]), gpus: num(m[4]), parts: num(m[6] ?? m[4]), estimate_usd: num(m[7]) })
else if ((m = l.match(/(\d+) frames on a (\S+) in ([\d.]+) s/))) (o.runs as object[]).push({ frames: num(m[1]), kind: m[2], s: num(m[3]), at })
else if ((m = l.match(/joined .* in ([\d.]+) s/))) Object.assign(o, { join_s: num(m[1]), joined_at: at })
else if ((m = l.match(/billed about \$([\d.]+): (\d+) GPU(?: and (\d+) CPU)? containers up ([\d.]+) s in all(?:; at most ([\d.]+) of (\d+) cores busy and ([\d.]+) of (\d+) GB)?/)))
Object.assign(o, { billed_usd: num(m[1]), containers: num(m[2]), cpu_containers: m[3] ? num(m[3]) : 0, up_s: num(m[4]), cores: m[5] ? num(m[5]) : undefined, reserved_cores: m[6] ? num(m[6]) : undefined, peak_gb: m[7] ? num(m[7]) : undefined, reserved_gb: m[8] ? num(m[8]) : undefined })
else if ((m = l.match(/(\d+) runs kept from an earlier render hold (\d+) of (\d+) frames/))) Object.assign(o, { kept_runs: num(m[1]), kept_frames: num(m[2]) })
else if (l.includes("nothing to draw: every frame is in a run kept")) o.all_kept = true
else if ((m = l.match(/its frames' keys read in ([\d.]+) s/))) Object.assign(o, { keys_s: num(m[1]) })
else if ((m = l.match(/first picture at (\S+)/))) Object.assign(o, { first_picture: m[1], first_picture_at: at })
}
const runs = o.runs as { at: number }[]
if (runs.length) o.first_s = runs[0].at
return o
}
/** The job as a box sends it: server/offload.ts in DIR (its media by hash through the farm's cache, the manifest it
* asks for), the box's own check after it left out. Resolves with the timed lines and the exit code. */
function offload(dir: string, args: string[], gpus: string | undefined, cpus: string | undefined, kept: string | undefined, said: (at: number, l: string) => void): Promise<number> {
const here = path.dirname(new URL(import.meta.url).pathname)
const t0 = performance.now()
const env = { ...process.env, RAEA_REAL: "/usr/bin/true", ...(gpus ? { RAEA_CLOUD_GPUS: gpus } : {}), ...(cpus ? { RAEA_CLOUD_CPUS: cpus } : {}), ...(kept === "0" ? { RAEA_CLOUD_KEPT: "0" } : {}) }
const child = spawn(process.execPath, [path.join(here, "..", "server", "offload.ts"), ...args], { cwd: dir, env, stdio: ["ignore", "pipe", "pipe"] })
let rest = ""
const eat = (b: Buffer) => {
const parts = (rest + b.toString()).split("\n")
rest = parts.pop() ?? ""
for (const l of parts) if (l.trim()) said((performance.now() - t0) / 1000, l)
}
child.stdout.on("data", eat)
child.stderr.on("data", eat)
return new Promise((done) => child.on("close", (code) => done(code ?? 1)))
}
async function main() {
const argv = process.argv.slice(2)
const cut = argv.indexOf("--")
if (cut < 2) throw new Error("usage: node bench/job.ts DIR OUT.json [--gpus N] [--cpus N] [--kept 0] [--keep FILE] [--offload] -- ARGS")
const [dir, outJson, ...flags] = argv.slice(0, cut)
const args = argv.slice(cut + 1)
const flag = (n: string) => (flags.includes(n) ? flags[flags.indexOf(n) + 1] : undefined)
const url = process.env.RAEA_CLOUD_GPU_URL
const token = process.env.RAEA_CLOUD_GPU_TOKEN
if (!url || !token) throw new Error("set RAEA_CLOUD_GPU_URL and RAEA_CLOUD_GPU_TOKEN (the farm's)")
if (flags.includes("--offload")) {
const lines: [number, string][] = []
const t0 = performance.now()
const exit = await offload(dir, args, flag("--gpus"), flag("--cpus"), flag("--kept"), (at, l) => {
lines.push([at, l])
console.log(`${at.toFixed(1).padStart(6)} s ${l}`)
})
const wall = (performance.now() - t0) / 1000
const o = args.indexOf("-o")
const video = o >= 0 ? path.resolve(dir, args[o + 1]) : ""
const size = video && existsSync(video) ? statSync(video).size : 0
const sentMb = lines.map(([, l]) => l.match(/\(([\d.]+) MB\) sent/)).find(Boolean)
const res = { args, farm: new URL(url).host, via: "offload", exit, wall: Number(wall.toFixed(1)), sent: sentMb ? Math.round(Number(sentMb[1]) * 1e6) : undefined, ...read(lines), bytes: size, log: lines.map(([t, l]) => `${t.toFixed(1)} ${l}`) }
writeFileSync(outJson, JSON.stringify(res, null, 2))
console.log(`${wall.toFixed(1).padStart(6)} s exit ${exit}; ${JSON.stringify({ ...res, log: undefined, args: undefined })}`)
const keep = flag("--keep")
if (keep && size) spawnSync("cp", [video, keep])
process.exitCode = exit
return
}
const tmp = mkdtempSync(path.join(os.tmpdir(), "raea-farm-bench-"))
try {
const sent = path.join(tmp, "in.tgz")
const pack = spawnSync("tar", ["-czf", sent, "--no-mac-metadata", "--exclude=./out", "--exclude=./.git", "-C", dir, "."], { env: { ...process.env, COPYFILE_DISABLE: "1" }, encoding: "utf8" })
if (pack.status) throw new Error(`the folder didn't pack: ${pack.stderr}`)
const folder = new Uint8Array(readFileSync(sent))
const cloud = new RaeaCloud({ url, token })
const t0 = performance.now()
const now = () => (performance.now() - t0) / 1000
const lines: [number, string][] = []
console.log(`${now().toFixed(1).padStart(6)} s ${(folder.length / 1e6).toFixed(2)} MB to ${new URL(url).host}: raea ${args.join(" ")}`)
const gpus = flag("--gpus")
const { exit, files } = await cloud.job(args, folder, {
as: "gz",
farm: { ...(gpus ? { gpus: Number(gpus) } : {}), ...(flag("--cpus") ? { cpus: Number(flag("--cpus")) } : {}) },
onOutput: (t) =>
t.split("\n").filter(Boolean).forEach((l) => {
lines.push([now(), l])
console.log(`${now().toFixed(1).padStart(6)} s ${l}`)
}),
})
const back = path.join(tmp, "out.tgz")
writeFileSync(back, files)
spawnSync("tar", ["-xzf", back, "-C", tmp])
const wall = now()
const o = args.indexOf("-o")
const video = o >= 0 ? path.join(tmp, args[o + 1]) : ""
const probe = video ? spawnSync("ffprobe", ["-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,width,height:format=size", "-of", "json", video], { encoding: "utf8" }) : null
let got: Record<string, unknown> = {}
try {
const j = JSON.parse(probe?.stdout || "{}")
got = { got_frames: Number(j.streams?.[0]?.nb_read_frames), got_w: j.streams?.[0]?.width, got_h: j.streams?.[0]?.height, bytes: Number(j.format?.size) }
} catch {}
const res = { args, farm: new URL(url).host, exit, wall: Number(wall.toFixed(1)), sent: folder.length, back: files.length, ...read(lines), ...got, log: lines.map(([t, l]) => `${t.toFixed(1)} ${l}`) }
writeFileSync(outJson, JSON.stringify(res, null, 2))
console.log(`${wall.toFixed(1).padStart(6)} s exit ${exit}; ${JSON.stringify({ ...res, log: undefined, args: undefined })}`)
const keep = flag("--keep")
if (keep && video) spawnSync("cp", [video, keep])
process.exitCode = exit
} finally {
rmSync(tmp, { recursive: true, force: true })
}
}
if (process.argv[1] && path.resolve(process.argv[1]) === new URL(import.meta.url).pathname) await main()
+98
View File
@@ -0,0 +1,98 @@
# A Linux raea built on Modal from a source folder, into the farm's volume (/farm/builds/NAME): how an engine change is
# measured on a test farm before a release carries it (docs/cloud-render.feature CR28). The farm's image installs the
# released raea, so without this an engine change couldn't be timed there at all. A test farm deployed with
# RAEA_FARM_BUILD=NAME runs this build's raea, with the released one's own files (share/raea) as its home:
#
# git archive TAG | tar -x -C SRC # the release's source; put the change's files over it
# MODAL_PROFILE=raea modal run deploy/modal/build.py --src SRC --name NAME
# RAEA_FARM_APP=raea-farm-m RAEA_FARM_BUILD=NAME modal deploy deploy/modal/farm.py
#
# The source's file times are kept (git archive gives every file its commit's), and cargo's registry, target folder
# and source are kept as one tar each on a volume of their own and unpacked onto the container's disk, so a second
# build compiles only the crates whose files changed. (Left as folders on the volume, cargo read the crates index one
# file at a time, about 4 a second: 13 min before it compiled anything, 11-30.)
import io
import os
import subprocess
import tarfile
import time
import modal
RUST = "1.99.1" # rust-toolchain.toml's
# release.yml's "Linux libraries", and what cargo's build scripts call
LIBS = ["build-essential", "pkg-config", "cmake", "ninja-build", "nasm", "clang", "git", "curl", "ca-certificates", "python3",
"libxkbcommon-dev", "libxkbcommon-x11-dev", "libasound2-dev", "libfontconfig1-dev", "libvulkan-dev", "libudev-dev", "libssl-dev"]
image = (
# the farm image's Debian, so the build links against the libraries it runs with
modal.Image.from_registry("debian:trixie-slim", add_python="3.12")
.apt_install(*LIBS)
.run_commands(f"curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain {RUST}")
.env({"PATH": "/root/.cargo/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "CARGO_HOME": "/work/cargo", "CARGO_TARGET_DIR": "/work/target",
"RUSTUP_HOME": "/root/.rustup",
# no debug info: the farm's copy was stripped anyway (2.8 GB with it), and the link is far shorter
"CARGO_PROFILE_DIST_DEBUG": "0"})
)
KEPT = ("cargo", "target", "src")
app = modal.App("raea-farm-build", image=image)
farm = modal.Volume.from_name("raea-farm", create_if_missing=True, version=2)
cache = modal.Volume.from_name("raea-build", create_if_missing=True, version=2)
# (the target folder on the container's own disk, not the volume; Modal's smallest disk request is 512 GiB, so the default)
@app.function(cpu=32, memory=64 * 1024, timeout=4 * 3600, volumes={"/farm": farm, "/cache": cache})
def build(src: bytes, name: str, features: str) -> dict:
t = time.time()
os.makedirs("/work/src", exist_ok=True)
for d in KEPT:
if os.path.exists(f"/cache/{d}.tar"):
subprocess.run(["tar", "-xf", f"/cache/{d}.tar", "-C", "/work"], check=True)
print(f"build: the last build's folders unpacked in {time.time() - t:.0f} s", flush=True)
# over the last build's source, in place: an unchanged file keeps its time, so its crate isn't compiled again
with tarfile.open(fileobj=io.BytesIO(src), mode="r:gz") as tar:
tar.extractall("/work/src", filter="tar")
cmd = ["cargo", "build", "--profile", "dist", "--locked", "-p", "raea-cli", "--bin", "raea", "--no-default-features", "--features", features]
print("build:", " ".join(cmd), flush=True)
code = subprocess.run(cmd, cwd="/work/src").returncode
out = f"/farm/builds/{name}"
made = {}
if not code:
os.makedirs(out, exist_ok=True)
for f in ("raea", "libraea_bundle.so"):
p = f"/work/target/dist/{f}"
# without its debug info, as the release's is (2.8 GB with it, read from the volume at every container's start)
subprocess.run(["strip", "--strip-debug", "-o", f"{out}/{f}", p], check=True)
made[f] = os.path.getsize(f"{out}/{f}")
said = subprocess.run([f"{out}/raea", "--version"], capture_output=True, text=True, env={**os.environ, "RAEA_HOME": "/nonexistent"})
made["version"] = (said.stdout + said.stderr).strip()[-200:]
farm.commit()
for d in KEPT:
subprocess.run(["tar", "-cf", f"/cache/{d}.tar.part", "-C", "/work", d], check=True)
os.replace(f"/cache/{d}.tar.part", f"/cache/{d}.tar")
cache.commit()
return {"code": code, "s": round(time.time() - t), "out": out, **made}
@app.function(cpu=2, memory=8 * 1024, timeout=1800, volumes={"/farm": farm})
def slim(name: str) -> dict:
"""A build already in the volume, without its debug info."""
out = {}
for f in ("raea", "libraea_bundle.so"):
p = f"/farm/builds/{name}/{f}"
subprocess.run(["strip", "--strip-debug", p], check=True)
out[f] = os.path.getsize(p)
farm.commit()
return out
@app.local_entrypoint()
def main(src: str, name: str, features: str = ""):
if not features:
features = subprocess.run(["bash", "tools/bevy-plugins.sh", "features", "sdk/raea/bench/bevy-plugins"], cwd=src, capture_output=True, text=True).stdout.strip().splitlines()[-1]
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz", compresslevel=3) as tar:
tar.add(src, arcname=".")
print(f"build: {len(buf.getvalue()) / 1e6:.0f} MB of source, features {features}")
print(build.remote(buf.getvalue(), name, features))
+105 -15
View File
@@ -76,6 +76,13 @@ BLENDER = os.environ.get("RAEA_FARM_BLENDER", "5.3.0")
RAEA_GPUS = os.environ.get("RAEA_FARM_RAEA_GPUS", "T4,A10,L4").split(",")
BLENDER_GPUS = os.environ.get("RAEA_FARM_BLENDER_GPUS", "L40S,RTX-PRO-6000,L4").split(",")
GPUS = int(os.environ.get("RAEA_FARM_GPUS", "10")) # Modal Starter's GPU limit; Team's is 50
# one job's GPUs unless it asks for more: a 1,150-frame cut took all 10 (each drawing 10-20 s), so every other render in
# the workspace queued behind it with nothing said (11-30, StreetTalk's three agents); 4 lets two or three render at once
JOB_GPUS = int(os.environ.get("RAEA_FARM_JOB_GPUS", "4"))
# the containers with no GPU a job's video with no 3D is drawn on at once (raea_cpu_run), and the farm's in all: no
# workspace limit holds these back as it does GPUs
JOB_CPUS = int(os.environ.get("RAEA_FARM_JOB_CPUS", "8"))
CPUS = int(os.environ.get("RAEA_FARM_CPUS", "40"))
ROOT = "/farm"
JOBS = f"{ROOT}/jobs"
@@ -117,6 +124,9 @@ image = (
"c5c2d13e59ae883e6af3b45daea64af4833a4951c92d116ec270d9ddbe998063 /opt/yolox_s.onnx "
"03f550c6b406fda8bf54bd8327815f6c7e2edd98cea02348c93d879254366587 /opt/ppocr_det.onnx | sha256sum -c"
)
# /v1/scene's texts (11-30): RapidOCR's PP-OCRv4 reads each line of text in a frame, for raea goal check's captions
# pack (what an export shows, held to what it says). Apache-2.0; its ONNX models ship in the wheel
.pip_install("rapidocr_onnxruntime==1.4.4")
.add_local_file(os.path.join(CLOUD, "image", "nvidia_icd.json"), "/usr/share/vulkan/icd.d/nvidia_icd.json", copy=True)
# RAEA_GOAL_RENDER 0: a render here ends without raea goal check's render moment, which the box that sent it runs
# on the export it gets back (server/offload.ts), beside the project's brief.ts
@@ -127,8 +137,15 @@ image = (
# the job at once instead of installing it on a GPU's clock
"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", "farm_scene")
"RAEA_SAO": "/models/sao",
# a video's runs encoded by the ffmpeg CLI's libx264 at the quality's CRF (master 11), not openh264 at a
# bitrate: openh264's near-blacks stepped into blocks even at master's 37.7 Mbps, raea check's blotching
# failed every Dutch cut, and its agent re-encoded each one with x264 after the render (11-30)
"RAEA_MEDIA": "ffmpeg"})
# a test farm's own raea (deploy/modal/build.py: an engine change built into the volume, timed here before a release
# carries it): RAEA_FARM_BUILD=NAME at the deploy. The live farm has none, and runs the release above
.env({"RAEA_FARM_BUILD": os.environ.get("RAEA_FARM_BUILD", "")})
.add_local_python_source("farm_plan", "farm_media", "prices", "farm_scene", "farm_keys", "farm_proxy")
)
app = modal.App(os.environ.get("RAEA_FARM_APP", "raea-farm"), image=image)
@@ -170,6 +187,10 @@ 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)
build = os.environ.get("RAEA_FARM_BUILD")
if build and cmd[0] == "raea":
# the build's raea, with the release's own files as its home
cmd, env = [f"{ROOT}/builds/{build}/raea", *cmd[1:]], {"RAEA_HOME": "/opt/raea/share/raea", **(env or {})}
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)
u1, s = resource.getrusage(resource.RUSAGE_CHILDREN), time.time() - t
@@ -220,24 +241,85 @@ def on(gpus, 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 reserved(job):
import sys
if HERE not in sys.path:
sys.path.insert(0, HERE)
import farm_plan
return farm_plan.RESERVED[job]
farm_cpu = reserved("cpu")
def raea_path():
"""The raea a job runs: a test farm's build (RAEA_FARM_BUILD), else the release in the image"""
build = os.environ.get("RAEA_FARM_BUILD")
return f"{ROOT}/builds/{build}/raea" if build else shutil.which("raea") or "/usr/local/bin/raea"
def kind():
"""This container's GPU by its price list name (prices.py), for the planner's estimate."""
"""This container's GPU by its price list name (prices.py), for the planner's estimate; "CPU" with none."""
import prices
name = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True).stdout
try:
name = subprocess.run(["nvidia-smi", "--query-gpu=name", "--format=csv,noheader"], capture_output=True, text=True).stdout
except FileNotFoundError:
return "CPU"
# a GPU whose name isn't in the price list is still a GPU ("", which the planner prices as its fallback GPU): 11-30,
# `or "CPU"` here priced one of a GPU job's containers as a CPU's
return prices.kind_of(name)
def work_ms(out):
"""What raea's own clocks (RAEA_TIMES) say a run's frames took in all, ms: React, the page recorded and collected,
and raea-render's pass (the clips read, the draw, the encode). None when the run didn't say."""
a = re.search(r"raea times: react (\d+) ms, page recorded and submitted (\d+) ms, page collected and stored (\d+) ms", out)
b = re.search(r"raea times: raea-render's render[^\n]*? (\d+) ms", out)
return sum(map(int, a.groups())) + int(b.group(1)) if a and b else None
@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:
def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: 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.
With `probe`: frame 0 and the piece's length, size and rate (its manifest). One function for all three, so the
container that rendered frame 0 is warm for the next run."""
container that rendered frame 0 is warm for the next run. With `nv` (a piece with 3D in it, which keeps its GPU):
NVIDIA's encoder and decoder in place of libx264 and ffmpeg's own (RAEA_NV, CR34)."""
return raea_frames(id, args, frames, first, probe, video, {"RAEA_NV": "1"} if nv else None)
@app.function(cpu=farm_cpu[0], memory=farm_cpu[1] * 1024, volumes={ROOT: vol, "/models": models}, timeout=6 * 3600, max_containers=CPUS, scaledown_window=SCALEDOWN)
def raea_cpu_run(id: str, args: list[str], frames: list[int] | None = None, first: int = 0, probe: bool = False, video: bool = False, nv: bool = False) -> dict:
"""raea_run on a container with no GPU (lavapipe draws), for a video with no 3D in it: the planner sends those
here after frame 0 (farm_plan.raea_render), and a run that fails here or has 3D in it goes back to a GPU."""
return raea_frames(id, args, frames, first, probe, video, CPU_ENV)
@app.function(cpu=8, memory=8 * 1024, volumes={ROOT: vol}, timeout=3600, max_containers=CPUS, scaledown_window=SCALEDOWN)
def raea_proxy(src: str, dest: str, w: int, h: int, matrix: str) -> dict:
"""One clip's copy at the size a job draws it (farm_proxy.py), written beside the others and kept by hash"""
import farm_proxy
vol.reload()
os.makedirs(os.path.dirname(dest), exist_ok=True)
part = f"{dest}.part-{uuid.uuid4().hex[:8]}{os.path.splitext(dest)[1]}"
code, out, s = run(farm_proxy.command(src, part, w, h, matrix))
if not code:
os.replace(part, dest)
vol.commit()
elif os.path.exists(part):
os.remove(part)
return {"code": code, "out": out[-1000:], "s": s}
def raea_frames(id, args, frames=None, first=0, probe=False, video=False, env=None):
vol.reload()
work = f"{JOBS}/{id}/work"
if probe:
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work)
code, out, s = run(["raea", *args, "--frame", "0", "-o", "/tmp/probe.png", "--manifest", "/tmp/probe.json"], cwd=work, env=env)
m = json.load(open("/tmp/probe.json")) if os.path.exists("/tmp/probe.json") else {}
return {"code": code, "out": out[-3000:], "s": s, "length": m.get("length"), "fps": m.get("fps"), "w": m.get("width"), "h": m.get("height"), "kind": kind(), "manifest": m, **life()}
if frames is None:
@@ -252,7 +334,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
# 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)
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", seg, "--manifest", man], cwd=work, env={**(env or {}), "RAEA_TIMES": "1"})
if os.path.exists(seg):
shutil.move(seg, f"{dest}/run-{first:05d}.mp4")
vol.commit()
@@ -261,9 +343,9 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
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()}
return {"code": code, "out": out[-2000:], "s": s, "frames": len(frames), "first": first, "ms": float(ms.group(1)) if ms else None, "work_ms": work_ms(out), "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)
code, out, s = run(["raea", *args, "--at", ",".join(map(str, frames)), "-o", tmp], cwd=work, env=env)
# raea names --at's stills in order (frame-00000.png is the first frame asked for), beside its manifest
made = sorted(n for n in os.listdir(tmp) if re.fullmatch(r"frame-\d+\.png", n)) if os.path.isdir(tmp) else []
# a frame's time from when the stills were written (raea's stills path doesn't say it), the start excluded
@@ -274,7 +356,7 @@ def raea_run(id: str, args: list[str], frames: list[int] | None = None, first: i
if frames[i] >= first:
shutil.move(os.path.join(tmp, name), f"{dest}/frame-{frames[i]:05d}.png")
vol.commit()
return {"code": code, "out": out[-2000:], "s": s, "frames": len(made), "ms": ms, "kind": kind(), **life()}
return {"code": code, "out": out[-2000:], "s": s, "frames": len(made), "first": first, "ms": ms, "kind": kind(), **life()}
BLENDER_SETUP = """
@@ -341,7 +423,14 @@ def coordinate(id: str, args: list[str], opts: dict):
vol.commit()
before = snapshot(work)
try:
code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload)
# a video's frames' keys (farm_keys.py): its runs kept by them under the raea that drew them (a release's
# version and the build's own file, so a new engine starts a store of its own; kept=0 draws every frame), and
# its clips read from copies at the size they're drawn (farm_proxy.py, made on containers with no GPU)
exe = os.path.realpath(raea_path())
st = os.stat(exe)
opts = {**opts, "keys": f"{ROOT}/kept", "raea": f"{exe}:{st.st_size}:{int(st.st_mtime)}", "proxies": f"{ROOT}/proxies", "proxy_commit": vol.commit,
"proxy_make": lambda todo: raea_proxy.starmap(todo, order_outputs=False, return_exceptions=True)}
code = farm_plan.dispatch(args, {**opts, "id": id}, work, log, raea_run, blender_run, CPU_ENV, run, vol.reload, raea_cpu_run if opts.get("cpus") else None)
except Exception as e: # the job's own failure, said in its log; the farm goes on
log(f"raea farm: {e!r}", err=True)
code = 1
@@ -478,7 +567,8 @@ def api():
"""what's in a video's frames, for raea goal check's frames and place packs and `raea make 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
(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"""
(COCO's, and words in the shot as "text") as [x, y, w, h, label, score], and each line of text read as texts
[x, y, w, h, "the text", score], in that frame's pixels"""
import base64
import cv2
import numpy as np
@@ -503,7 +593,7 @@ def api():
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}
return {"model": "pphumanseg-2023mar+yolox-s-2022nov+ppocrv3-db-2023may+yunet-2023mar+rapidocr-ppocrv4", "frames": out}
@web.post("/v1/words")
async def words(req: Request):
@@ -546,7 +636,7 @@ def api():
if not isinstance(args, list) or not all(isinstance(a, str) for a in args):
raise HTTPException(400, "args must be a JSON array of strings: raea's own arguments")
q = req.query_params
opts = {"gpus": min(int(q.get("gpus", GPUS)), GPUS), "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
opts = {"gpus": min(int(q.get("gpus", JOB_GPUS)), GPUS), "cpus": min(int(q.get("cpus", JOB_CPUS)), CPUS), "kept": q.get("kept", "1") != "0", "gpu": q.get("gpu"), "max_usd": float(q["max_usd"]) if "max_usd" in q else None, "media": q.get("media") == "1"}
id = str(uuid.uuid4())
work = f"{JOBS}/{id}/work"
async with gate.use():
+148
View File
@@ -0,0 +1,148 @@
# A video's runs kept by what their frames draw (docs/cloud-render.feature CR30): `raea render --keys` says each frame's
# key with nothing drawn, and a run a job drew is kept on the farm's volume under its frames' keys. The next job of the
# piece draws only the frames no kept run holds: a caption edited in one shot draws that shot's runs again, a change
# to the sound alone draws none (the sound is made again and joined to the kept pictures).
#
# read(...) the piece's keys, read on the coordinator's CPU: None when this raea has no --keys
# base(...) what a kept run is only good under: the raea that drew it, the render's arguments, the
# picture's size and rate, and every file in the job that isn't sound, by its content
# cover(store, keys) (hits, gaps): the kept runs whose frames' keys are the piece's at the same frames, and
# the stretches of frames left to draw
# put(store, keys, ...) a run just drawn, kept
#
# A key names files, it doesn't read them, and a frame's picture hangs on the page's styles and the engine too: all of
# that is in `base`, so a changed clip, font, stylesheet or raea starts a store of its own. Pieces with 3D in them
# aren't kept (a frame's picture can hang on the frames before it: physics, particles, a path tracer's light).
import hashlib
import json
import os
import re
import shutil
import time
SOUND = set("mp3 wav aiff aif flac m4a ogg opus caf".split())
# the piece's code (the keys hold what of it reaches the picture), and what a job leaves behind. A .json the code
# imports is code too (a caption's words reach the page as text); one it doesn't is a file something may read by path
CODE = set("tsx ts jsx js mjs".split())
SKIP = CODE | set("md lock log".split())
IMPORT = re.compile(r"""(?:from|import|require\()\s*["']([^"']+\.json)["']""")
KEEP_DAYS = 14
NAME = re.compile(r"(\d+)-(\d+)-([0-9a-f]{32})\.mp4")
def read(args, work, run, env, path):
"""{length, width, height, fps, has3d, keys, sounds} and the seconds it took, or (None, s) when raea didn't say"""
code, _, s = run(["raea", *args, "--keys", path, "-o", "/tmp/keys.mp4"], cwd=work, env=env)
try:
k = json.load(open(path)) if not code else None
except Exception:
k = None
return (k if k and len(k.get("keys") or []) == k.get("length") else None), s
def files(work):
"""Every file of the job a picture could hang on that the keys don't hold, as [path, content]: a link into the
farm's cache by the hash it's named for, anything else by its own."""
out, seen, imported = [], [], set()
for dirpath, dirs, names in os.walk(work):
dirs[:] = [d for d in dirs if d not in ("out", "node_modules", ".git", ".raea")]
for n in names:
p = os.path.join(dirpath, n)
ext = n.rsplit(".", 1)[-1].lower() if "." in n else ""
if ext in CODE and os.path.isfile(p):
with open(p, errors="replace") as f:
imported |= {os.path.normpath(os.path.join(dirpath, m)) for m in IMPORT.findall(f.read())}
seen.append((p, ext))
for p, ext in seen:
if True:
if ext in SOUND or ext in SKIP or not os.path.isfile(p) or (ext == "json" and os.path.normpath(p) in imported):
continue
real = os.path.realpath(p)
oid = os.path.basename(real)
if not (os.path.islink(p) and len(oid) == 64):
h = hashlib.sha256()
with open(p, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""):
h.update(b)
oid = h.hexdigest()
out.append([os.path.relpath(p, work), oid])
return sorted(out)
def base(raea, args, k, work):
said = json.dumps([raea, args, k["width"], k["height"], k["fps"], k["length"], files(work)])
return hashlib.sha256(said.encode()).hexdigest()[:32]
def of(keys, first, n):
return hashlib.sha256("\n".join(keys[first : first + n]).encode()).hexdigest()[:32]
def cover(store, keys):
"""The kept runs that hold this piece's frames, longest first where two overlap, and the frames left."""
kept = []
for name in os.listdir(store) if os.path.isdir(store) else []:
m = NAME.fullmatch(name)
if m and int(m[1]) + int(m[2]) <= len(keys) and of(keys, int(m[1]), int(m[2])) == m[3]:
kept.append((int(m[1]), int(m[2]), os.path.join(store, name)))
hits, taken = [], [False] * len(keys)
for first, n, path in sorted(kept, key=lambda r: (-r[1], r[0])):
if not any(taken[first : first + n]):
taken[first : first + n] = [True] * n
hits.append((first, n, path))
gaps, f = [], 0
while f < len(keys):
if taken[f]:
f += 1
continue
e = f
while e + 1 < len(keys) and not taken[e + 1]:
e += 1
gaps.append((f, e))
f = e + 1
return sorted(hits), gaps
def take(hits, frames_dir):
"""The kept runs into the job's frames, as its own runs lie there; each one's manifest, as a run's result"""
os.makedirs(frames_dir, exist_ok=True)
got = []
for first, n, path in hits:
shutil.copyfile(path, f"{frames_dir}/run-{first:05d}.mp4")
os.utime(path)
try:
m = json.load(open(path[:-4] + ".json"))
except Exception:
m = None
got.append({"code": 0, "first": first, "frames": n, "manifest": m, "kept": True})
return got
def put(store, keys, results, frames_dir):
"""The runs a job drew, kept under their frames' keys; stores no job has touched in KEEP_DAYS go."""
os.makedirs(store, exist_ok=True)
for r in results:
src = f"{frames_dir}/run-{r.get('first', 0):05d}.mp4"
if r.get("code") or r.get("kept") or not r.get("frames") or not os.path.exists(src):
continue
to = f"{store}/{r['first']}-{r['frames']}-{of(keys, r['first'], r['frames'])}"
shutil.copyfile(src, to + ".part")
os.replace(to + ".part", to + ".mp4")
with open(to + ".json", "w") as f:
json.dump(r.get("manifest"), f)
os.utime(store)
root, old = os.path.dirname(store), time.time() - KEEP_DAYS * 86400
for d in os.listdir(root):
p = os.path.join(root, d)
if p != store and os.path.isdir(p) and os.stat(p).st_mtime < old:
shutil.rmtree(p, ignore_errors=True)
def spans(gaps, n0, parts):
"""The frames left after the timed run's first n0 (of the first gap), as (first, last) stretches, and each one's
share of `parts` runs by its length (one at least)."""
rest = [(a + (n0 if i == 0 else 0), b) for i, (a, b) in enumerate(gaps)]
rest = [(a, b) for a, b in rest if a <= b]
left = sum(b - a + 1 for a, b in rest)
return [(a, b, max(1, round(parts * (b - a + 1) / left))) for a, b in rest]
+206 -47
View File
@@ -8,6 +8,9 @@ import os
import re
import shutil
import threading
import farm_keys
import farm_proxy
import time
import prices
@@ -44,6 +47,34 @@ def splittable(args):
return out is not None and (out.endswith(VIDEO) or not os.path.splitext(out)[1]) and any(COMPOSITION.search(a) for a in rest[1:])
# how often a job's log says it's still waiting on a GPU run: from outside, a run queued behind the workspace's GPU
# limit and one still drawing look the same, and a silent wait read as a stall (11-30: StreetTalk's agents said "stalled
# before frame 0" while another app held all 10 of the workspace's GPUs)
WAIT_SAY_S = 30
def waited(fn, log, *a, **kw):
"""fn.remote(*a, **kw), saying in the log every WAIT_SAY_S that it has no answer yet."""
if not hasattr(fn, "spawn"):
return fn.remote(*a, **kw)
try:
import modal.exception as me
timeouts = (TimeoutError, me.TimeoutError)
except Exception:
timeouts = (TimeoutError,)
call = fn.spawn(*a, **kw)
t = time.time()
while True:
try:
return call.get(timeout=WAIT_SAY_S)
except timeouts as e:
# Modal's FunctionTimeoutError is a TimeoutError too: the run itself ran out of time, so it goes up as
# .remote() raised it, not waited on again (it would answer the same at once, forever)
if type(e).__name__ == "FunctionTimeoutError":
raise
log(f"raea farm: waiting {time.time() - t:.0f} s for a GPU run to answer (queued while the workspace's GPUs are busy, or still drawing)")
def gpus_for(frames, frame_s, start_s, most):
"""The GPUs worth starting for `frames` frames of `frame_s` each, when each one first spends `start_s`: the most that
keep each one's start at most SHARE of its time, never more than `most`."""
@@ -59,16 +90,23 @@ def gpus_for(frames, frame_s, start_s, most):
# a GPU takes up to this many parts of a long job, one after another from the job's queue, so a slow card (an L4 among
# L40Ss) ends up drawing fewer frames instead of holding up the job
PARTS = 4
# containers with no GPU are all the same machine, so a queue only evens out frames that cost more in one stretch than
# another: 2 parts each. At 4 an 894-frame ad went out as 32 parts of 28 frames, each paying about 5 s to start
# (raea, the composition, each clip read on from its last keyframe) for 10 s of frames (11-30)
CPU_PARTS = 2
# a video part's start is never planned at less than this (s): the timed run's own start is measured on a warm
# container with the clips' first frames, and came out at 2.8-3.6 s where the parts after it paid about 5
PART_START = 5.0
def parts_per_gpu(frames, k, frame_s, start_s):
"""How many parts each of `k` GPUs takes from the queue: the most (up to PARTS) that keep a part's own start
(start_s, more than a warm GPU needs) at most SHARE of the part. Above 1 only when the GPU limit capped `k`."""
def parts_per_gpu(frames, k, frame_s, start_s, most=PARTS):
"""How many parts each of `k` containers takes from the queue: the most (up to `most`) that keep a part's own start
(start_s, more than a warm one needs) at most SHARE of the part. Above 1 only when the limit capped `k`."""
if k <= 0 or frame_s <= 0:
return 1
least = start_s * (1 - SHARE) / SHARE / frame_s # the frames a part needs for its start to be worth it
m = 1
while m < PARTS and frames / (k * (m + 1)) >= least:
while m < most and frames / (k * (m + 1)) >= least:
m += 1
return m
@@ -90,11 +128,18 @@ def runs(first, last, k, warm=0):
# 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)}
# "cpu" is a container with no GPU (farm.py's raea_cpu_run), for a video with no 3D in it: on 60 frames of a 1080x1920
# ad cut from 4K footage a T4 container took 11.1 s with 2.5 cores busy and 8 cores alone took 13.9 s with 4.7 busy
# (11-30), the same picture at SSIM 0.9999, for about half the price a frame.
RESERVED = {"raea": (2, 8), "blender": (4, 16), "cpu": (4, 8)}
CPU = "CPU" # a container with no GPU, as a run's kind
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)
def price(kind, seconds, cpu=None, memory_gib=None, busy=0.0):
"""What `seconds` of a container of `kind` cost: its GPU, its memory, and the cores it reserves or, when it kept
more than that busy, those (Modal bills a container's use above what it reserves)."""
c, g = RESERVED["cpu" if kind == CPU else "raea"]
return prices.cost(kind, cpu=max(cpu or c, busy or 0), memory_gib=memory_gib or g, seconds=seconds)
SCALEDOWN = 2 # s a GPU container stays up after its last run (farm.py), billed
@@ -111,16 +156,23 @@ class Bill:
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))
k, b0, e0, c0 = self.tasks.get(r["task"], (r.get("kind"), b, e, 0.0))
# a container's cores: its busiest run's, an upper bound on what it's billed above its reservation
self.tasks[r["task"]] = (k or r.get("kind"), min(b, b0), max(e, e0), max(c0, r.get("cores") or 0))
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 usd(self):
return sum(price(k or "L4", e - b + BOOT + SCALEDOWN, *((None, None) if k == CPU else (self.cpu, self.gib)), busy=c) for k, b, e, c in self.tasks.values())
def line(self):
up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e in self.tasks.values()]
# the busiest run's cores and biggest process, against what each container reserves (farm.py on())
up = [(k or "L4", e - b + BOOT + SCALEDOWN) for k, b, e, _ in self.tasks.values()]
# the busiest run's cores and biggest process, against what a GPU 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}"
flat = sum(1 for k, _ in up if k == CPU)
# the containers by what they are: a job with no 3D has one GPU container (frame 0's) and the rest with none
what = f"{len(up)} GPU containers" if not flat else f"{len(up) - flat} GPU and {flat} CPU containers"
return f"raea farm: billed about ${self.usd():.3f}: {what} up {sum(s for _, s in up):.0f} s in all{used}"
def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
@@ -134,19 +186,34 @@ def encode(frames_dir, out, fps, sound, run, start=0, frames=None):
return run(cmd)
def join(frames_dir, out, sound, run):
"""The runs' H.264 videos (run-FIRST.mp4) as OUT, one after another without encoding again, with the sound."""
def join(frames_dir, out, sound, run, seconds=None):
"""The runs' H.264 videos (run-FIRST.mp4) as OUT, one after another without encoding again, with the sound, cut at
`seconds` (the piece's length). Only the runs' video tracks are read: each run has an AAC track too, whose encoder
delay (1024 samples) moved the joined video 21 ms after the sound, and -shortest then ended it 2 frames early
(the 894-frame ad came back as 892 on every farm render before 11-30, the live farm's included)."""
runs_ = sorted(n for n in os.listdir(frames_dir) if re.fullmatch(r"run-\d+\.mp4", n))
listing = os.path.join(frames_dir, "runs.txt")
track = video_track(os.path.join(frames_dir, runs_[0]), run) if runs_ else None
with open(listing, "w") as f:
if track:
f.write(f"ffconcat version 1.0\nstream\nexact_stream_id {track}\n")
f.writelines(f"file '{n}'\n" for n in runs_)
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", listing]
if sound and os.path.exists(sound) and os.path.getsize(sound) > 44:
cmd += ["-i", sound, "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "256k", "-shortest"]
cmd += ["-i", sound, "-map", "0:v", "-map", "1:a", "-c:a", "aac", "-b:a", "256k"]
if seconds:
cmd += ["-t", f"{seconds:.6f}"]
cmd += ["-c:v", "copy", "-movflags", "+faststart", out]
return run(cmd)
def video_track(path, run):
"""A video file's video track id (0x1), as the concat demuxer's exact_stream_id takes it; None when not said."""
c, o, _ = run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=id", "-of", "csv=p=0", path])
o = (o or "").strip().splitlines()
return o[0].strip() if not c and o and o[0].strip().startswith("0x") else None
def keep(frames_dir, out, start=0):
"""The frames as a folder of PNGs, named as raea names them (frame-00000.png is the first)."""
os.makedirs(out, exist_ok=True)
@@ -154,30 +221,49 @@ 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, got=None):
"""`calls` on `fn`, at most `most` GPUs at once when there are more calls than that (each GPU takes the next call
def spread(fn, kind, calls, log, what, bill=None, most=None, got=None, again=None):
"""`calls` on `fn`, at most `most` containers at once when there are more calls than that (each takes the next call
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."""
failure's code, else 0. With `again` (a list): a run that failed, or drew 3D, isn't the job's failure: its call
goes in `again`, for a GPU to take."""
code = 0
if most and len(calls) > most:
fn = fn.with_options(max_containers=most)
left = {c[3]: c for c in calls if len(c) > 3} if again is not None else {}
for r in fn.starmap(calls, order_outputs=False, return_exceptions=True):
if isinstance(r, Exception):
log(f"raea farm: a run failed: {r!r}", err=True)
code = code or 1
# (with `again`, said too: 11-30 a run went back to a GPU and nothing said why)
log(f"raea farm: a run failed{' without a GPU' if again is not None else ''}: {r!r}"[:600], err=again is None)
code = code if again is not None else code or 1
continue
if bill:
bill.add(r)
if again is not None and (r["code"] or (r.get("manifest") or {}).get("has3d")):
why = "it drew 3D" if not r["code"] else f"exit {r['code']}: " + " | ".join((r.get("out") or "").strip().splitlines()[-3:])
log(f"raea farm: frames from {r.get('first')} didn't draw without a GPU ({why})"[:600])
continue
left.pop(r.get("first"), None)
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)
code = code or r["code"]
if again is not None:
again.extend(left.values())
return code
def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None, bill=None):
def timed(r, n):
"""A timed run's (seconds a frame, seconds to start): the frame from raea's own clocks over the whole frame (React,
the page, the clips read, the draw, the encode: farm.py's work_ms) when the run says them, else from its "N ms a
frame" line, which is React and the page alone. That line read 47 ms on a 3D film whose frames took 151 ms, so
the plan put 892 frames on one GPU, and 205 ms on an ad whose slow stretch took 1,600 (11-30)."""
frame_s = (r.get("work_ms") / n if r.get("work_ms") else r.get("ms") or 1000 * r["s"] / n) / 1000
return frame_s, max(0.0, r["s"] - frame_s * n)
def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None, bill=None, cpu_render=None):
bill = bill or Bill()
id = opts["id"]
rest, out = split_out(args)
@@ -190,35 +276,100 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
if out.endswith(VIDEO):
t = threading.Thread(target=lambda: run(["raea", *rest, "-o", sound], cwd=work, env=cpu_env))
t.start()
p = bill.add(render.remote(id, rest, probe=True))
if p["code"] or not p["length"]:
log(p["out"], err=True)
if not p["code"]:
log("raea farm: frame 0 rendered but didn't say the piece's length, so its frames can't be shared out", err=True)
return p["code"] or 1
length, fps, kind = p["length"], p["fps"] or 30, p.get("kind") or opts.get("gpu") or "T4"
log(f"raea farm: {length} frames at {p['w']}x{p['h']}, {fps} fps; frame 0 on a {kind} in {p['s']:.1f} s")
video = out.endswith(VIDEO)
n0 = min(length, FIRST)
r0 = bill.add(render.remote(id, rest, list(range(n0)), 0, video=video))
if r0["code"]:
can_flat = bool(video and cpu_render and not opts.get("gpu"))
# what each frame draws, as a key (farm_keys.py): read here with nothing drawn, when this raea has --keys
keyed, keys_s = farm_keys.read(rest, work, run, cpu_env, f"/tmp/{id}-keys.json") if video and opts.get("keys") else (None, 0)
def probed():
p = bill.add(waited(render, log, id, rest, probe=True))
if p["code"] or not p["length"]:
log(p["out"], err=True)
if not p["code"]:
log("raea farm: frame 0 rendered but didn't say the piece's length, so its frames can't be shared out", err=True)
return p, p["code"] or 1
log(f"raea farm: {p['length']} frames at {p['w']}x{p['h']}, {p['fps'] or 30} fps; frame 0 on a {p.get('kind') or opts.get('gpu') or 'T4'} in {p['s']:.1f} s")
return p, 0
if keyed and keyed["has3d"] is False and can_flat:
# its keys say the length, the size and that there's no 3D in it: no frame 0 on a GPU first
p = {"code": 0, "length": keyed["length"], "fps": keyed["fps"], "w": keyed["width"], "h": keyed["height"], "s": 0.0, "keys": True,
"manifest": {k: keyed[k] for k in ("width", "height", "fps", "length", "has3d")}}
log(f"raea farm: {p['length']} frames at {p['w']}x{p['h']}, {p['fps'] or 30} fps; its frames' keys read in {keys_s:.1f} s, no 3D in it")
else:
p, code = probed()
if code:
return code
length, fps, kind = p["length"], p["fps"] or 30, p.get("kind") or opts.get("gpu") or "T4"
# the runs an earlier render of the piece left (kept by their frames' keys), and the frames no kept run holds
store, hits, gaps = None, [], [(0, length - 1)]
if keyed and not keyed["has3d"] and keyed["length"] == length and opts.get("kept", True):
store = f"{opts['keys']}/{farm_keys.base(opts.get('raea'), rest, keyed, work)}"
hits, gaps = farm_keys.cover(store, keyed["keys"])
if hits:
held = sum(n for _, n, _ in hits)
log(f"raea farm: {len(hits)} runs kept from an earlier render hold {held} of {length} frames, so {length - held} are drawn")
# the clips read from copies no larger than the page draws them (farm_proxy.py), after the store's name is read
# from the originals: a draft at half size reads most of a 4K cut's footage at a quarter of its pixels
if keyed and keyed.get("drawn") and opts.get("proxies") and gaps:
if farm_proxy.use(farm_proxy.plan(keyed["drawn"], work, run, opts["proxies"]), opts["proxy_make"], log, reload):
opts.get("proxy_commit", lambda: None)()
todo = sum(b - a + 1 for a, b in gaps)
n0, at0 = min(todo, FIRST, gaps[0][1] - gaps[0][0] + 1 if gaps else 0), gaps[0][0] if gaps else 0
# a video with no 3D in it (frame 0's manifest says) is drawn by containers with no GPU: the page, the clips and
# the encode are the CPU's work either way. A named GPU (opts gpu) keeps the job on it.
gpu_render, gpu_kind = render, kind
# a piece with 3D in it keeps its GPU, and its runs use the GPU's encoder and decoder too (CR34): on a 2D piece NVENC
# bought nothing (300 frames: 210 s against libx264's 215 s, 11% more bytes), the page and the clips are the work
nv = bool((p.get("manifest") or {}).get("has3d"))
flat = bool(video and cpu_render and not opts.get("gpu") and (p.get("manifest") or {}).get("has3d") is False)
r0 = None
first = list(range(at0, at0 + n0))
if flat and n0:
r0 = bill.add(waited(cpu_render, log, id, rest, first, at0, video=video))
if r0["code"] or (r0.get("manifest") or {}).get("has3d"):
log("raea farm: the first frames didn't draw without a GPU, so the job stays on GPUs")
flat, r0 = False, None
if p.get("keys"): # no frame 0 was drawn on a GPU yet: its time is what a cold GPU's start is planned by
p, code = probed()
if code:
return code
kind = gpu_kind = p.get("kind") or opts.get("gpu") or "T4"
if flat:
render, kind, most = cpu_render, CPU, opts.get("cpus") or opts["gpus"]
else:
most = opts["gpus"]
if n0:
r0 = bill.add(waited(render, log, id, rest, first, at0, video=video, **({"nv": True} if nv else {})))
if r0 and r0["code"]:
log(r0["out"], err=True)
return r0["code"]
frame_s = (r0["ms"] or 1000 * r0["s"] / n0) / 1000
start_s = max(0.0, r0["s"] - frame_s * n0)
left = length - n0
k = gpus_for(left, frame_s, start_s, opts["gpus"])
m = parts_per_gpu(left, k, frame_s, start_s)
cost = price(kind, p["s"] + r0["s"] + k * m * start_s + left * frame_s)
frame_s, start_s = timed(r0, n0) if r0 else (0.0, 0.0)
left = todo - n0
# a container beyond the first starts cold: frame 0's whole time, less its one frame (the first is warm by now)
cold_s = start_s if flat else max(start_s, p["s"] - frame_s)
k = gpus_for(left, frame_s, cold_s, most)
m = parts_per_gpu(left, k, frame_s, max(start_s, PART_START) if video else start_s, CPU_PARTS if flat else PARTS)
cost = price(gpu_kind, p["s"]) + price(kind, (r0["s"] if r0 else 0) + k * m * start_s + (k - 1) * (cold_s - start_s) + left * frame_s, busy=(r0 or {}).get("cores") or 0)
parts = f" in {k * m} parts" if m > 1 else ""
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {k} {kind}s{parts}, about ${cost:.3f} in all")
on = f"{k} {kind}s" if not flat else f"{k} containers with no GPU (no 3D in it)"
if r0:
log(f"raea farm: {frame_s * 1000:.0f} ms a frame, {start_s:.1f} s to start; {left} frames left on {on}{parts}, about ${cost:.3f} in all")
else:
log("raea farm: nothing to draw: every frame is in a run kept from an earlier render")
if opts.get("max_usd") is not None and cost > opts["max_usd"]:
log(f"raea farm: about ${cost:.3f} is over max_usd ${opts['max_usd']:.3f}, so the rest don't start", err=True)
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)
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
got = [r0] if r0 else []
calls = [(id, rest, f, at, False, video, *([True] if nv and not flat else [])) for a, b, share in farm_keys.spans(gaps, n0, k * m) for f, at in runs(a, b, share, warm)] if left else []
again = [] if flat else None
code = spread(render, kind, calls, log, "frames", bill, k, got, again) if calls else 0
if again:
# what a container with no GPU couldn't draw, or drew 3D in (on a software rasteriser): a GPU draws it again
log(f"raea farm: {len(again)} of {len(calls)} runs go to a GPU (they failed without one, or have 3D in them)")
code = spread(gpu_render, gpu_kind, again, log, "frames", bill, opts["gpus"], got)
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
@@ -228,14 +379,22 @@ def raea_render(args, opts, work, log, render, cpu_env, run, reload=lambda: None
reload() # the other containers' frames
frames = f"{os.path.dirname(work)}/frames"
dest = os.path.join(work, out)
# (a run that drew 3D after all isn't kept: its frames can hang on the frames before them)
if store and not any((r.get("manifest") or {}).get("has3d") for r in got):
farm_keys.put(store, keyed["keys"], got, frames)
got += farm_keys.take(hits, frames)
if manifest and p.get("manifest"):
path = os.path.join(work, manifest)
os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
whole = joined(p["manifest"], [r.get("manifest") for r in got])
if hits and keyed.get("sounds"):
# a kept run's manifest holds the sounds of the render that drew it: the piece's own, as its keys' pass heard them
whole["sounds"] = keyed["sounds"]
with open(path, "w") as f:
json.dump(joined(p["manifest"], [r.get("manifest") for r in got]), f, indent=2)
json.dump(whole, f, indent=2)
if video:
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
c, o, s = join(frames, dest, sound, run)
c, o, s = join(frames, dest, sound, run, length / fps)
log(f"raea farm: joined {out} in {s:.1f} s" if not c else o, err=bool(c))
return c
keep(frames, dest)
@@ -321,7 +480,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
if video:
o |= {"video": True, "fps": info["fps"]}
log(f"raea farm: {blend}, frames {first}-{last} ({info['engine']}), at {info['fps']:g} fps")
r0 = bill.add(render.remote(id, blend, first, first, o))
r0 = bill.add(waited(render, log, id, blend, first, first, o))
if r0["code"]:
log(r0["out"], err=True)
return r0["code"]
@@ -353,7 +512,7 @@ def blender(args, opts, work, log, render, run, reload=lambda: None, bill=None):
return 0
def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload=lambda: None):
def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload=lambda: None, cpu_render=None):
"""The job: a split raea render, a split Blender render, or `raea ARGS` whole on one GPU."""
if opts.get("gpu"):
render, blender_render = (f.with_options(gpu=opts["gpu"]) for f in (render, blender_render))
@@ -364,9 +523,9 @@ def dispatch(args, opts, work, log, render, blender_render, cpu_env, run, reload
return code
bill = Bill()
if splittable(args):
code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill)
code = raea_render(args, opts, work, log, render, cpu_env, run, reload, bill, cpu_render)
else:
r = bill.add(render.remote(opts["id"], args))
r = bill.add(waited(render, log, opts["id"], args))
log(r["out"], err=bool(r["code"]))
code = r["code"]
log(bill.line())
+120
View File
@@ -0,0 +1,120 @@
# A job's clips read from copies no larger than they're drawn (docs/cloud-render.feature CR36): `raea render --keys`
# says the largest each clip is drawn over the piece (its box as drawn, transforms and a framed take's punch-in
# applied, in output px), and a clip much larger than that is read from a copy at that size, kept on the farm's volume
# by the source's hash and the size, so it's made once across every job. The picture can't lose detail: no copy is
# smaller than the largest the page draws the clip, and none is made for a clip whose size wasn't known for a frame.
#
# plan(drawn, work, run) [(path, source, w, h, copy)]: the clips worth a copy (at most AT of the width)
# use(plans, make, log) each copy made where missing (in parallel, `make` on containers with no GPU), then
# the job's link pointed at it
#
# A 1080x1920 cut from 4K landscape footage needs most of each clip (a 9:16 crop of 2160 rows into 1920, and punch-ins
# above 1): its master render gets no copies. A half-size draft (--scale 0.5) reads six of its seven clips from copies
# at 27-59% of the width.
import json
import os
AT = 0.75 # a copy at most this much of the source's width (56% of its pixels), or none: below that it's barely worth it
CRF = 12 # visually lossless (libx264 medium): the page scales the copy, so any loss would show only at 1:1
EVEN = lambda v: max(2, int(v + 1.999) // 2 * 2) # noqa: E731 - up to an even number of px (yuv420p)
def probe(path, run):
c, o, _ = run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,color_space:stream_side_data=rotation",
"-of", "json", path])
try:
s = json.loads(o)["streams"][0]
except Exception:
return None
rot = any(abs(int(d.get("rotation", 0))) in (90, 270) for d in s.get("side_data_list") or [])
return int(s["width"]), int(s["height"]), s.get("color_space") or "", rot
def source_id(path):
"""The file's content id: a link into the farm's cache is named for its hash; anything else is hashed here"""
real = os.path.realpath(path)
name = os.path.basename(real)
if os.path.islink(path) and len(name) == 64 and all(c in "0123456789abcdef" for c in name):
return name
import hashlib
h = hashlib.sha256()
with open(real, "rb") as f:
for b in iter(lambda: f.read(1 << 20), b""):
h.update(b)
return h.hexdigest()
def plan(drawn, work, run, store):
"""The clips worth reading from a copy: [(path in the job, its source, copy w, copy h, copy path, matrix)]"""
out = []
for rel, size in (drawn or {}).items():
path = os.path.join(work, rel)
if not size or not os.path.isfile(path) or not os.path.realpath(path).startswith("/"):
continue
p = probe(path, run)
if not p or p[3]: # (a rotated clip's drawn size is in its turned frame: left as it is)
continue
w, h, matrix, _ = p
need = max(size[0] / w, size[1] / h)
if need > AT:
continue
cw, ch = EVEN(w * need), EVEN(h * need)
ext = os.path.splitext(rel)[1].lower() or ".mp4"
# untagged HD is read as BT.709 (io/ffmpeg's decoder, as Apple and browsers read it): the copy is tagged so,
# or a copy under 720 lines would be read as BT.601 and shift its colours
matrix = matrix if matrix in ("bt709", "bt470bg", "smpte170m", "bt2020nc") else ("bt709" if h >= 720 else "smpte170m")
out.append((path, os.path.realpath(path), cw, ch, os.path.join(store, f"{source_id(path)}-{cw}x{ch}{ext}"), matrix))
return out
def command(src, dest, w, h, matrix):
"""ffmpeg making one copy: scaled with lanczos in the source's own matrix, every frame at its own time, the sound copied"""
tag = {"bt709": "bt709", "bt470bg": "bt470bg", "smpte170m": "smpte170m", "bt2020nc": "bt2020nc"}[matrix]
return ["ffmpeg", "-v", "error", "-y", "-i", src, "-map", "0:v:0", "-map", "0:a?", "-vf",
f"scale={w}:{h}:flags=lanczos:in_color_matrix={tag if tag != 'bt2020nc' else 'bt2020'}:out_color_matrix={tag if tag != 'bt2020nc' else 'bt2020'}",
"-fps_mode", "passthrough", "-c:v", "libx264", "-preset", "medium", "-crf", str(CRF), "-pix_fmt", "yuv420p",
"-colorspace", tag, "-c:a", "copy", "-movflags", "+faststart", "-f", "mov" if dest.endswith(".mov") else "mp4", dest]
def use(plans, make, log, reload=lambda: None):
"""Each copy made where it isn't kept yet (`make`: a function's starmap over (src, dest, w, h, matrix)), then each
clip's link in the job pointed at its copy. Returns the number of clips swapped."""
todo = [(src, copy, w, h, m) for _, src, w, h, copy, m in plans if not os.path.exists(copy)]
made = 0
if todo:
for r in make(todo):
if isinstance(r, Exception) or (r or {}).get("code"):
log(f"raea farm: a clip's copy wasn't made, so it's read whole: {r if isinstance(r, Exception) else r.get('out', '')}"[:400])
else:
made += 1
reload()
used = 0
for path, src, w, h, copy, _ in plans:
if os.path.exists(copy):
tmp = f"{path}.proxy-link"
os.symlink(copy, tmp)
os.replace(tmp, path)
keep_faces(path, copy)
used += 1
if plans:
log(f"raea farm: {used} clips read from copies at the size they're drawn ({made} made now, {used - made if used >= made else 0} kept from before)")
return used
def keep_faces(path, copy):
"""A framed take's face track (TAKE.faces.json, made from the original by the keys pass) stamped for the copy, so
the page frames on the original's faces and doesn't find them again in the copy (runtime/page/src/faces.rs reads a
track only when its stamp is the take's own size and time)"""
side = os.path.splitext(path)[0] + ".faces.json"
if not os.path.exists(side):
return
try:
with open(side) as f:
t = json.load(f)
st = os.stat(copy)
t["take"] = {"bytes": st.st_size, "modified": int(st.st_mtime)}
with open(side, "w") as f:
f.write(json.dumps(t) + "\n")
except Exception:
pass
+25 -2
View File
@@ -8,6 +8,7 @@ Four small ONNX models from OpenCV's zoo, on the CPU through cv2.dnn, each pinne
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 pack's)
And RapidOCR's PP-OCRv4 (1.4.4, Apache-2.0), which reads each line of text, for the captions pack.
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."""
@@ -48,6 +49,7 @@ class Scene:
self.words_model.setPolygonThreshold(0.5)
self.words_model.setMaxCandidates(200)
self.words_model.setUnclipRatio(2.0)
self.ocr = None
self.face_path = face
self.face, self.face_size = None, None
@@ -121,10 +123,31 @@ class Scene:
_, 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):
def texts(self, im, least=0.5):
"""each line of text in the frame, read, as [x, y, w, h, "the text", score] (11-30, the captions pack: what an
export shows, held to what it says). RapidOCR's PP-OCRv4 (Apache-2.0, its ONNX models in the wheel), on the
CPU; it reads 540-wide frames' captions word for word in about 0.13 s a frame, where OpenCV's zoo CRNN dropped
spaces and misread them. Loaded on first use"""
if self.ocr is None:
from rapidocr_onnxruntime import RapidOCR
self.ocr = RapidOCR()
found, _ = self.ocr(im, use_cls=False)
out = []
for box, text, score in found or []:
if float(score) < least:
continue
xs, ys = [p[0] for p in box], [p[1] for p in box]
out.append([round(float(min(xs)), 1), round(float(min(ys)), 1), round(float(max(xs) - min(xs)), 1), round(float(max(ys) - min(ys)), 1), str(text), round(float(score), 3)])
return out
def read(self, im, texts=True):
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)}
out = {"w": w, "h": h, "grid": grid(p, w, h), "things": self.things(im) + self.words(im), "faces": self.faces(im)}
if texts:
out["texts"] = self.texts(im)
return out
def grid(p, w, h):
+2
View File
@@ -40,4 +40,6 @@ def kind_of(name):
for k in ("B300", "B200", "H200", "H100", "L40S", "A10", "L4", "T4"):
if re.search(rf"\b{k}\b", n):
return k
if re.search(r"\bA10G\b", n): # AWS's A10 (Modal's "A10" on some hosts)
return "A10"
return ""
+33 -5
View File
@@ -185,12 +185,26 @@ function files(req: IncomingMessage, res: ServerResponse, url: URL) {
res.writeHead(200, { "content-type": "application/octet-stream", "content-length": st.size }).end(readFileSync(p))
}
/** An NDJSON answer's headers sent at once, and an empty line ({}) every KEEPALIVE_MS until it ends: the box sits
* behind Cloudflare, which answers 524 when nothing comes back for 100 s, and `raea goal check --json` over seven
* cuts prints nothing until it's done (11-30, Dutch's stop at Client sign-off was sent back on it). Readers skip a
* line with no out, err or exit. */
const KEEPALIVE_MS = 30_000
function streamOpen(res: ServerResponse) {
res.writeHead(200, { "content-type": "application/x-ndjson" })
res.flushHeaders()
const beat = setInterval(() => res.write("{}\n"), KEEPALIVE_MS)
const stop = () => clearInterval(beat)
res.on("finish", stop)
res.on("close", stop)
}
async function run(req: IncomingMessage, res: ServerResponse) {
const { args, cwd } = JSON.parse((await body(req)).toString() || "{}") as { args?: unknown; cwd?: string }
if (!Array.isArray(args) || !args.every((a) => typeof a === "string")) return json(res, { error: "args must be an array of strings: raea's own arguments" }, 400)
const dir = resolve(cwd ?? ".")
mkdirSync(dir, { recursive: true })
res.writeHead(200, { "content-type": "application/x-ndjson" })
streamOpen(res)
const child = spawn(RAEA, args, { cwd: dir, env: childEnv(), stdio: ["ignore", "pipe", "pipe"] })
const line = (v: unknown) => res.write(JSON.stringify(v) + "\n")
child.stdout.setEncoding("utf8").on("data", (out: string) => line({ out }))
@@ -202,6 +216,8 @@ async function run(req: IncomingMessage, res: ServerResponse) {
}
const SHELL_DEFAULT_MS = 600_000
/** an ACP agent silent both ways this long is ended (the /v1/acp socket below) */
const IDLE_AGENT_MS = Number(process.env.RAEA_CLOUD_IDLE_AGENT_MS ?? 45 * 60_000)
const SHELL_MAX_MS = 3_600_000
async function shell(req: IncomingMessage, res: ServerResponse) {
@@ -210,7 +226,7 @@ async function shell(req: IncomingMessage, res: ServerResponse) {
const ms = typeof timeout_ms === "number" && timeout_ms > 0 ? Math.min(timeout_ms, SHELL_MAX_MS) : SHELL_DEFAULT_MS
const dir = resolve(cwd ?? ".")
mkdirSync(dir, { recursive: true })
res.writeHead(200, { "content-type": "application/x-ndjson" })
streamOpen(res)
// the shell on any OS: bash and a process group here, RAEA_CLOUD_BASH and taskkill on Windows (shell-os.ts)
const { bash, groupOpts, shellEnv, stopTree } = await import("./shell-os.ts")
// in a process group of its own, so a timeout or a caller leaving stops what the command started too
@@ -370,8 +386,19 @@ server.on("upgrade", (req, socket, head) => {
// "socket closed" ends came 114-125 s into a silence). raea cloud skips notifications it doesn't know; the agent
// never sees it
const beat = setInterval(() => ws.readyState === ws.OPEN && ws.send('{"jsonrpc":"2.0","method":"_raea/keepalive"}'), 20_000)
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat)))
child.on("exit", () => running.delete(child))
// an agent that has said nothing and been sent nothing for IDLE_AGENT_MS is ended: raea cloud ends a turn whose
// agent is quiet 30 min (acp-run.ts QUIET_TOOL_MS), and a socket whose caller went away without closing it (an API
// restart; the Sprite's proxy kept the box's half open) otherwise kept its agent forever (11-30: two Gemini agents
// on raea-3 for 2 h, counted as running, so no box update could go on)
let heard = Date.now()
const idle = setInterval(() => {
if (Date.now() - heard < IDLE_AGENT_MS) return
process.stderr.write(`raea-cloud: ${agent.id} said nothing and was sent nothing for ${Math.round(IDLE_AGENT_MS / 60_000)} min: ended\n`)
ws.terminate()
stopAll()
}, Math.min(60_000, IDLE_AGENT_MS / 2))
ws.on("close", () => (agentSockets.delete(ws), clearInterval(beat), clearInterval(idle)))
child.on("exit", () => (running.delete(child), clearInterval(idle)))
// its stderr to the box's log as before, and along the socket as _raea/stderr notifications, so raea cloud keeps
// it with the run's trace (runtrace.ts) instead of only on this box's disk (11-25: raea-1's logs died with it)
child.stderr.setEncoding("utf8").on("data", (c: string) => {
@@ -381,10 +408,11 @@ server.on("upgrade", (req, socket, head) => {
let buf = ""
// ACP messages are newline-delimited JSON: split on \n only
child.stdout.setEncoding("utf8").on("data", (c: string) => {
heard = Date.now()
buf += c
for (let i; (i = buf.indexOf("\n")) >= 0; buf = buf.slice(i + 1)) if (i > 0) ws.send(buf.slice(0, i))
})
ws.on("message", (m) => child.stdin.write(m.toString() + "\n"))
ws.on("message", (m) => ((heard = Date.now()), child.stdin.write(m.toString() + "\n")))
ws.on("close", stopAll)
child.on("error", (e) => ws.close(1011, `couldn't start ${agent.id}: ${e.message}`.slice(0, 120)))
child.on("exit", (code) => (ws.close(1011, `${agent.id} exited ${code}`), stopAll()))
+1 -1
View File
@@ -145,7 +145,7 @@ async function main() {
else if (typeof lfs === "string" && existsSync(path.join(p.root, ".lfsconfig"))) say(`media goes in the tar: ${lfs}`)
// a render farm's choices (deploy/modal/farm.py): RAEA_CLOUD_GPUS, RAEA_CLOUD_GPU_KIND, RAEA_CLOUD_MAX_USD
const n = (v?: string) => (v ? Number(v) : undefined)
const farm = { gpus: n(process.env.RAEA_CLOUD_GPUS), gpu: process.env.RAEA_CLOUD_GPU_KIND, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD), media: typeof lfs !== "string" }
const farm = { gpus: n(process.env.RAEA_CLOUD_GPUS), cpus: n(process.env.RAEA_CLOUD_CPUS), kept: process.env.RAEA_CLOUD_KEPT === "0" ? false : undefined, gpu: process.env.RAEA_CLOUD_GPU_KIND, maxUsd: n(process.env.RAEA_CLOUD_MAX_USD), media: typeof lfs !== "string" }
let finish: (() => Promise<number>) | undefined
const media = typeof lfs === "string" ? undefined : async (made: Parameters<typeof outputs>[2]) => {
const o = await outputs(p.root, lfs, made)
+7
View File
@@ -32,6 +32,11 @@ export interface Health {
* names: L4, L40S, ...), and a price over `maxUsd` (estimated from the first frames) stops it before the rest. */
export interface Farm {
gpus?: number
/** at most this many containers with no GPU at once, for a video with no 3D in it; 0 keeps the job on GPUs */
cpus?: number
/** false: every frame of a video drawn, none taken from the runs an earlier render of the piece left (kept by their
* frames' keys, docs/cloud-render.feature CR30) */
kept?: boolean
card?: string
maxUsd?: number
/** the job's media outputs stay on the farm for `media` to send to R2 (docs/cloud-render.feature CR23) */
@@ -149,6 +154,8 @@ export class RaeaCloud {
async startJob(args: string[], folder: Uint8Array, signal?: AbortSignal, farm: Farm = {}): Promise<string> {
const q = new URLSearchParams({ args: JSON.stringify(args) })
if (farm.gpus !== undefined) q.set("gpus", String(farm.gpus))
if (farm.cpus !== undefined) q.set("cpus", String(farm.cpus))
if (farm.kept === false) q.set("kept", "0")
if (farm.card) q.set("gpu", farm.card)
if (farm.maxUsd !== undefined) q.set("max_usd", String(farm.maxUsd))
if (farm.media) q.set("media", "1")
+186 -1
View File
@@ -32,8 +32,9 @@ class FakeGpu:
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=gray:s=16x16", "-frames:v", "1", src])
shutil.copy(src, path)
def remote(self, id, args, frames=None, first=0, probe=False, video=False):
def remote(self, id, args, frames=None, first=0, probe=False, video=False, nv=False):
self.calls.append(("probe" if probe else "run", frames, first))
self.nv = getattr(self, "nv", []) + ([nv] if not probe else [])
self.args = getattr(self, "args", []) + [list(args)]
if probe:
# as raea does with two --manifest: the first wins, so the probe's own says nothing
@@ -149,6 +150,153 @@ assert code == 0 and len(out) == 1000 and q.options == {"max_containers": 2} and
assert "on 2 L4s in 8 parts" in " ".join(lines), lines
ok("a long job on too few GPUs: 4 parts a GPU from a queue of 2 at a time, every frame back")
# a video with no 3D in it (frame 0's manifest says): after frame 0 on a GPU, its frames go to containers with no GPU,
# and a run that fails there, or has 3D in it after all, is drawn again by a GPU
class Flat(FakeGpu):
def __init__(self, root, length=600, name="CPU", bad=(), has3d=False):
super().__init__(root, length)
self.name, self.bad, self.has3d = name, bad, has3d
def remote(self, id, args, frames=None, first=0, probe=False, video=False, nv=False):
r = super().remote(id, args, frames, first, probe, video, nv)
if probe:
r["manifest"]["has3d"] = self.has3d
return {**r, "kind": "T4"}
r = {**r, "first": first, "kind": self.name, "work_ms": 500.0 * len(frames), "task": f"{self.name}-{first}", "boot": 0, "end": 1, "cores": 4.7}
if first in self.bad:
r = {**r, "code": 1} if self.bad[first] == "fails" else {**r, "manifest": {**(r.get("manifest") or {}), "has3d": True}}
return r
lines.clear()
os.makedirs(os.path.join(root, "jobs", "jc", "work"))
g, c = Flat(root, name="T4"), Flat(root)
code = fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jc", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "jc", "work"), log, g, {}, run, cpu_render=c)
said = " ".join(lines)
assert code == 0 and [x[0] for x in g.calls] == ["probe"] and len(c.calls) == 1 + 6, (code, g.calls, len(c.calls), lines)
assert "on 6 containers with no GPU (no 3D in it)" in said and "frames on a CPU" in said, lines
# capped by the job's cpus, a long piece goes out as 2 parts a container, not 4
assert fp.parts_per_gpu(886, 8, 0.2, 5.0, fp.CPU_PARTS) == 1 and fp.parts_per_gpu(9000, 8, 0.2, 5.0, fp.CPU_PARTS) == 2 and fp.parts_per_gpu(9000, 8, 0.2, 5.0) == 4
ok("a video with no 3D: frame 0 on a GPU, every frame after on containers with no GPU, up to the job's cpus")
lines.clear()
os.makedirs(os.path.join(root, "jobs", "jd", "work"))
g, c = Flat(root, name="T4"), Flat(root, bad={8: "fails", 107: "3d"})
code = fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jd", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "jd", "work"), log, g, {}, run, cpu_render=c)
again = [x for x in g.calls if x[0] == "run"]
assert code == 0 and sorted(x[2] for x in again) == [8, 107] and "2 of 6 runs go to a GPU" in " ".join(lines), (code, again, lines)
n = int(subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", os.path.join(root, "jobs", "jd", "work", "out", "a.mp4")], capture_output=True, text=True).stdout)
assert n == 600, n
ok("a run that fails with no GPU, or has 3D in it, is drawn again by a GPU, and the video still has every frame")
lines.clear()
os.makedirs(os.path.join(root, "jobs", "je", "work"))
g, c = Flat(root, name="T4"), Flat(root)
code = fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "je", "gpu": "L4", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "je", "work"), log, g, {}, run, cpu_render=c)
assert code == 0 and not c.calls, c.calls
code = fp.raea_render(["render", "a.tsx", "-o", "stills"], {"id": "je", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "je", "work"), log, g, {}, run, cpu_render=c)
assert code == 0 and not c.calls, c.calls
ok("a job that names its GPU, and a render to stills, stay on GPUs")
# a video's runs kept by their frames' keys (farm_keys.py): the same piece again draws nothing and joins the kept runs
# with its sound made again; one shot changed draws only the runs that held it
class Keyed:
def __init__(self, length): self.keys = [f"k{i}" for i in range(length)]
def __call__(self, cmd, cwd=None, env=None, timeout=None):
if "--keys" in cmd:
n = len(self.keys)
with open(cmd[cmd.index("--keys") + 1], "w") as f:
json.dump({"width": 1920, "height": 1080, "fps": 30, "length": n, "has3d": False, "keys": self.keys, "sounds": {"fps": 30, "clips": [{"key": "mine"}], "notes": [], "lines": []}}, f)
return 0, "", 0.4
return run(cmd, cwd, env, timeout)
kept, keyed = os.path.join(root, "kept"), Keyed(600)
def frames_in(job):
return int(subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", os.path.join(root, "jobs", job, "work", "out", "a.mp4")], capture_output=True, text=True).stdout)
def drawn(c): return sum(len(x[1]) for x in c.calls if x[0] == "run")
for job in ("jk1", "jk2", "jk3"):
os.makedirs(os.path.join(root, "jobs", job, "work"))
shutil.copy(os.path.join(root, "one.png"), os.path.join(root, "jobs", job, "work", "logo.png"))
lines.clear()
g, c = Flat(root, name="T4"), Flat(root)
o = {"gpus": 2, "cpus": 8, "keys": kept, "raea": "test"}
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {**o, "id": "jk1"}, os.path.join(root, "jobs", "jk1", "work"), log, g, {}, keyed, cpu_render=c) == 0, lines
assert not g.calls and drawn(c) == 600 and frames_in("jk1") == 600, (g.calls, drawn(c), lines)
lines.clear()
g, c = Flat(root, name="T4"), Flat(root)
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4", "--manifest", "out/a.json"], {**o, "id": "jk2"}, os.path.join(root, "jobs", "jk2", "work"), log, g, {}, keyed, cpu_render=c) == 0, lines
assert not g.calls and not c.calls and frames_in("jk2") == 600, (g.calls, c.calls, lines)
assert "hold 600 of 600 frames" in " ".join(lines) and json.load(open(os.path.join(root, "jobs", "jk2", "work", "out", "a.json")))["sounds"]["clips"] == [{"key": "mine"}], lines
keyed.keys[300:320] = [f"new{i}" for i in range(20)]
lines.clear()
g, c = Flat(root, name="T4"), Flat(root)
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {**o, "id": "jk3"}, os.path.join(root, "jobs", "jk3", "work"), log, g, {}, keyed, cpu_render=c) == 0, lines
assert 20 <= drawn(c) < 300 and all(min(x[1]) <= 319 and max(x[1]) >= 300 or True for x in c.calls) and frames_in("jk3") == 600, (drawn(c), lines)
ok(f"kept runs: the same piece again draws nothing; 20 frames changed draw {drawn(c)} of 600; no frame 0 on a GPU first")
# a file the keys don't hold (an image the page shows, the engine) starts a store of its own
k = {"width": 1, "height": 1, "fps": 30, "length": 1}
w = os.path.join(root, "jobs", "jk3", "work")
b1 = fp.farm_keys.base("test", ["a"], k, w)
open(os.path.join(w, "logo.png"), "ab").write(b"x")
assert b1 != fp.farm_keys.base("test", ["a"], k, w) != fp.farm_keys.base("other", ["a"], k, w)
ok("a changed image, or another raea, keeps nothing from the store before it")
# a piece with 3D keeps its GPU, and its runs use NVIDIA's encoder and decoder (CR34); a 2D piece's GPU runs don't
lines.clear()
os.makedirs(os.path.join(root, "jobs", "jn", "work"))
g, c = Flat(root, name="T4", has3d=True), Flat(root)
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jn", "gpus": 2, "cpus": 8}, os.path.join(root, "jobs", "jn", "work"), log, g, {}, run, cpu_render=c) == 0, lines
assert not c.calls and g.nv and all(g.nv), (c.calls, g.nv)
g = Flat(root, name="T4")
assert fp.raea_render(["render", "a.tsx", "-o", "out/a.mp4"], {"id": "jn", "gpus": 2, "cpus": 0}, os.path.join(root, "jobs", "jn", "work"), log, g, {}, run) == 0, lines
assert g.nv and not any(g.nv), g.nv
ok("a piece with 3D draws on GPUs with NVENC and NVDEC asked for; a 2D piece kept on GPUs doesn't ask")
# the join keeps every frame of runs that have B-frames, with the piece's sound (11-30: -shortest ended the joined
# video 2 frames early, 892 of an 894-frame ad)
jd = os.path.join(root, "joins")
os.makedirs(jd)
for first, n in ((0, 8), (8, 148), (156, 147)):
# each with an AAC track, as raea's --at runs have
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=s=64x64:r=30", "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-frames:v", str(n), "-t", str(n / 30), "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", f"{jd}/run-{first:05d}.mp4"])
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "sine=f=440:d=10.1", "-ar", "48000", f"{jd}/s.wav"])
c, o, _ = fp.join(jd, f"{jd}/out.mp4", f"{jd}/s.wav", run, 303 / 30)
said = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-select_streams", "v", "-show_entries", "stream=nb_read_frames,start_time", "-of", "csv=p=0", f"{jd}/out.mp4"], capture_output=True, text=True).stdout.strip().split(",")
assert c == 0 and int(said[1]) == 303 and float(said[0]) == 0, (c, o, said)
ok("the join keeps every frame of runs that have their own AAC tracks, the video from 0 with the sound")
# a clip much larger than it's drawn is read from a copy at that size, made once and kept by its hash (CR36); one
# drawn near its size, or whose size wasn't known for a frame, is read whole
import farm_proxy # noqa: E402
pw = os.path.join(root, "jobs", "jp", "work")
os.makedirs(os.path.join(pw, "media"))
run(["ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=s=640x360:r=30", "-f", "lavfi", "-i", "sine=f=440:r=48000", "-t", "2", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", os.path.join(pw, "media", "a.mp4")])
for n in ("b.mp4", "c.mp4"):
shutil.copy(os.path.join(pw, "media", "a.mp4"), os.path.join(pw, "media", n))
with open(os.path.join(pw, "media", "a.faces.json"), "w") as f:
json.dump({"take": {"bytes": 1, "modified": 1}, "every": 0.5, "eyes": [[0.5, 0.4]]}, f)
store = os.path.join(root, "proxies")
plans = farm_proxy.plan({"media/a.mp4": [100, 200], "media/b.mp4": [600, 340], "media/c.mp4": None}, pw, run, store)
assert [(os.path.basename(p[0]), p[2], p[3]) for p in plans] == [("a.mp4", 356, 200)], plans
made = []
def make(todo):
made.extend(todo)
os.makedirs(store, exist_ok=True)
return [{"code": run(farm_proxy.command(*a))[0]} for a in todo]
assert farm_proxy.use(plans, make, log) == 1 and len(made) == 1
a = os.path.join(pw, "media", "a.mp4")
said = subprocess.run(["ffprobe", "-v", "error", "-count_frames", "-show_entries", "stream=codec_type,width,height,nb_read_frames", "-of", "csv=p=0", a], capture_output=True, text=True).stdout.split()
assert os.path.islink(a) and said[0].startswith("video,356,200,60") and said[1].startswith("audio"), said
assert json.load(open(os.path.join(pw, "media", "a.faces.json")))["take"]["bytes"] == os.path.getsize(made[0][1])
# b.mp4 is the same file under another name: its copy is found by its hash, nothing made again
plans = farm_proxy.plan({"media/b.mp4": [100, 200]}, pw, run, store)
assert farm_proxy.use(plans, make, log) == 1 and len(made) == 1 and os.path.realpath(os.path.join(pw, "media", "b.mp4")) == os.path.realpath(made[0][1])
ok("clips drawn far smaller than they are read from copies at that size (every frame, the sound, the face track kept); others whole")
# a frame's time is raea's own clocks over the whole frame when the run says them, not its React line
assert fp.timed({"s": 20.0, "ms": 47.0, "work_ms": 1208.0}, 8) == (0.151, 20.0 - 0.151 * 8)
assert fp.timed({"s": 20.0, "ms": 47.0}, 8)[0] == 0.047 and fp.timed({"s": 20.0, "ms": None}, 8) == (2.5, 0.0)
ok("the timed run's frame is the whole frame's time, so a 3D film isn't planned at a third of its cost")
b = fp.Bill()
t = b.t0
b.add({"task": "a", "kind": "L40S", "boot": t - 100, "end": t + 10}) # left up by an earlier job: from this job's start
@@ -157,5 +305,42 @@ b.add({"task": "b", "kind": "T4", "boot": t + 1, "end": t + 6})
b.add({"code": 1, "out": "no task id"})
assert "2 GPU containers up 35 s" in b.line(), b.line()
ok("the bill: each container from its boot or the job's start to its last run, plus its boot and idle seconds")
b = fp.Bill()
b.add({"task": "g", "kind": "T4", "boot": b.t0, "end": b.t0 + 15, "cores": 1.0})
b.add({"task": "c1", "kind": "CPU", "boot": b.t0, "end": b.t0 + 95, "cores": 7.0})
want = fp.prices.cost("T4", 2, 8, 20) + fp.prices.cost("CPU", 7.0, 8, 100)
assert "1 GPU and 1 CPU containers up 120 s" in b.line() and abs(b.usd() - want) < 1e-9, (b.line(), want)
ok("the bill prices a container with no GPU as one, and the cores a run kept busy above what it reserves")
# a GPU run with no answer yet is said in the log, not waited on in silence; its answer still comes back
class SlowCall:
def __init__(self, waits): self.waits = waits
def get(self, timeout=None):
if self.waits:
self.waits -= 1
raise TimeoutError
return {"code": 0, "out": "drawn"}
class SlowGpu:
def spawn(self, *a, **kw): return SlowCall(2)
lines.clear()
fp.WAIT_SAY_S = 0.01
assert fp.waited(SlowGpu(), log, "j4", ["render"]) == {"code": 0, "out": "drawn"}
assert sum("waiting" in l and "GPU run" in l for l in lines) == 2, lines
ok("a GPU run that hasn't answered is said in the log every WAIT_SAY_S until it does")
# a GPU run that ran out of its own time fails the job, as .remote() did, instead of being waited on forever
class FunctionTimeoutError(TimeoutError): pass
class TimedOutCall:
def get(self, timeout=None): raise FunctionTimeoutError("Function timeout")
class TimedOutGpu:
def spawn(self, *a, **kw): return TimedOutCall()
lines.clear()
try:
fp.waited(TimedOutGpu(), log, "j5", ["render"])
raise AssertionError("waited() swallowed a function timeout")
except FunctionTimeoutError:
pass
assert not any("waiting" in l for l in lines), lines
ok("a GPU run that timed out fails the job instead of being waited on forever")
shutil.rmtree(root)
+7 -2
View File
@@ -27,6 +27,11 @@ export interface Workflow {
/** raea's packs by name (packs/index.ts): what each holds a job to */
export const PACKS = {
words: "every word a cut's lines say is heard whole in its export, none faded under a crossfade",
captions: "every caption on screen says exactly what's heard there: nothing added or changed, no words dropped from a captioned line",
voice: "the dialogue on top of the mix (10 dB over what's under it) and every line as loud as the others, measured on the export",
hook: "the hook opens on words and picture together: no dead air before the first word",
airgaps: "no air between words: gaps tightened in the hook's first 3 s, no long pause after (tighten() cuts between words only)",
reading: "every block of text that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture",
sound: "edit points in the pauses, every line within 6 dB of the others, every effect heard",
frames: "no face cut by the frame or a split screen's seam, no text too small to read",
montage: "each cut's pace kept to its beats, and eye trace, screen direction and tone kept across its cuts",
@@ -55,13 +60,13 @@ export type PackName = keyof typeof PACKS
/** each kind's packs, on unless the brief switches them off (surprise is on only where a brief turns it on) */
export const DEFAULTS: Record<GoalKind | "floor", PackName[]> = {
cut: ["words", "sound", "frames", "montage", "place", "floor", "stills", "seen", "naming", "sizes", "quotes", "count", "open", "say", "never", "cta", "shape"],
cut: ["words", "captions", "voice", "reading", "hook", "airgaps", "sound", "frames", "montage", "place", "floor", "stills", "seen", "naming", "sizes", "quotes", "count", "open", "say", "never", "cta", "shape"],
rules: ["deliverables", "stills"],
scene: ["deliverables", "record", "critic", "notes", "stills"],
kit: ["deliverables", "record", "critic", "notes", "stills"],
shot: ["deliverables", "record", "critic", "notes", "stills"],
// a project with no `goal`: what any made video is held to, and any composition as it's saved
floor: ["frames", "floor", "seen", "stills"],
floor: ["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"],
}
/** a `says` rule: what a fresh critic must find true of the work (`raea goal judge`) */
+2 -1
View File
@@ -234,7 +234,8 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
}
const fs = (g.faces as any[][]) ?? []
faces.push({ w: g.w, h: g.h, faces: fs.map((x) => [x[0], x[1], x[2], x[3], x[5]]), seams: g.seams })
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs } as Scene)
// texts: each line of text read (the farm's PP-OCRv4 since 11-30); undefined from a farm that doesn't read text
scenes.push({ w: g.w, h: g.h, grid: g.grid, things: g.things ?? [], faces: fs, ...(Array.isArray(g.texts) ? { texts: g.texts } : {}) } as Scene)
}
}
return { rate: at?.length ? 0 : RATE, faces, scenes }
+214
View File
@@ -0,0 +1,214 @@
// The captions pack (11-30, Shane: "running a transcription and ocr pass on the final output as fast as possible would
// be helpful because it also helps catch if audio captions pick up something else that's not supposed to be there or if
// we cut off words"): what an export SHOWS against what it SAYS, both read off the export itself, so it can't be passed
// by what the edit meant to show. Elfster's captions, typed by hand, said "for a bad gift" (said: "when they get a bad
// gift"), "Oh my god" (said: "Oh my"), dropped half a line and two words of the brief's own call to action; every
// check passed them, since none read the picture.
//
// read: the scene reader (raea cloud's farm, POST /v1/scene) reads the text in each frame, two a second (PP-OCRv4).
// heard: the words pass's transcript of the same export.
// captions: a line of text whose letters mostly match what's said around it (within 2.5 s before to 1 s after) is a
// caption; hook text, a title, a logo or a sign isn't, and is left alone.
// shown, not said: a run of three letters or more in the captions that nothing heard near it accounts for is an
// error (a word added or changed: "god").
// said, not shown: while captions are up, a heard word the captions leave out is a warning, two or more in a row an
// error (words dropped: "when they get"). Fillers (um, uh) aren't counted.
// Letters are compared, not words: the reader often drops a caption's spaces ("Createyour GiftExchangehere.").
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import type { TextLine } from "./place.ts"
/** a line of text the reader found in a frame: [x, y, w, h, text, score], in that frame's pixels */
export type Read = TextLine
export type Finding = { level: "error" | "warn" | "note"; kind: "shown" | "dropped" | "none"; at: number; says: string }
/** a word or a line as it's compared: lower case letters and digits, nothing else */
export const letters = (s: string) => s.toLowerCase().normalize("NFKD").replace(/[^\p{L}\p{N}]+/gu, "")
/** what's said that a caption may leave out without changing what's said */
const FILLER = new Set(["um", "uh", "uhh", "umm", "mm", "mhm", "hmm", "er", "erm", "ah"])
/** a line is a caption when this share of its letters is matched by what's said around it */
export const CAPTION = 0.6
/** the time around a caption that what it says may be heard: before it shows, after */
const BEFORE = 2.5
const AFTER = 1.0
/** least score a read line counts at */
export const LEAST = 0.6
/** a caption against what's said around it: the caption's letters aligned to the stretch of the heard letters they fit
* best (an edit distance with the heard text's start and end free). dist: the edits; bad: for each caption letter,
* whether it was changed or added (no heard letter matches it) */
export function fit(cap: string, said: string): { dist: number; bad: boolean[]; from: number; to: number } {
const n = cap.length
const m = said.length
// D[i][j]: edits to make cap[0..i) end at said[j); a free start anywhere in said
const D = Array.from({ length: n + 1 }, (_, i) => new Uint16Array(m + 1).fill(i))
for (let i = 1; i <= n; i++)
for (let j = 1; j <= m; j++) D[i][j] = Math.min(D[i - 1][j - 1] + (cap[i - 1] === said[j - 1] ? 0 : 1), D[i - 1][j] + 1, D[i][j - 1] + 1)
let j = 0
for (let k = 1; k <= m; k++) if (D[n][k] < D[n][j]) j = k
const dist = D[n][j]
const to = j
const bad = new Array<boolean>(n).fill(false)
let i = n
while (i > 0 && j > 0) {
const d = D[i][j]
if (d === D[i - 1][j - 1] + (cap[i - 1] === said[j - 1] ? 0 : 1)) {
if (cap[i - 1] !== said[j - 1]) bad[i - 1] = true
i--
j--
} else if (d === D[i - 1][j] + 1) bad[--i] = true
else j--
}
while (i > 0) bad[--i] = true
return { dist, bad, from: j, to }
}
/** the heard words whose time falls in [a, b] */
const heardIn = (heard: Word[], a: number, b: number) => heard.filter((w) => w.end >= a && w.start <= b)
const saidAround = (heard: Word[], a: number, b: number) => heardIn(heard, a - BEFORE, b + AFTER).map((w) => letters(w.text)).join("")
/** a caption's showings: one line of text, from its first frame to its last (the same line in frames side by side), and
* how far down the frame its middle is (a share of the frame's height) */
export type Shown = { text: string; key: string; from: number; to: number; y: number }
/** a frame's lines, and the frame's height */
export type Frame = { h: number; lines: Read[] }
/** lines whose middles are this close (a share of the frame's height) are the same line in the next frame */
const ROW = 0.03
/** a showing longer than this (s) is a title, a badge or a card, not a caption */
const HELD = 4.5
/** a caption fits what's said while it's up with at most this share of its letters edited; a line in capitals (a
* badge's style: "BODY BUTTER · UP TO 96 HOURS" over "Body Butter delivers up to 96 hours") with at most CAPS_FIT */
const FIT = 0.45
const CAPS_FIT = 0.3
/** captions are a track: up for at least this share of what's said, else the cut has none (hook text alone) */
const TRACK = 0.4
const CARDS = 8
/** more lines than this in a frame is a screen or a card */
const BUSY = 3
/** words a transcriber often leaves out of what it hears (so a caption that has them may be right) */
const SOFT = new Set(["yeah", "yes", "okay", "like", "wow", "hey", "right", "sorry", "well"])
/** words this close are one line (s) */
const LINE = 0.7
/** the frames' captions. First every line, the same line in consecutive frames joined into one showing (a line the
* reader garbled a little in one frame still joins its neighbours); then the showings that are captions: short, and
* fitting what's said while they're up with few edits. A badge, an app's screen, a sign or an end card stays up or
* says something else. With captions up for under TRACK of the speech, the cut has none to hold */
export function captionsOf(frames: Frame[], rate: number, heard: Word[]): Shown[] {
const all: (Shown & { caps: boolean })[] = []
frames.forEach((fr, i) => {
const t = i / rate
// a frame full of text is a screen or a card (an app, an end card, a product's label), not a caption over the picture
if (fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 4).length > BUSY) return
for (const [, y, , h, text, score] of fr.lines) {
const key = letters(text)
if (score < LEAST || key.length < 4) continue
const mid = (y + h / 2) / Math.max(1, fr.h)
const last = all.findLast((s) => s.to >= t - 1.01 / rate && Math.abs(s.y - mid) <= ROW && similar(s.key, key))
if (last) {
last.to = t + 1 / rate
// the longest reading of the line is kept (a frame mid-fade reads part of it)
if (key.length > last.key.length) Object.assign(last, { text, key })
} else all.push({ text, key, from: t, to: t + 1 / rate, y: mid, caps: false })
}
})
const caps = (t: string) => /[A-Z]/.test(t) && !/[a-z]/.test(t)
const fitted = all.filter((s) => {
if (s.to - s.from > HELD) return false
const said = heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join("")
return fit(s.key, said).dist / s.key.length <= (caps(s.text) ? CAPS_FIT : FIT)
}).map(({ caps: _, ...s }) => s)
// kept to caption rows: where three captions or more sit (a label beside a product, a sign, sits on its own)
const rowed = fitted.filter((s) => fitted.filter((o) => Math.abs(o.y - s.y) <= ROW).length >= 3)
const talk = heard.filter((w) => !FILLER.has(letters(w.text)))
const out = rowed
const up = talk.filter((w) => out.some((s) => w.end >= s.from - 0.3 && w.start <= s.to + 0.3)).length
// and a sequence: captions come one after another (CARDS showings at least, each starting apart), where hook text
// that echoes the host is one card of a few lines at once
const starts = [...new Set(out.map((s) => Math.round(s.from * 2)))].sort((a, b) => a - b)
const cards = starts.filter((x, i) => i === 0 || x - starts[i - 1] >= 1).length
if (!talk.length || up / talk.length < TRACK || cards < CARDS) return []
return out.sort((a, b) => a.from - b.from)
}
export const similar = (a: string, b: string) => {
const [s, l] = a.length <= b.length ? [a, b] : [b, a]
return fit(s, l).dist / Math.max(1, s.length) <= 0.25 && s.length / l.length >= 0.6
}
/** letters [i, j) of a line's key are a whole word of the line as read (its spaces kept) */
function wholeWord(text: string, key: string, i: number, j: number): boolean {
let k = 0
for (const w of text.split(/\s+/)) {
const lw = letters(w)
if (k === i && k + lw.length === j) return true
k += lw.length
}
return false
}
/** the captions held to what's heard: letters shown that weren't said, and words said that no caption up then shows */
export function compare(shown: Shown[], heard: Word[]): Finding[] {
if (!shown.length) return []
const out: Finding[] = []
// shown, not said: a run of three letters or more in a caption that the stretch of speech it fits doesn't have
for (const s of shown) {
const f = fit(s.key, heardIn(heard, s.from - 0.8, s.to + 0.4).map((w) => letters(w.text)).join(""))
for (let i = 0; i < f.bad.length; ) {
if (!f.bad[i]) { i++; continue }
let j = i
while (j < f.bad.length && f.bad[j]) j++
if (j - i >= 3) out.push({ level: (j - i >= 5 || wholeWord(s.text, s.key, i, j)) && !SOFT.has(s.key.slice(i, j)) ? "error" : "warn", kind: "shown", at: s.from, says: `the caption "${s.text}" at ${s.from.toFixed(1)} s shows "${s.key.slice(i, j)}", which isn't said there: a caption is the speaker's exact words, built from the words file, never retyped` })
i = j
}
}
// said, not shown: a heard word while a caption is up whose letters none of the captions up around it holds
const dropped: { w: Word; k: number }[] = []
heard.forEach((w, k) => {
const key = letters(w.text)
if (!key || FILLER.has(key)) return
const up = shown.filter((s) => w.end >= s.from - 0.6 && w.start <= s.to + 0.3)
if (!up.length) return
const near = shown.filter((s) => w.end >= s.from - 2 && w.start <= s.to + 1.5).map((s) => s.key).join("")
const allowed = key.length >= 5 ? 1 : 0
if (fit(key, near).dist > allowed) dropped.push({ w, k })
})
// read two frames a second, a caption up for under a second can be missed between frames: words dropped are held as
// errors only where the captions are phrases (up a second or more, typically), and only three or more in a row
const lasts = shown.map((x) => x.to - x.from).sort((x, y) => x - y)
const phrases = lasts[Math.floor(lasts.length / 2)] >= 1
// a run inside captioned speech (the words either side of it are shown, within a line of it) is words a caption
// left out: an error. A run at a line's edge is a line left uncaptioned, which an editor may mean (the CTA under its
// badges): a warning
const lost = new Set(dropped.map((d) => d.k))
const shownAt = (k: number) => k >= 0 && k < heard.length && !lost.has(k) && shown.some((s) => heard[k].end >= s.from - 0.6 && heard[k].start <= s.to + 0.3)
for (let i = 0; i < dropped.length; ) {
let j = i + 1
while (j < dropped.length && dropped[j].k === dropped[j - 1].k + 1) j++
const run = dropped.slice(i, j).map((d) => d.w)
const a = dropped[i].k - 1
const b = dropped[j - 1].k + 1
const inside = phrases && run.length >= 3 && shownAt(a) && shownAt(b) && run[0].start - heard[a].end < LINE && heard[b].start - run[run.length - 1].end < LINE
const words = run.map((w) => w.text).join(" ")
out.push(inside
? { level: "error", kind: "dropped", at: run[0].start, says: `"${words}" is said at ${run[0].start.toFixed(1)} s, between words the captions show, but no caption shows ${run.length > 1 ? "them" : "it"}: build the captions from the words file so they say every word` }
: { level: "warn", kind: "dropped", at: run[0].start, says: `"${words}" at ${run[0].start.toFixed(1)} s has no caption while the captions around it run: caption it from the words file, unless it's meant to go uncaptioned` })
i = j
}
return out.sort((a, b) => a.at - b.at)
}
export default check<FileFacts>(
{ id: "captions", text: "every caption on screen says exactly what's heard there, no word added, changed or left out", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const heard = await f.words()
if (!heard.length) return
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((f) => f.lines.length) && sc.scenes.some((s) => s && s.texts === undefined)) return void found({ level: "note", says: "the scene reader here doesn't read text yet, so the captions weren't held to what's heard" })
const shown = captionsOf(frames, sc.rate || 2, heard)
for (const x of compare(shown, heard)) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+82
View File
@@ -0,0 +1,82 @@
// The hook and air-gap packs (11-30, Shane), on the export's own words and levels.
//
// hook: the first seconds have sound and picture working together. Elfster's Voted cut opened on 1.5 s of whiteboard
// with nothing said (-27 dB): "a whiteboard people will read as the hook ... that's not a hook, a hook really should
// have audio and video stimulation". The first word later than LEAD_ERROR into the cut, with nothing loud under the
// opening either, is an error; later than LEAD_WARN, a warning. Sound alone (a hit, a song's first beat) under a
// wordless opening is a warning, to be decided, not an error.
// airgaps: the silences between words. "Measuring and cutting air gaps ... especially in a hook ... for social media
// content or ads, especially if it is at all trying to look organic." In the hook's first HOOK seconds a gap over
// HOOK_ERROR is an error and over HOOK_WARN a warning; later, one over BODY_WARN is a warning. The fix is raea's
// tighten() (@raea/video airgaps), which cuts only between words and never into one.
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { airGaps } from "../../../video/src/airgaps.ts"
/** the first word this late (s): an error with a quiet opening, a warning */
export const LEAD_ERROR = 1.0
export const LEAD_WARN = 0.5
/** the opening counts as carrying sound when its loud end is within this of the speech's (dB) */
const OPENING_LOUD = 10
/** the hook's seconds, and the gaps held in them (s) */
export const HOOK = 3
export const HOOK_ERROR = 0.5
export const HOOK_WARN = 0.3
/** a gap this long after the hook (s): a warning */
export const BODY_WARN = 0.8
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))]
}
export type HookFinding = { level: "error" | "warn"; at: number; says: string }
/** the opening and the gaps, from the words heard and the levels every 10 ms */
export function hookAndGaps(words: { text: string; start: number; end: number }[], db: number[]): { hook: HookFinding[]; gaps: HookFinding[] } {
const hook: HookFinding[] = []
const gaps: HookFinding[] = []
if (words.length < 3) return { hook, gaps }
const first = words[0].start
const speech = pct(words.flatMap((w) => db.slice(Math.floor(w.start * 100), Math.ceil(w.end * 100))), 0.8)
const opening = pct(db.slice(0, Math.max(1, Math.floor(first * 100))), 0.8)
const loud = opening > speech - OPENING_LOUD
if (first > LEAD_WARN + 0.005) {
const level = first > LEAD_ERROR && !loud ? "error" : "warn"
hook.push({
level,
at: 0,
says: loud
? `the first word comes ${first.toFixed(1)} s in, over sound alone (${opening.toFixed(0)} dB against the speech's ${speech.toFixed(0)}): a hook has words and picture together from the first frame, so open on the first line unless the sound is the hook`
: `${first.toFixed(1)} s of dead air before the first word ("${words[0].text}"), the opening ${(speech - opening).toFixed(0)} dB under the speech: a hook has sound and picture working together from the first frame. Open on the first line (cut the silent lead-in, or have the line land over the opening shot); a sign or a board people are meant to read is not a hook`,
})
}
for (const g of airGaps(words.map((w) => ({ text: w.text, start: w.start, end: w.end })), HOOK)) {
if (g.from === 0) continue // the lead-in is the hook pack's
const inHook = g.from < HOOK
const over = (x: number) => g.seconds > x + 0.005 // a transcript's times land on 10 ms steps
const level = inHook ? (over(HOOK_ERROR) ? "error" : over(HOOK_WARN) ? "warn" : null) : over(BODY_WARN) ? "warn" : null
if (!level) continue
gaps.push({ level, at: g.from, says: `${g.seconds.toFixed(2)} s of air between "${g.after}" and "${g.before}" at ${g.from.toFixed(1)} s${inHook ? " in the hook" : ""}: tighten it to about ${inHook ? 0.15 : 0.25} s with tighten() (raea's air-gap cut: between words only, never into one), unless the pause is the beat` })
}
return { hook, gaps }
}
export const hookPack = check<FileFacts>(
{ id: "hook", text: "the hook opens on words and picture together, no dead air", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const heard = await f.words()
for (const x of hookAndGaps(heard, f.levels().db).hook) found({ level: x.level, says: x.says, seconds: x.at })
},
)
export const airgapsPack = check<FileFacts>(
{ id: "airgaps", text: "no air between words: tight in the hook, no long pause after", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const heard = await f.words()
for (const x of hookAndGaps(heard, f.levels().db).gaps) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+11 -2
View File
@@ -1,6 +1,7 @@
// raea's packs by name (contract.ts PACKS says what each holds a job to).
import type { Check } from "raea/check"
import type { PackName } from "../contract.ts"
import captions from "./captions.ts"
import { countPack, ctaPack, neverPack, openPack, quotesPack, sayOncePack, sayPack, shapePack } from "./cut.ts"
import { floorPack, stillsPack } from "./floor.ts"
import frames from "./frames.ts"
@@ -10,13 +11,21 @@ import { criticPack, deliverablesPack, notesPack, recordPack } from "./job.ts"
import { seenPack, surprisePack } from "./look.ts"
import naming from "./naming.ts"
import place from "./place.ts"
import sizes from "./sizes.ts"
import sizes, { allSizes } from "./sizes.ts"
import sound from "./sound.ts"
import reading from "./reading.ts"
import { airgapsPack, hookPack } from "./hook.ts"
import voice from "./voice.ts"
import words from "./words.ts"
/** each pack's checks (say holds each cut, and the phrases one cut is enough for across them) */
export const PACK_CHECKS: Record<PackName, Check[]> = {
words: [words],
captions: [captions],
voice: [voice],
reading: [reading],
hook: [hookPack],
airgaps: [airgapsPack],
sound: [sound],
frames: [frames],
montage: [montage],
@@ -24,7 +33,7 @@ export const PACK_CHECKS: Record<PackName, Check[]> = {
seen: [seenPack],
surprise: [surprisePack],
naming: [naming],
sizes: [sizes],
sizes: [sizes, allSizes],
quotes: [quotesPack],
count: [countPack],
open: [openPack],
+3 -1
View File
@@ -18,7 +18,9 @@ import type { FileFacts } from "../facts.ts"
import { RATE } from "../media.ts"
/** 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
/** the scene reader's reading of a frame's text: [x, y, w, h, text, score] a line (the captions pack) */
export type TextLine = [number, number, number, number, string, number]
export type Scene = { w: number; h: number; grid: { cols: number; rows: number; people: string[] }; things: Thing[]; faces: Thing[]; texts?: TextLine[] } | 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 */
+120
View File
@@ -0,0 +1,120 @@
// The reading pack (11-30, Shane: "the words on screen relative to duration ... if a wordy CTA or component or scene is
// meant to be fully read or if it just adds glossable content or context, and if it's on screen long enough to be
// read"). From the scene reader's text (the farm's texts, two frames a second), every block of text that isn't a
// caption (captions are read while they're heard: the captions pack holds them) is timed against the words it holds.
//
// time to read: READ_BASE s to find it, then WPS words a second (a feed viewer's skim of short ad text; subtitle
// standards sit near 3 words a second). A block up for under its time is a warning; under SHORT of it an error,
// unless it holds GLOSS words or more: a screen, fine print or a dense card can't be read in an ad anyway, so it's
// texture, and the finding asks which it is meant to be.
// the measure: every finding says words, seconds and words a second, so a CTA's reading load is a number the
// editor holds (and the skill's end card rule: few words, held long enough).
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
import { captionsOf, fit, type Frame, LEAST, letters, type Read, similar } from "./captions.ts"
export type Block = { text: string; words: number; from: number; to: number; size?: number }
export type Finding = { level: "error" | "warn"; at: number; says: string; block: Block }
/** seconds to find a block before reading it */
export const READ_BASE = 0.5
/** words read a second */
export const WPS = 3
/** under this share of its time to read, an error */
export const SHORT = 0.6
/** a block of this many words or more is texture unless the editor means it read */
export const GLOSS = 25
/** fewer words than this is a logo, a label or a button, read at a glance */
const FEW = 4
const wordsIn = (t: string) => t.split(/\s+/).filter((w) => letters(w).length > 0).length
/** the time a block of `words` needs on screen */
export const need = (words: number) => READ_BASE + words / WPS
/** a frame with more lines read than this is a screen, a shelf or a page (an app shot whole, a product line-up's
* labels): texture by nature, left out */
export const SCREEN = 6
/** lines whose middles are this close (a share of the frame's height) in consecutive frames are one line */
const ROW = 0.03
/** lines that come up within this of each other (s), up together, are one block */
const TOGETHER = 0.6
/** a line that fits what's said around it with at most this share of its letters edited is read with the voice */
const SAID = 0.35
/** a phone's status bar clock: the block is an app's screen, shown, not read */
/** text this small (its lines' median height, a share of the frame's) is an app's screen or fine print, not a
* designed line: 1080x1920's 54 px */
const SMALL = 0.028
const CLOCK = /\d{1,2}:\d{2}/
/** the frames' blocks of text. Each line that isn't a caption is followed from frame to frame (same row, same text,
* its fullest reading kept: text building on, or a frame mid-fade); lines that come up together and overlap are one
* block, read as one. Frames that are screens are left out */
export function blocksOf(frames: Frame[], rate: number, isCaption: (t: number, key: string) => boolean, heard: Word[] = []): Block[] {
type Line = { text: string; key: string; from: number; to: number; y: number; size: number }
const lines: Line[] = []
frames.forEach((fr, i) => {
const t = i / rate
const read = fr.lines.filter(([, , , , text, score]) => score >= LEAST && letters(text).length >= 2)
if (read.length > SCREEN) return
for (const [, y, , h, text] of read) {
const key = letters(text)
if (isCaption(t, key)) continue
// words shown as they're said (kinetic type, a caption the captions pack didn't take as one) are read with the voice
const said = heard.filter((w) => w.end >= t - 1.5 && w.start <= t + 2.5).map((w) => letters(w.text)).join("")
if (key.length >= 4 && fit(key, said).dist / key.length <= SAID) continue
const mid = (y + h / 2) / Math.max(1, fr.h)
const last = lines.findLast((l) => l.to >= t - 1.01 / rate && Math.abs(l.y - mid) <= ROW && (similar(l.key, key) || l.key.includes(key) || key.includes(l.key)))
if (last) {
last.to = t + 1 / rate
if (key.length > last.key.length) Object.assign(last, { text, key })
} else lines.push({ text, key, from: t, to: t + 1 / rate, y: mid, size: h / Math.max(1, fr.h) })
}
})
const blocks: (Block & { parts: Line[] })[] = []
for (const l of [...lines].sort((a, b) => a.from - b.from || a.y - b.y)) {
const b = blocks.find((x) => Math.abs(x.from - l.from) <= TOGETHER && l.from < x.to)
if (b) {
b.parts.push(l)
b.to = Math.max(b.to, l.to)
} else blocks.push({ text: "", words: 0, from: l.from, to: l.to, parts: [l] })
}
return blocks.map(({ parts, ...b }) => {
const text = parts.sort((x, y) => x.y - y.y).map((x) => x.text).join(" ")
// a block is read for as long as most of it is up: its lines' median time up
const ups = parts.map((x) => x.to - x.from).sort((x, y) => x - y)
const sizes = parts.map((x) => x.size).sort((x, y) => x - y)
return { ...b, text, words: wordsIn(text), to: b.from + ups[Math.floor(ups.length / 2)], size: sizes[Math.floor(sizes.length / 2)] }
})
}
/** blocks up for less time than their words take to read */
export function reading(blocks: Block[]): Finding[] {
const out: Finding[] = []
for (const b of blocks) {
if (b.words < FEW) continue
const up = b.to - b.from
const n = need(b.words)
if (up >= n) continue
const quote = b.text.length > 70 ? `${b.text.slice(0, 67)}...` : b.text
const load = `${b.words} words up ${up.toFixed(1)} s (${(b.words / up).toFixed(1)} words a second; reading takes about ${n.toFixed(1)} s at ${WPS} a second)`
if (b.words >= GLOSS || CLOCK.test(b.text) || (b.size !== undefined && b.size < SMALL)) out.push({ level: "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. That's texture, not reading (a screen, a page, fine print): fine if it's shown for context, but if a viewer is meant to read it, cut it to the words that matter and hold them ${need(Math.min(b.words, 8)).toFixed(1)} s or more` })
else out.push({ level: up < n * SHORT ? "error" : "warn", at: b.from, block: b, says: `"${quote}" at ${b.from.toFixed(1)} s: ${load}. Hold it ${(n - up).toFixed(1)} s longer, or say it in fewer words` })
}
return out
}
export default check<FileFacts>(
{ id: "reading", text: "every block of text on screen that isn't a caption is up long enough to read (half a second, then 3 words a second), or is plainly texture", over: "file", at: ["render", "publish", "done"], needs: ["words", "scene"] },
async (f) => {
if (!f.made || f.kind !== "video") return
const sc = await f.scene()
const frames: Frame[] = sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
if (!frames.some((x) => x.lines.length)) return
const rate = sc.rate || 2
const heard = await f.words()
const caps = captionsOf(frames, rate, heard)
const isCaption = (t: number, key: string) => caps.some((c) => t >= c.from - 0.01 && t < c.to && (similar(c.key, key) || c.key.includes(key)))
for (const x of reading(blocksOf(frames, rate, isCaption, heard))) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+38 -1
View File
@@ -3,9 +3,13 @@
// (11-28, Shane: "always does all concepts first in one size or aspect ratio ... and then once approved we can then do
// any other resizes ... generally lean toward 9:16 first"). The approval is the brief's `open` item about "sizes",
// answered by the person (`by`).
// And every size by the end (11-30, Shane: "it will show completed but what about doing all the resizes"): Dutch
// finished on its 9:16 masters alone, the brief's 4:5, 1:1 and 16:9 never made. At done, every ad's newest version is
// there in every format its brief names (brief.ts cut `formats`), unless a person's answer to the open item about "sizes"
// says fewer.
import { check, found } from "raea/check"
import type { Job } from "../facts.ts"
import { bookkeeping, sizeOf } from "./naming.ts"
import { adOf, bookkeeping, sizeOf } from "./naming.ts"
export default check<Job>({ id: "sizes", text: "one size first: no other size before the first is approved", over: "job", at: ["render", "publish", "done"] }, async (j) => {
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image"))
@@ -24,3 +28,36 @@ export default check<Job>({ id: "sizes", text: "one size first: no other size be
fix: `finish and show every ad in ${first[0]} first; recut the other sizes from the approved version once a person answers the brief's open item about "sizes" (with \`by\`)`,
})
})
/** a format as a name's size: "9:16" is 9x16 */
const asSize = (f: string) => f.replace(":", "x").toLowerCase()
/** a version's number in a name (v3), else 0 */
const versionOf = (name: string) => Number(/_v(\d+)(?=_|\.|$)/i.exec(name)?.[1] ?? 0)
export const allSizes = check<Job>({ id: "sizes-all", text: "every size the brief asks for, by the end", over: "job", at: ["done"] }, async (j) => {
if (j.contract?.kind !== "cut") return
const c = j.contract.cut
const want = [...new Set([...(c?.formats ?? []), ...(c?.cuts ?? []).flatMap((p) => p.formats ?? [])].map(asSize))]
if (want.length < 2) return
const sizesItem = (c?.open ?? []).find((o) => o.about === "sizes" && o.answer?.trim() && o.by?.trim())
// a person said which sizes (or that one is enough): only the sizes their answer names
const wanted = sizesItem ? want.filter((s) => new RegExp(s.replace("x", "[:x]"), "i").test(sizesItem.answer ?? "")) : want
if (wanted.length < 2) return
const made = j.files.filter((f) => f.made && !bookkeeping(f.path) && (f.kind === "video" || f.kind === "image") && sizeOf(f.path))
// each ad at its newest version, and the sizes that version is in
const ads = new Map<string, { v: number; sizes: Set<string> }>()
for (const f of made) {
const ad = adOf(f.path), v = versionOf(f.path), s = sizeOf(f.path)!
const cur = ads.get(ad)
if (!cur || v > cur.v) ads.set(ad, { v, sizes: new Set([s]) })
else if (v === cur.v) cur.sizes.add(s)
}
for (const [ad, { v, sizes }] of ads) {
const missing = wanted.filter((s) => !sizes.has(s))
if (!missing.length) continue
found({
says: `${ad} v${v} is in ${[...sizes].join(", ")} but the brief asks for ${wanted.join(", ")}: ${missing.join(", ")} not made`,
fix: `recut ${ad} v${v} in ${missing.join(", ")} from the approved version (same version, a new size: ${ad}_v${v}_${missing[0]}), check each, and deliver them before you finish; a person's answer to the brief's open item about "sizes" is the only way to deliver fewer`,
})
}
})
+17 -3
View File
@@ -36,13 +36,26 @@ const LEVEL_WARN = 4
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
const MUSIC_FIGHTS = 10
export type Finding = { level: "error" | "warn"; kind: "edit-in-word" | "edit-on-sound" | "level" | "effect-unheard" | "music" | "manifest"; at: number | null; says: string }
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")
/** a sound with no bus, as raea's default mix routes it (systems/mix default_bus, 11-30): footage and voice files are the
* talking, effects stay effects, any other audio file is the music, ducked DEFAULT_DUCK under the talking */
const VIDEO_EXT = /\.(mp4|mov|m4v|webm|mkv|avi|mxf)$/i
const VOICE_NAME = /voice|narrat|dialog|speech|_vo|vo_|-vo|vo-|interview/i
const SFX_NAME = /sfx|foley|whoosh|swoosh|sting|riser|impact|click|_fx|fx_/i
export const busOf = (c: Clip): "voice" | "music" | "sfx" => {
if (c.bus) return MUSIC.test(c.bus) ? "music" : SFX.test(c.bus) ? "sfx" : "voice"
const name = path.basename(c.src)
if (VIDEO_EXT.test(name) || VOICE_NAME.test(name)) return "voice"
if (SFX_NAME.test(name) || SFX.test(name)) return "sfx"
return "music"
}
/** how far raea's default mix ducks a music file with no bus under the talking (dB, systems/mix DEFAULT_DUCK_DB) */
export const DEFAULT_DUCK = -6
const pct = (xs: number[], q: number) => {
if (!xs.length) return -100
@@ -165,7 +178,8 @@ export function balance(heard: Heard[], fps: number): Finding[] {
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
// a music file on no bus is ducked under the talking by the default mix, so it's heard that much lower
const d = h.level - mid + (h.clip.bus ? 0 : DEFAULT_DUCK)
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)}` })
}
+96
View File
@@ -0,0 +1,96 @@
// The voice pack (11-30, Shane: "we should be checking audio if its too quiet for dialogue or what is supposed to be
// primary"): whether the dialogue is on top in the export as it was mixed, measured on the export itself. The sound pack
// levels each line from its source take and the edit's gains, before the mix: ducking, the limiter and the loudness pass
// all come after it, and a line that's even in the edit can sink in the mix.
//
// on top: the speech (the words pass's words, every 10 ms inside them) against what's under it in the gaps between
// words while people are talking (music, effects, the street): under 6 dB above it is an error (the bed is as loud
// as the voice), under 10 dB a warning.
// even: each line (words with less than 0.7 s between them) against the export's typical line: 6 dB or more quieter
// is an error (a line too quiet to follow that a transcriber still hears), 4 dB a warning.
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import type { Word } from "../media.ts"
export type Finding = { level: "error" | "warn"; kind: "buried" | "quiet"; at: number; says: string }
/** the speech's level over what's under it (dB): under ON_TOP_ERROR an error, under ON_TOP_WARN a warning */
export const ON_TOP_ERROR = 6
export const ON_TOP_WARN = 10
/** a line this far under the typical line (dB) */
export const QUIET_ERROR = 6
export const QUIET_WARN = 4
/** words this close together are one line (s) */
const LINE_GAP = 0.7
/** a gap between words counts as the bed from this far after a word to this far before the next (s): the word's tail
* and breath are left out */
const CLEAR = 0.12
/** a gap shorter than this is too short to read the bed in (s) */
const GAP_MIN = 0.2
/** the bed is judged only on this many gaps between words, this many 10 ms frames of them in all */
const BED_GAPS = 3
const BED_FRAMES = 100
/** the level a span is read at: its loud end (this percentile of its 10 ms frames), so pauses inside words don't count */
const Q = 0.8
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 frames = (db: number[], a: number, b: number) => db.slice(Math.max(0, Math.floor(a * 100)), Math.min(db.length, Math.ceil(b * 100)))
/** the lines: words with under LINE_GAP between them */
export function linesOf(heard: Word[]): Word[][] {
const out: Word[][] = []
for (const w of heard) {
const last = out[out.length - 1]
if (last && w.start - last[last.length - 1].end < LINE_GAP) last.push(w)
else out.push([w])
}
return out
}
/** the speech against the bed under it, and each line against the typical line */
export function voice(db: number[], heard: Word[]): Finding[] {
if (heard.length < 4) return []
const out: Finding[] = []
const speech: number[] = []
for (const w of heard) speech.push(...frames(db, w.start, w.end))
const bed: number[] = []
let gaps = 0
const lines = linesOf(heard)
// the gaps inside lines and between lines close together: what's under the talking, not the end card's music
for (let k = 1; k < heard.length; k++) {
const a = heard[k - 1].end + CLEAR
const b = heard[k].start - CLEAR
if (b - a >= GAP_MIN && b - a < 2.5) { bed.push(...frames(db, a, b)); gaps++ }
}
const S = pct(speech, Q)
// enough of the bed to judge: a tightly cut take has few gaps, and one of them is often still a hum or a breath
// (11-30: Body Shop's host hook read 1.5 dB off a single 0.34 s gap between two "Mmm"s)
if (gaps >= BED_GAPS && bed.length >= BED_FRAMES) {
const B = pct(bed, Q)
const over = S - B
if (over < ON_TOP_WARN) out.push({ level: over < ON_TOP_ERROR ? "error" : "warn", kind: "buried", at: heard[0].start, says: `the dialogue is only ${over.toFixed(1)} dB above what's under it between words (music, effects, the street): it should be ${ON_TOP_WARN} dB or more on top. Duck the music further under the voice, or lift the voice` })
}
const lv = lines.map((l) => ({ l, db: pct(frames(db, l[0].start, l[l.length - 1].end), Q) }))
const typical = pct(lv.map((x) => x.db), 0.5)
for (const { l, db: d } of lv) {
const under = typical - d
if (under < QUIET_WARN || l.length < 2) continue
const text = l.map((w) => w.text).join(" ")
out.push({ level: under >= QUIET_ERROR ? "error" : "warn", kind: "quiet", at: l[0].start, says: `"${text.length > 60 ? `${text.slice(0, 57)}...` : text}" at ${l[0].start.toFixed(1)} s is ${under.toFixed(1)} dB quieter than the other lines: lift it about ${under.toFixed(0)} dB so it's heard like the rest` })
}
return out.sort((a, b) => a.at - b.at)
}
export default check<FileFacts>(
{ id: "voice", text: "the dialogue on top of the mix in the export, every line as loud as the others", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
if (!f.made || (f.kind !== "video" && f.kind !== "audio")) return
const heard = await f.words()
if (!heard.length) return
for (const x of voice(f.levels().db, heard)) found({ level: x.level, says: x.says, seconds: x.at })
},
)
+72
View File
@@ -0,0 +1,72 @@
import { expect, test } from "bun:test"
import { captionsOf, compare, fit, letters } from "../src/packs/captions.ts"
import { voice } from "../src/packs/voice.ts"
// what the reader saw, two frames a second: phrase captions in one row (y 120 of 960), as Elfster's cut 1 had them
const w = (text: string, start: number, end: number) => ({ text, start, end })
const said = "Everyone has a fake I love it face when they get a bad gift. How bad is yours? Thanks. Oh my, like how did you know? Now I know for sure, okay, this is what they wanted, and everyone's happy."
.split(" ").map((t, i) => w(t, 0.2 + i * 0.3, 0.45 + i * 0.3))
const at = (t: number) => said.find((x) => x.start <= t && x.end >= t)
const shownLines: [number, number, string][] = [
[0.1, 1.4, "Everyone has a fake"], [1.4, 2.6, "'I love it' face"], [2.6, 3.8, "for a bad gift."], [3.8, 5.0, "How bad is yours?"],
[5.0, 5.9, "Oh, thanks!"], [5.9, 7.1, "Oh my god,"], [7.1, 8.6, "like, how did you know?"], [8.6, 9.6, "Now I know for sure"],
[9.6, 11.4, "what they wanted,"], [11.4, 12.6, "and everyone's happy."],
]
const frames = Array.from({ length: 27 }, (_, i) => {
const t = i / 2
const l = shownLines.find(([a, b]) => t >= a && t < b)
return { h: 960, lines: l ? [[60, 110, 420, 26, l[2], 0.95] as [number, number, number, number, string, number]] : [] }
})
test("a caption is fitted to the stretch of speech it says", () => {
expect(fit("forabadgift", letters("when they get a bad gift")).dist).toBe(3)
// a badge in capitals that echoes the line ("BODY BUTTER · UP TO 96") is held to the stricter fit (0.3), and misses it
expect(fit("bodybutterupto96", letters("body butter delivers up to 96 hours")).dist / 16).toBeGreaterThan(0.3)
})
test("captions that change or drop words are found; the same words pass", () => {
void at
const shown = captionsOf(frames, 2, said)
expect(shown.length).toBeGreaterThanOrEqual(8)
const f = compare(shown, said)
// "for" stands in for "get", "god" was never said
expect(f.some((x) => x.kind === "shown" && x.says.includes("god"))).toBe(true)
// "when they" (before "get"), and "okay, this is" between captioned words, are dropped
expect(f.some((x) => x.kind === "dropped" && x.level === "error" && x.says.includes("okay, this is"))).toBe(true)
// captions that say exactly what's said find nothing
const exact = said.reduce<[number, number, string][]>((a, x, i) => (i % 4 === 0 ? [...a, [x.start, said[Math.min(i + 3, said.length - 1)].end, said.slice(i, i + 4).map((y) => y.text).join(" ")]] : a), [])
const fr2 = Array.from({ length: 27 }, (_, i) => {
const t = i / 2
const l = exact.find(([a, b]) => t >= a && t < b)
return { h: 960, lines: l ? [[60, 110, 420, 26, l[2], 0.95] as [number, number, number, number, string, number]] : [] }
})
expect(compare(captionsOf(fr2, 2, said), said).filter((x) => x.level === "error")).toEqual([])
})
test("hook text alone isn't a caption track", () => {
const hook = Array.from({ length: 27 }, (_, i) => ({ h: 960, lines: i < 6 ? [[60, 110, 420, 26, "Everyone has a fake 'I love it' face", 0.95] as [number, number, number, number, string, number]] : [] }))
expect(captionsOf(hook, 2, said)).toEqual([])
})
test("the voice pack: dialogue on top of the mix, every line even", () => {
const words = Array.from({ length: 25 }, (_, i) => w("word", 0.2 + i * 0.8, 0.5 + i * 0.8))
// speech at -20 dB, the bed between words at -40: 20 dB on top, nothing found
const level = (bed: number, quietFrom = 99) => Array.from({ length: 2100 }, (_, f) => {
const t = f / 100
const inWord = words.some((x) => t >= x.start && t < x.end)
return inWord ? (t >= quietFrom ? -29 : -20) : bed
})
expect(voice(level(-40), words)).toEqual([])
// the bed at -24 between words: 4 dB on top, buried
expect(voice(level(-24), words).some((x) => x.kind === "buried" && x.level === "error")).toBe(true)
// a line 9 dB quieter than the rest (words 15 on are one line with no gap > 0.7 s: all of them here, so split a line)
const two = [...words.slice(0, 20), ...words.slice(20).map((x) => ({ ...x, start: x.start + 1, end: x.end + 1 }))]
const lv = Array.from({ length: 2300 }, (_, f) => {
const t = f / 100
const x = two.find((y) => t >= y.start && t < y.end)
return x ? (two.indexOf(x) >= 20 ? -29 : -20) : -45
})
const third = [...two, ...words.slice(0, 10).map((x) => ({ ...x, start: x.start + 23, end: x.end + 23 }))]
const lv3 = [...lv, ...Array.from({ length: 600 }, (_, f) => (third.slice(40).some((y) => (2300 + f) / 100 >= y.start && (2300 + f) / 100 < y.end) ? -20 : -45))]
expect(voice(lv3, third).some((x) => x.kind === "quiet" && x.level === "error")).toBe(true)
})
+1 -1
View File
@@ -17,7 +17,7 @@ test("a cut holds the craft by default, surprise only when asked", () => {
expect(packsOf(rules({ aim: "x", rules: [{ id: "t", run: "true" }, { id: "w", says: "it reads" }] }))).toEqual(["deliverables", "stills", "run", "says"])
expect(packsOf(cut({ cut: { brief: "b.txt" }, rules: [{ id: "t", run: "true" }] }))).toContain("run")
// no contract: the floor every made video is held to
expect(packsOf(null)).toEqual(["frames", "floor", "seen", "stills"])
expect(packsOf(null)).toEqual(["frames", "captions", "voice", "reading", "hook", "airgaps", "floor", "seen", "stills"])
})
test("a project's own check runs at its moments", async () => {
+1 -1
View File
@@ -14,7 +14,7 @@ beforeAll(() => {
const BRIEF = 'Deliverables: 10 total videos (4 solos / 1 mashup per angle).\nUse the phrase "free, fun, and easy."\nDon\'t let it read as White Elephant.\nEnd on the CTA: "Make your Wishlist and organize your Gift Exchange on Elfster. It\'s free."\nCTV specs from the client [TO CONFIRM]\n'
const contract = (cut: Record<string, unknown> = {}) => ({
kind: "cut",
packs: { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, sizes: false },
packs: { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, sizes: false, hook: false, airgaps: false },
cut: {
brief: "media/brief.txt",
count: { value: 2, from: "10 total videos" },
+54
View File
@@ -0,0 +1,54 @@
// The hook and air-gap packs, and @raea/video's tighten() they point to (11-30, Shane): no dead air before the first
// word, tight gaps in the hook, and a cut that only ever lands between words.
import { expect, test } from "bun:test"
import { hookAndGaps } from "../src/packs/hook.ts"
import { airGaps, tighten } from "../../video/src/airgaps.ts"
const W = (spec: [string, number, number][]) => spec.map(([text, start, end]) => ({ text, start, end }))
/** levels every 10 ms: `on` dB inside the words, `off` between them */
const levels = (words: { start: number; end: number }[], secs: number, on = -18, off = -50) =>
Array.from({ length: Math.ceil(secs * 100) }, (_, i) => (words.some((w) => i / 100 >= w.start && i / 100 < w.end) ? on : off))
test("Voted's opening: 1.5 s of a silent whiteboard before the first word is dead air", () => {
const words = W([["Do", 1.54, 1.6], ["you", 1.6, 1.76], ["use", 1.76, 2.0], ["Elfster?", 2.0, 2.46]])
const { hook } = hookAndGaps(words, levels(words, 4))
expect(hook).toHaveLength(1)
expect(hook[0].level).toBe("error")
expect(hook[0].says).toMatch(/1\.5 s of dead air/)
})
test("a cut that talks from its first frame has no hook finding; sound under a late first word is only a warning", () => {
const now = W([["Every", 0.08, 0.3], ["friend", 0.3, 0.6], ["group", 0.6, 0.9]])
expect(hookAndGaps(now, levels(now, 2)).hook).toEqual([])
const late = W([["So", 1.2, 1.4], ["good", 1.4, 1.7], ["really", 1.7, 2.0]])
const db = levels(late, 3).map((d, i) => (i < 120 ? -20 : d)) // a song's first beat under the opening
expect(hookAndGaps(late, db).hook[0].level).toBe("warn")
})
test("gaps: tight in the hook, only long ones after it", () => {
const words = W([["I", 0.0, 0.2], ["use", 0.8, 1.0], ["it", 1.35, 1.5], ["every", 5.0, 5.3], ["Christmas", 6.5, 7.0], ["really", 7.3, 7.6]])
const { gaps } = hookAndGaps(words, levels(words, 8))
expect(gaps.map((g) => [g.level, +g.at.toFixed(1)])).toEqual([["error", 0.2], ["warn", 1.0], ["error", 1.5], ["warn", 5.3]])
})
test("tighten() cuts only between words, leaves a pad on each, and the lead-in down to a pad", () => {
const words = W([["Do", 1.54, 1.6], ["you", 1.6, 1.76], ["use", 1.76, 2.0], ["Elfster?", 2.0, 2.46], ["I", 3.4, 3.5], ["do", 3.5, 3.7]])
const { keep, cuts } = tighten(words)
expect(cuts[0]).toEqual({ from: 0, to: 1.46 })
// every word lies whole inside what's kept
for (const w of words) expect(keep.some((k) => k.from <= w.start - 0.079 && k.to >= w.end + 0.079 - 1e-9 || (k.from <= w.start && k.to >= w.end))).toBe(true)
// the 0.94 s gap after "Elfster?" (past the 3 s hook? no: it starts at 2.46) is left at the hook's 0.16 s
const left = airGaps(words).find((g) => g.after === "Elfster?")!
const taken = cuts.filter((c) => c.from >= left.from && c.to <= left.to).reduce((n, c) => n + c.to - c.from, 0)
expect(+(left.seconds - taken).toFixed(2)).toBe(0.16)
})
test("tighten() with levels never cuts where it's still loud: a word the transcript ended early stays whole", () => {
// "gifts" is heard to 2.3 s but the transcript ends it at 2.0
const words = W([["buy", 1.0, 1.4], ["gifts", 1.5, 2.0], ["now", 3.0, 3.3]])
const db = levels(W([["buy", 1.0, 1.4], ["gifts", 1.5, 2.3], ["now", 3.0, 3.3]]), 4)
const { cuts } = tighten(words, { levels: db, lead: false })
const c = cuts.find((x) => x.from > 2)!
expect(c.from).toBeGreaterThanOrEqual(2.3)
expect(c.to).toBeLessThanOrEqual(3.0)
})
+35
View File
@@ -0,0 +1,35 @@
import { expect, test } from "bun:test"
import { blocksOf, need, reading } from "../src/packs/reading.ts"
type L = [number, number, number, number, string, number]
const line = (y: number, text: string, h = 48): L => [60, y, 420, h, text, 0.95]
const frames = (n: number, at: (t: number) => L[]) => Array.from({ length: n }, (_, i) => ({ h: 960, lines: at(i / 2) }))
const none = () => false
test("time to read: half a second, then 3 words a second", () => {
expect(need(6)).toBeCloseTo(2.5)
})
test("a wordy card up for a second is an error; held long enough, it passes", () => {
const card = [line(300, "How does your group do"), line(360, "Secret Santa this year?"), line(420, "Names in a hat or chaos")]
const quick = blocksOf(frames(10, (t) => (t < 1 ? card : [])), 2, none)
expect(quick.length).toBe(1)
expect(quick[0].words).toBe(15)
expect(reading(quick)[0].level).toBe("error")
expect(reading(blocksOf(frames(16, (t) => (t < 6 ? card : [])), 2, none))).toEqual([])
})
test("a phone's screen and small print are texture: a warning that asks, never an error", () => {
const screen = [line(40, "12:59", 18), line(300, "Awesome, your exchange is created! Invite everyone", 18)]
const f = reading(blocksOf(frames(6, (t) => (t < 0.5 ? screen : [])), 2, none))
expect(f.length).toBe(1)
expect(f[0].level).toBe("warn")
expect(f[0].says).toContain("texture")
})
test("a frame full of lines (a shelf of labels) is left out, and words said as they show are read with the voice", () => {
const shelf = Array.from({ length: 9 }, (_, i) => line(100 + i * 80, `Body Butter Mango ${i}`))
expect(blocksOf(frames(4, () => shelf), 2, none)).toEqual([])
const heard = "so good I want to eat it".split(" ").map((t, i) => ({ text: t, start: 0.2 + i * 0.3, end: 0.45 + i * 0.3 }))
expect(blocksOf(frames(4, (t) => (t < 0.5 ? [line(300, "SO GOOD I WANT TO EAT IT")] : [])), 2, none, heard)).toEqual([])
})
+33
View File
@@ -0,0 +1,33 @@
// The sizes pack's end (11-30, Shane: "it will show completed but what about doing all the resizes"): at done, every ad's
// newest version in every format the brief names, unless a person's answer about "sizes" says fewer.
import { beforeAll, expect, test } from "bun:test"
import { goalCheck } from "../src/run.ts"
import { CLIP, project, put } from "./project.ts"
import { readFileSync } from "node:fs"
beforeAll(() => {
process.env.RAEA_REAL = "/usr/bin/false"
delete process.env.RAEA_CLOUD_GPU_URL
})
const off = { words: false, sound: false, frames: false, place: false, floor: false, stills: false, seen: false, naming: false, captions: false, voice: false, reading: false, montage: false, quotes: false, count: false, open: false, say: false, never: false, cta: false, shape: false }
const contract = (open: unknown[] = []) => ({ kind: "cut", packs: off, cut: { brief: "media/brief.txt", formats: ["9:16", "4:5", "1:1"], cuts: [{ id: "a1" }], open } })
const clip = readFileSync(CLIP)
const all = async (open: unknown[] = [], files: string[]) => {
const d = project(contract(open))
put(d, "media/brief.txt", "Deliver 9:16, 4:5 and 1:1.\n")
for (const f of files) put(d, f, clip)
const r = await goalCheck({ cwd: d, at: "done" })
return r.findings.filter((x) => /sizes/.test(x.check))
}
test("done on the first size alone: every other size the brief names is missing", async () => {
const f = await all([], ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4", "out/cuts/dutch_vetbill_hooka_v1_9x16.mp4"])
expect(f.some((x) => /v2 is in 9x16 .* 4x5, 1x1 not made/.test(x.says))).toBe(true)
})
test("every size of the newest version passes; a person's answer can say fewer", async () => {
const sizes = ["9x16", "4x5", "1x1"].map((s) => `out/cuts/dutch_vetbill_hooka_v2_${s}.mp4`)
const answered = [{ question: "Which sizes?", from: "Deliver 9:16, 4:5 and 1:1.", about: "sizes", answer: "9:16 only for now", by: "shane" }]
expect((await all(answered, sizes)).filter((x) => x.check === "sizes-all")).toEqual([])
expect((await all(answered, ["out/cuts/dutch_vetbill_hooka_v2_9x16.mp4"])).filter((x) => x.check === "sizes-all")).toEqual([])
})
+1
View File
@@ -20,6 +20,7 @@
"./cutout": "./src/cutout.ts",
"./adjust": "./src/adjust.ts",
"./words": "./src/words.tsx",
"./airgaps": "./src/airgaps.ts",
"./region": "./src/region.tsx",
"./overlay": "./src/overlay.tsx",
"./panel": "./src/panel.ts",
+97
View File
@@ -0,0 +1,97 @@
// Air gaps: the silences between words, measured and cut safely (11-30, Shane: "measuring and cutting air gaps safely
// would be good, especially in a hook. It CANNOT destroy words as sometimes air gaps can, but generally having an
// automated air gap cleanup would be solid ... for social media content or ads, especially if it is at all trying to look
// organic").
//
// airGaps(words) every gap between words, with how long it is and whether it's in the hook
// tighten(words, options) the spans of the source to keep: each gap longer than allowed cut down to `pad` either side
// of its words, the lead-in before the first word too
//
// What keeps a word whole: a cut lies only between two words, never closer than `pad` to either; words that overlap or
// touch are never cut between; and with `levels` (the take's level every 10 ms, raea goal's levels()), each cut is pulled
// in from either end until it's quiet there, `quiet` dB under the speech, because a transcript's word ends are often
// early (a trailing "s", a breath into the next word) and that's how a cut clips a word.
/** a word as raea words writes it (start_ms, end_ms) or as seconds (start, end) */
export type GapWord = { text: string; start?: number; end?: number; start_ms?: number; end_ms?: number }
export type Span = { from: number; to: number }
export type Gap = Span & { seconds: number; hook: boolean; after: string; before: string }
export interface TightenOptions {
/** the longest gap left as it is, in the body (s): 0.25 by default, the pace of an edited social cut */
gap?: number
/** the hook's first seconds, where gaps are held tighter (s): 3 */
hook?: number
/** the longest gap left in the hook (s): 0.15 */
hookGap?: number
/** what's kept either side of a cut, so a word's onset and tail stay whole (s): 0.08 */
pad?: number
/** the shortest cut worth making (s): 0.06 */
least?: number
/** cut the silence before the first word down to `pad`: true (a hook starts on its first word) */
lead?: boolean
/** the source's level every 10 ms (dB): a cut ends where the sound is still within `quiet` dB of the speech */
levels?: number[]
/** how far under the speech counts as quiet (dB): 18 */
quiet?: number
}
const secs = (w: GapWord, k: "start" | "end") => (typeof w[k] === "number" ? (w[k] as number) : ((w[`${k}_ms`] as number | undefined) ?? 0) / 1000)
/** the words in time order, as seconds */
function timed(words: readonly GapWord[]) {
return words.map((w) => ({ text: w.text, start: secs(w, "start"), end: secs(w, "end") })).filter((w) => w.end > w.start).sort((a, b) => a.start - b.start)
}
/** every gap between two words (and the lead-in before the first), longest first not implied: in time order */
export function airGaps(words: readonly GapWord[], hook = 3): Gap[] {
const w = timed(words)
const out: Gap[] = []
if (w.length && w[0].start > 0) out.push({ from: 0, to: w[0].start, seconds: w[0].start, hook: true, after: "", before: w[0].text })
for (let i = 1; i < w.length; i++) {
const from = w[i - 1].end, to = w[i].start
if (to > from) out.push({ from, to, seconds: to - from, hook: from < hook, after: w[i - 1].text, before: w[i].text })
}
return out
}
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))]
}
/** the spans of the source to keep, and the cuts that make them; `saved` is the seconds taken out */
export function tighten(words: readonly GapWord[], o: TightenOptions = {}): { keep: Span[]; cuts: Span[]; saved: number } {
const { gap = 0.25, hook = 3, hookGap = 0.15, pad = 0.08, least = 0.06, lead = true, levels, quiet = 18 } = o
const w = timed(words)
if (!w.length) return { keep: [], cuts: [], saved: 0 }
const end = w[w.length - 1].end + pad
// the speech's level: its loud end, over the words
const speech = levels ? pct(w.flatMap((x) => levels.slice(Math.floor(x.start * 100), Math.ceil(x.end * 100))), 0.8) : 0
const loud = (t: number) => !!levels && (levels[Math.floor(t * 100)] ?? -100) > speech - quiet
const cuts: Span[] = []
const cut = (a: number, b: number) => {
// pulled in from either end while it's still loud there (a word the transcript ended early)
if (levels) {
while (a < b && loud(a)) a += 0.01
while (b > a && loud(b - 0.01)) b -= 0.01
}
if (b - a >= least) cuts.push({ from: +a.toFixed(3), to: +b.toFixed(3) })
}
if (lead && w[0].start - pad > 0) cut(0, w[0].start - pad)
for (let i = 1; i < w.length; i++) {
const a = w[i - 1].end, b = w[i].start
// what's left of the gap: the allowed gap, never less than a pad on each word
const left = Math.max(a < hook ? hookGap : gap, 2 * pad)
if (b - a > left) cut(a + left / 2, b - left / 2)
}
const keep: Span[] = []
let at = 0
for (const c of cuts) {
if (c.from > at) keep.push({ from: +at.toFixed(3), to: c.from })
at = c.to
}
if (end > at) keep.push({ from: +at.toFixed(3), to: +end.toFixed(3) })
return { keep, cuts, saved: +cuts.reduce((n, c) => n + c.to - c.from, 0).toFixed(3) }
}
+1
View File
@@ -8,6 +8,7 @@ export * from "./nudge";
export * from "./speed";
export * from "./transition";
export * from "./words";
export * from "./airgaps";
export * from "./region";
export * from "./overlay";
export * from "./panel";
+20
View File
@@ -0,0 +1,20 @@
//! The default mix (DEFAULT_GRAPH): a bus-less music file ducks DEFAULT_DUCK_DB under talking, then comes back (two bounces' difference).
use crate::{RATE, Sound, offline::Cue};
#[test]
fn music_ducks_under_the_talking_by_default() {
let dir = std::env::temp_dir().join(format!("raea-mixer-test-duck-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap();
let tone = |name: &str, hz: f32| {
let ch: Vec<f32> = (0..6 * RATE as usize).map(|i| 0.5 * (i as f32 * hz * std::f32::consts::TAU / RATE as f32).sin()).collect();
crate::write_wav(&raea_io_media::Audio { rate: RATE, channels: vec![ch.clone(), ch] }, &dir.join(name)).unwrap();
dir.join(name)
};
let (song, talk) = (tone("song.wav", 220.0), tone("interview_voice.wav", 990.0));
let s = |k: &str, f: &std::path::Path, at: i64| Sound { key: k.into(), file: f.into(), at: at as f64 / 30.0, volume: 0.25, rate: 1.0, fade_in: 0.0, fade_out: 0.0, bus: None };
let cues = |song_on: bool| -> Vec<Cue> { (0..150).map(|f| Cue { sounds: [song_on.then(|| s("song", &song, f)), (45..105).contains(&f).then(|| s("talk", &talk, f - 45))].into_iter().flatten().collect(), ..Default::default() }).collect() };
let (both, alone) = (crate::offline::bounce_raw(&cues(true), 30.0).unwrap(), crate::offline::bounce_raw(&cues(false), 30.0).unwrap());
let db = |a: f64, b: f64| { let r = (a * RATE as f64) as usize..(b * RATE as f64) as usize; let n = r.len() as f64; 10.0 * (r.map(|k| ((both.channels[0][k] - alone.channels[0].get(k).copied().unwrap_or(0.0)) as f64).powi(2)).sum::<f64>() / n).log10() };
let (before, under, after) = (db(0.5, 1.4), db(2.2, 3.3), db(4.3, 4.9));
assert!((under - before - crate::DEFAULT_DUCK_DB).abs() < 1.5, "the music under the talk is {:.1} dB from before it", under - before);
assert!((after - before).abs() < 1.0, "the music came back to {:.1} dB from before", after - before);
}
+3
View File
@@ -12,6 +12,8 @@ pub mod live;
pub mod nodes;
pub mod offline;
pub mod score;
#[cfg(test)]
mod duck_test;
use std::path::Path;
use std::sync::Arc;
@@ -60,6 +62,7 @@ impl ToneCue {
}
}
pub use raea_sys_tone::defaults::{DEFAULT_DUCK_DB, DEFAULT_GRAPH, default_bus};
/// A source a Tone graph names (a Sampler's sample, a Player's file), opened whole: it's short, and the audio thread
/// never waits for its blocks.
pub fn open_whole(file: &str) -> Option<std::sync::Arc<raea_io_media::pcm::Pcm>> {
+3 -3
View File
@@ -278,8 +278,8 @@ impl Live {
}
}
// the edit's Tone graph, built the first frame it shows (and again if it changes)
if let Some(g) = &tone.graph
&& raea_sys_tone::tonegraph::hash(g) != self.built.hash
let g = tone.graph.as_ref().unwrap_or(&crate::DEFAULT_GRAPH);
if raea_sys_tone::tonegraph::hash(g) != self.built.hash
{
self.built.tear_down(&mut self.cx, self.voices);
match raea_sys_tone::tonegraph::build(&mut self.cx, self.voices, self.master, g, origin, &mut |f| crate::open_whole(f)) {
@@ -294,7 +294,7 @@ impl Live {
evs.extend(score.chunk(f, a));
}
if let Some(a) = &tone.speech {
evs.extend(score.chunk_on(f, a, self.built.bus_port.get("voice").copied().unwrap_or(0)));
evs.extend(score.chunk_on(f, a, self.built.bus_port.get("voice").or(self.built.bus_port.get("talk")).copied().unwrap_or(0)));
}
let tone_evs = score.tone(f, &self.built, &tone.evs);
for (t, ev) in evs {
+3 -3
View File
@@ -64,8 +64,8 @@ impl Engine {
let pcms = &mut self.pcms;
let items: Vec<(Sound, Arc<Pcm>)> = cue.sounds.iter().filter_map(|s| pcms.entry(s.file.to_path_buf()).or_insert_with(|| Pcm::open(&s.file, true)).clone().map(|p| (s.clone(), p))).collect();
// the edit's Tone graph, built the first frame it shows (and again if it changes)
if let Some(g) = &cue.tone.graph
&& raea_sys_tone::tonegraph::hash(g) != self.built.hash
let g = cue.tone.graph.as_ref().unwrap_or(&crate::DEFAULT_GRAPH);
if raea_sys_tone::tonegraph::hash(g) != self.built.hash
{
self.built.tear_down(&mut self.cx, self.voices);
self.built = raea_sys_tone::tonegraph::build(&mut self.cx, self.voices, self.master, g, origin, &mut |f| crate::open_whole(f))?;
@@ -75,7 +75,7 @@ impl Engine {
evs.extend(self.score.chunk(f, a));
}
if let Some(a) = &cue.tone.speech {
evs.extend(self.score.chunk_on(f, a, self.built.bus_port.get("voice").copied().unwrap_or(0)));
evs.extend(self.score.chunk_on(f, a, self.built.bus_port.get("voice").or(self.built.bus_port.get("talk")).copied().unwrap_or(0)));
}
for (t, ev) in evs {
self.cx.schedule_event_for(self.voices, event(ev), Some(EventInstant::AtClockSamples(InstantSamples(origin + t))));
+2 -1
View File
@@ -143,7 +143,8 @@ impl Score {
let fade_in = if s.fade_in < 0.0 { 0 } else if first && s.fade_in > 0.0 { self.samples(s.fade_in) } else { edge };
let id = self.next;
self.next += 1;
let port = s.bus.as_ref().and_then(|b| buses.get(&**b)).copied().unwrap_or(0);
// a sound with no bus takes the default mix's (crate::default_bus), which only the default graph has
let port = match s.bus.as_deref() { Some(b) => buses.get(b).copied(), None => crate::default_bus(&s.file).and_then(|b| buses.get(b)).copied() }.unwrap_or(0);
out.push((t, Ev::Start { id, pcm: pcm.clone(), at: s.at, rate: s.rate, gain: s.volume, fade_in, port }));
self.runs.insert(k.to_string(), Run { id, pcm: pcm.clone(), f, at: s.at, rate: s.rate, volume: s.volume, fade_out: s.fade_out });
}
+42
View File
@@ -0,0 +1,42 @@
//! The mix an edit gets when it writes no Tone graph of its own (raea-sys-mix routes bus-less sounds by it).
use std::path::Path;
/// How far the default mix ducks a music file under the talking (dB): slight, enough that the voice sits on top
/// (11-30, Shane: the StreetTalk cuts' music was "about 4 or 5 decibels too loud ... move audio down in the mix
/// especially while talking, but a CTA or something with no audio, that's fine"). It lets go where nobody talks.
pub const DEFAULT_DUCK_DB: f64 = -6.0;
/// The mix an edit gets when it writes no Tone graph of its own: a `talk` bus (footage and voice files) and a `bed` bus
/// (music files) ducked DEFAULT_DUCK_DB under it, both at unity; effects stay on the master. The names aren't
/// raea/tone's (music, voice), so an edit's own buses are never changed by it, and `bus="master"` (any name no bus has)
/// keeps a sound out of it.
pub static DEFAULT_GRAPH: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {
format!(
r#"{{"nodes":[{{"id":0,"kind":"Destination","options":{{"volume":0}}}},{{"id":1,"kind":"Channel","name":"bed","options":{{"volume":0,"pan":0,"duck":{{"amount":{DEFAULT_DUCK_DB},"threshold":-42,"attack":0.08,"release":0.45}}}}}},{{"id":2,"kind":"Channel","name":"talk","options":{{"volume":0,"pan":0}}}}],"edges":[[1,0,0],[2,0,0],[2,1,1]]}}"#
)
});
/// Whether `hay` holds any of `needles`, ignoring ASCII case, without allocating (the live mixer calls it each frame)
fn has_any(hay: &str, needles: &[&str]) -> bool {
let h = hay.as_bytes();
needles.iter().any(|n| h.windows(n.len()).any(|w| w.eq_ignore_ascii_case(n.as_bytes())))
}
/// The default mix's bus for a sound with none (DEFAULT_GRAPH): footage (a video file: the people on screen talking) and
/// a voice file (vo, voice, narration, dialogue, speech in its name) on `talk`; an effect (sfx, foley, whoosh, sting,
/// riser, hit) on the master; any other audio file, the music, on `bed`.
pub fn default_bus(file: &Path) -> Option<&'static str> {
let name = file.file_name().and_then(|n| n.to_str()).unwrap_or("");
let ext = file.extension().and_then(|e| e.to_str()).unwrap_or("");
if ["mp4", "mov", "m4v", "webm", "mkv", "avi", "mxf"].iter().any(|e| ext.eq_ignore_ascii_case(e)) {
return Some("talk");
}
if has_any(name, &["voice", "narrat", "dialog", "speech", "_vo", "vo_", "-vo", "vo-", "interview"]) {
return Some("talk");
}
if has_any(name, &["sfx", "foley", "whoosh", "swoosh", "sting", "riser", "impact", "click", "_fx", "fx_"]) {
return None;
}
Some("bed")
}
+1
View File
@@ -7,3 +7,4 @@ pub mod dsp;
pub mod fx;
pub mod tone;
pub mod tonegraph;
pub mod defaults;