Compare commits

..
Author SHA1 Message Date
shinyobjectz 559b23482f Safe defaults: text keeps out of the app's UI zones, talking clips move off words
Round 22's ad cuts spent most of their render passes on two kinds of error that the goal check found only after a
full render: text in the app's UI zones (the floor's safe-area rule) and clips whose in or out cut a word (the sound
pack's edit points). This makes the SDK's defaults avoid both.

Text: uiZones(width, height, {platform, shape}) is the floor's own table (apps/check/text/src/lib.rs zones), and
useUiZones() reads it for the composition. <SafeArea> is a layer over the frame inset by the zones, for text placed by
hand. <Region> now keeps its bands out of the zones by default: its edges were 0.08 H and 0.80 H, inside the 9:16 top
and bottom zones, and its sides a symmetric 65 px, inside the 140 px right-hand zone. keepOut={false} gives the old
bands for a part placed there on purpose, and platform picks a platform's zones.

Clips: a <Video> placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence) on a take
with its words beside it (TAKE.words.json, or footage/TAKE.words.json for a take in media/) moves in its take by the
least amount within 0.4 s that leaves neither end inside a word, judged as the sound pack judges it. In and out move
together, so its place and length in the edit stay and nothing freezes. Clips of one take that play on from each other
(a take split only to reframe it) move together, so the take plays on unbroken where they join; this is why the move
is made where the clips are placed (AbsoluteFill and Series look through their children) rather than by each Video,
which can't see the clips it joins. Each move is written to the render's log once, and the element carries
data-raea-snapped. snap={false} keeps a clip where it is; snap={true} moves a Video on its own where the tree doesn't
reach it.

Tested: bun test conformance (776 pass; the 6 that fail fail the same on main), with new tests in
safe-defaults.test.tsx and the Region tests updated to the new bands. On the three round 22 projects' render manifests
and take words, the clip snapping takes the real cut ends inside words from 24 to 8, 22 to 6 and 2 to 2, and keeps all
65 joins between continuous clips unbroken. On a Fly box, raea 0.1.17-rc4 with this sdk/video overlaid (its files were
identical to main's before the change) rendered a test edit: the caption row placed on the frame is flagged in the
right-hand zone and the same row inside SafeArea is not, a Region's bands are clear, the clip whose in cut a word
plays 300 ms earlier (sounds.clips at 10.2) with the move in the render's log, and the reframed pair is left alone.
The SDK reference pages are regenerated for the new exports only.
2026-12-04 10:21:13 -08:00
23 changed files with 933 additions and 897 deletions

No files matched your search

+134 -6
View File
@@ -38,13 +38,14 @@ See [Your first video](../../start/first-video.md) for the whole loop, and
import { AbsoluteFill, ACTION_KEY, actionsIn, Animate } from "raea"
```
`raea` exports 21 components, 9 hooks, 65 functions, 11 values, 109 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
`raea` exports 22 components, 10 hooks, 68 functions, 12 values, 117 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
## Components
### `AbsoluteFill`
A box over the whole of its parent, laid out as a flex column; `style` is merged over that.
A box over the whole of its parent, laid out as a flex column; `style` is merged over that. The talking clips placed
in it are moved off words first (snapPlaced).
| Prop | Type | What it does |
| --- | --- | --- |
@@ -209,6 +210,7 @@ component, whose box it can't reach, or a part with a mask, is placed inside a f
| `framing` | `"face"` | ours: frame the take on the largest face |
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
| `snap` | `boolean` | ours: whether its ends are moved off words. A Video placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence) on a talking take (one with its words beside it, TAKE.words.json) is moved, by default, to the nearest place within 0.4 s in the take where neither its in nor its out cuts a word: in and out together, so its place and length in the edit stay, and together with the clips of the same take that play on from it, so the take still plays on unbroken where they join. The render's log says each move. false plays it from exactly startFrom; true moves it on its own wherever it is (a Video inside a component of your own, which the edit's tree doesn't reach), not knowing the clips it joins (snap.ts) |
Also takes the props of [`MediaProps`](video.md#mediaprops).
@@ -229,10 +231,26 @@ A box at the band its name stands for, clear of the face perception found at thi
| --- | --- | --- |
| `name` | `RegionName` | the band: "auto" (default) takes the larger of top and bottom; top and bottom stay clear of the face; center is the middle third; full is the safe area |
| `margin` | `number` | the gap kept from the face and the sides, as a share of the width (0.06) |
| `keepOut` | `boolean` | keep the band out of the app's UI zones (true): its edges and sides clear the strips a social app draws its buttons and captions over (uiZones). false places it there on purpose: the older bands, 0.08 H from the top to 0.80 H down, inset by `margin` alone |
| `platform` | `UiPlatform` | the platform whose UI it keeps out of (tiktok, reels, shorts); none: the strictest, as the floor checks |
| `style` | `CSSProperties` | merged under the box's own placement |
| `className` | `string` | Tailwind or CSS classes |
| `children` | `ReactNode` | what goes in the band; `useRegion()` reads its box |
### `SafeArea`
A layer over the whole frame but the app's UI zones: text and captions placed inside it (absolutely, or in its
flex column) are clear of them. Its top, right, bottom and left are the zones, as CSS custom properties --ui-top,
--ui-right, --ui-bottom and --ui-left on it.
| Prop | Type | What it does |
| --- | --- | --- |
| `style` | `CSSProperties` | merged over the layer's own placement |
| `className` | `string` | Tailwind or CSS classes |
| `children` | `ReactNode` | what goes inside: placed in the layer, which keeps clear of the app's UI |
Also takes the props of [`UiZoneOptions`](#uizoneoptions) (`platform`, `shape`).
### `Sequence`
Shifts time by `from` and shows its children only for `durationInFrames` frames.
@@ -253,7 +271,8 @@ Used in: [manual: hello](https://github.com/shinyobjectz/raea/blob/main/docs/man
### `Series`
Plays its Series.Sequence children back to back, each shifted by its own offset.
Plays its Series.Sequence children back to back, each shifted by its own offset; the talking clips in them are moved
off words first (snapPlaced).
| Prop | Type | What it does |
| --- | --- | --- |
@@ -291,13 +310,15 @@ Its children, coming in over the part's first frames, going out over its last, a
### `Video`
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show.
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show. On a talking take its
ends are moved off words (`snap`).
| Prop | Type | What it does |
| --- | --- | --- |
| `framing` | `"face"` | ours: frame the take on the largest face |
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
| `snap` | `boolean` | ours: whether its ends are moved off words. A Video placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence) on a talking take (one with its words beside it, TAKE.words.json) is moved, by default, to the nearest place within 0.4 s in the take where neither its in nor its out cuts a word: in and out together, so its place and length in the edit stay, and together with the clips of the same take that play on from it, so the take still plays on unbroken where they join. The render's log says each move. false plays it from exactly startFrom; true moves it on its own wherever it is (a Video inside a component of your own, which the edit's tree doesn't reach), not knowing the clips it joins (snap.ts) |
Also takes the props of [`MediaProps`](video.md#mediaprops).
@@ -376,6 +397,14 @@ the map bound to the composition's fps as `song`.
function useSong(map: SongMap, options?: UseSongOptions): SongMoment & { song: Song; }
```
### `useUiZones`
The app's UI zones of the composition being rendered (its width and height).
```ts
function useUiZones(o?: UiZoneOptions): UiZones
```
### `useVideoConfig`
The settings of the composition being rendered (inside a Sequence, its width, height and length win).
@@ -697,10 +726,12 @@ function random(seed: string | number | null): number
### `regionBand`
Works out the vertical band each name stands for, given perception and the composition size.
Works out the vertical band each name stands for, given perception and the composition size. Its edges are the
platform's safe area when perception gives one, else clear of the app's UI zones (`keepOut`: uiZones of the frame);
with keepOut false, 0.08 H from the top and 0.80 H (0.92 H landscape) down, which reach into them.
```ts
function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin?: number): Band
function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin?: number, keepOut?: false | UiZones): Band
```
### `registerRoot`
@@ -788,6 +819,18 @@ arrives from a side: `distance` px (30) over `frames` (7), fading in over 5. `fr
function slide(o?: { from?: Dir; distance?: number; frames?: number; ease?: Curve; }): Move
```
### `snapClip`
The clip [tin, tout] of a take (seconds in the take; tout Infinity when it plays to the take's end or its length isn't
known) moved by the least amount, within SNAP_NEAR, that leaves neither end inside a word, as the sound pack's edit
points judge it (a cut on a boundary where words run together is tight, not a cut word): in a gap if one is near, else
on such a boundary. Failing that, the move that leaves the fewest ends inside words. Never moved before the take's
start.
```ts
function snapClip(words: readonly TakeWord[], tin: number, tout: number): Snap
```
### `song`
A song map bound to a frame rate (and where frame 0 sits in the song): frames from song times, and the reverse.
@@ -882,6 +925,15 @@ a strike-through line drawn: width 0 to 100% over `frames` (8).
function strike(o?: { frames?: number; ease?: Curve; }): Move
```
### `takeWords`
The words of the take `src`, read once from the first words file found (takeWordsFiles); null when there is none or
this isn't the engine (plain bun has no files to read).
```ts
function takeWords(src: string): TakeWord[] | null
```
### `tick`
a number counting from `from` (0) to `to` over `frames` (24), written as the element's text: `digits` decimals,
@@ -936,6 +988,15 @@ sees states (a playtest over a game's pure fold) recovers the TransitionRecord a
function transitionOf(m: AnyMachine, before: Snapshot<string> | undefined, after: Snapshot<string>): TransitionRecord | null
```
### `uiZones`
The app's UI zones of a `width` x `height` frame: how far in from each edge its text keeps, in px. The floor's
numbers (apps/check/text/src/lib.rs `zones`), scaled with the width.
```ts
function uiZones(width: number, height: number, o?: UiZoneOptions): UiZones
```
### `wipe`
a reveal wiping across from `from` (left) over `frames` (8), in-out-cubic, by clipping.
@@ -1003,6 +1064,10 @@ Where the space's media folder is served from.
The named moves by name, as `enter="rise"` finds them.
### `SNAP_NEAR`
the most a clip is moved to clear its ends (s): the sound pack's NEAR, where it looks for a gap
### `SPACE_KEY`
The prefix of the key the app holds on the stage for each panel that publishes (`data-feed-publish` on an element):
@@ -1637,6 +1702,10 @@ A control as a registered composition holds it: its cost said.
type RegisteredControl = Control & { cost: ControlCost }
```
### `SafeAreaProps`
The props of [`SafeArea`](#safearea), tabled there.
### `SequenceLayout`
```ts
@@ -1660,6 +1729,22 @@ The props of [`Sequence`](#sequence), tabled there.
| `width` | `number` | the width its children see, px (the parent's by default) |
| `durationInFrames` | `number` | how many frames it shows its children (forever by default) |
### `Snap`
What snapping a clip did: `by` seconds (0 when it stays), the ends it moved off words, and the ends it couldn't.
```ts
type Snap = { by: number; moved: SnapMove[]; left: { edge: "in" | "out"; at: number; word: string }[] }
```
### `SnapMove`
One move of a clip's end: where it was, where it went, and the word it cut.
```ts
type SnapMove = { edge: "in" | "out"; from: number; to: number; word: string; wordFrom: number; wordTo: number }
```
### `Snapshot`
The machine's runtime state, kept in the context it drives. `path` is the active states outermost first ([] before
@@ -1933,6 +2018,14 @@ On or off: a boolean.
| `cost` | `ControlCost` | how a change reaches the picture: "live" unless said |
| `about` | `string` | one line on what it changes, for the panel's tooltip and an agent reading the code |
### `TakeWord`
a word of a take, in seconds
```ts
type TakeWord = { text: string; start: number; end: number }
```
### `TextControl`
A string: a title, a caption, a name.
@@ -2024,6 +2117,41 @@ A target's name alone, one transition, or several checked in order.
type Transitions = | NoInfer<N> | TransitionConfig<C, E, N> | readonly (NoInfer<N> | TransitionConfig<C, E, N>)[]
```
### `UiPlatform`
The platform the cut is for: each draws its UI in a different place. None: the strictest of them, which is what the
floor checks when the brief names no platform.
```ts
type UiPlatform = "tiktok" | "reels" | "shorts"
```
### `UiShape`
The frame's shape; by default the nearest to its width over height.
```ts
type UiShape = "9:16" | "4:5" | "1:1" | "16:9"
```
### `UiZoneOptions`
| Field | Type | What it is |
| --- | --- | --- |
| `platform` | `UiPlatform` | the platform's own zones (tiktok, reels, shorts); none: the strictest |
| `shape` | `UiShape` | the shape to take the zones of; by default the nearest to width / height |
### `UiZones`
How far in from each edge of the frame the app's UI reaches, in the composition's px.
| Field | Type | What it is |
| --- | --- | --- |
| `top` (required) | `number` | the status bar and the app's top tabs |
| `right` (required) | `number` | the like, comment and share buttons |
| `bottom` (required) | `number` | the app's own caption, sound name and bar |
| `left` (required) | `number` | the edge's margin |
### `UseSongOptions`
| Field | Type | What it is |
+5 -2
View File
@@ -79,7 +79,8 @@ Shifts time by `from` and shows its children only for `durationInFrames` frames.
### `Series`
Plays its Series.Sequence children back to back, each shifted by its own offset.
Plays its Series.Sequence children back to back, each shifted by its own offset; the talking clips in them are moved
off words first (snapPlaced).
| Prop | Type | What it does |
| --- | --- | --- |
@@ -87,13 +88,15 @@ Plays its Series.Sequence children back to back, each shifted by its own offset.
### `Video`
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show.
A video clip in step with the frame; `data-source-time` is the source time (seconds) to show. On a talking take its
ends are moved off words (`snap`).
| Prop | Type | What it does |
| --- | --- | --- |
| `framing` | `"face"` | ours: frame the take on the largest face |
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
| `matte` | `VideoMatte` | ours: its cutout: the mattes made of its file, which it wears as its mask, so what is cut out shows what is under it |
| `snap` | `boolean` | ours: whether its ends are moved off words. A Video placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence) on a talking take (one with its words beside it, TAKE.words.json) is moved, by default, to the nearest place within 0.4 s in the take where neither its in nor its out cuts a word: in and out together, so its place and length in the edit stay, and together with the clips of the same take that play on from it, so the take still plays on unbroken where they join. The render's log says each move. false plays it from exactly startFrom; true moves it on its own wherever it is (a Video inside a component of your own, which the edit's tree doesn't reach), not knowing the clips it joins (snap.ts) |
Also takes the props of [`MediaProps`](#mediaprops).
+3 -66
View File
@@ -9,19 +9,14 @@ import type { Contract } from "./contract.ts"
import * as media from "./media.ts"
import type { Faces, Levels, Word } from "./media.ts"
import type { Scene } from "./packs/place.ts"
import { outOf, planScene, said } from "./plan.ts"
import type { Project } from "./project.ts"
/** a sound clip in a render's manifest: its comp frames, its source and the source second at `from` */
export type Clip = { key?: string; from: number; to: number; src: string; at: number; gainDb?: number; bus?: string; fadeIn?: number; fadeOut?: number }
/** a text on a frame, in render pixels: its layout box and its ink */
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number; lines?: number }
/** a video on a frame, in render pixels: its source and the source second it shows, its box (and what of it a box it's
* in leaves showing, `clip`), its object-fit and object-position ([x px, x share of the free space, y px, y share]) */
export type ManifestVideo = { src: string; at: number; box: number[]; clip?: number[]; fit?: string; position?: number[]; opacity?: number }
/** `raea render --manifest`: the frames with their texts and videos, and the sound's clips; `plan`: written by `raea
* render --plan`, which draws nothing (every frame laid out, no picture) */
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; plan?: boolean; frames?: { frame: number; text?: ManifestText[]; videos?: ManifestVideo[]; pictures?: { kind?: string; box?: number[]; opacity?: number }[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
export type ManifestText = { text: string; box?: number[]; ink?: number[]; opacity?: number; size?: number }
/** `raea render --manifest`: the frames with their texts, and the sound's clips */
export type Manifest = { width?: number; height?: number; fps?: number; length?: number; frames?: { frame: number; text?: ManifestText[] }[]; sounds?: { fps?: number; clips?: Clip[] } }
/** what was seen of a file and said (FILE.seen.json, `raea goal seen`); `look` is its design judged at full size */
export type Seen = { video: string; render: string; seen: string; look?: string; surprise?: string; at?: string }
@@ -42,9 +37,6 @@ export interface FileFacts {
height: number | null
fps: number
manifest: Manifest | null
/** a cut checked on its plan, before it's drawn (plan.ts): `manifest` is the plan, `path` and `abs` name the export
* it's of (which may not be there yet), and its words and scene are what its takes say and its sources show */
plan: boolean
moment: Moment
contract: Contract | null
/** what it says, word by word */
@@ -133,7 +125,6 @@ export function fileFacts(rel: string, root: string, moment: Moment, contract: C
height: shape?.height ?? manifest?.height ?? null,
fps: manifest?.fps ?? shape?.fps ?? 30,
manifest,
plan: false,
moment,
contract,
words: once(() => media.words(abs)),
@@ -176,57 +167,3 @@ export function runIn(dir: string) {
return r.status === 0 ? { ok: true, said: "passes" } : { ok: false, said: `exits ${r.status ?? "by a signal"}${last ? `: ${last}` : ""}` }
}
}
/** a composition checked on a plan of one of its cuts (`raea goal check --at edit --manifest OUT.plan.json EDIT.tsx`):
* the facts of the export the plan is of (OUT.mp4 beside the plan), known before it's drawn. Its words are its voice
* clips' takes' words where the clips put them, its scene its videos' source frames' (plan.ts); its own level, sheet
* and look wait for the export */
export function planFacts(plan: Manifest, planAbs: string, root: string, moment: Moment, contract: Contract | null): FileFacts {
const abs = `${outOf(planAbs)}.mp4`
const roots = [root, path.dirname(planAbs)]
const fps = Number(plan.fps) || 30
const takeWords = new Map<string, Promise<Word[]>>()
const take = (src: string) => onMachine(src, roots)
const wordsOfTake = (src: string) => {
const f = take(src)
if (!f) return Promise.reject(new media.Unmet(`${src} isn't on this machine`))
if (!takeWords.has(f)) takeWords.set(f, media.words(f, true))
return takeWords.get(f)!
}
const st = statSync(planAbs)
return {
path: path.relative(root, abs),
abs,
root,
kind: "other",
made: true,
stamp: `${Math.round(st.mtimeMs)} ${st.size}`,
seconds: (Number(plan.length) || plan.frames?.length || 0) / fps,
width: Number(plan.width) || null,
height: Number(plan.height) || null,
fps,
manifest: plan,
plan: true,
moment,
contract,
words: once(async () => {
const clips = plan.sounds?.clips ?? []
const got = new Map<string, Word[]>()
for (const c of clips) {
if (got.has(c.src)) continue
try {
got.set(c.src, await wordsOfTake(c.src))
} catch {}
}
return said(clips, plan.sounds?.fps ?? fps, (src) => got.get(src) ?? null)
}),
take,
takeWords: wordsOfTake,
levels: (a, b, src) => (src ? media.levels(take(src) ?? src, a, b) : { start: a ?? 0, db: [] }),
scene: once(() => planScene(root, plan, take)),
sheet: () => {
throw new media.Unmet("a plan has no picture to make a sheet of: render it")
},
seen: () => null,
}
}
+18 -31
View File
@@ -233,7 +233,24 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
else if (at?.length) at.forEach((s, i) => ffmpeg(["-v", "error", "-y", "-ss", String(s), "-i", file, "-frames:v", "1", "-vf", scale, "-q:v", "4", path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`)]))
else ffmpeg(["-v", "error", "-y", "-i", file, "-vf", `fps=${RATE},${scale}`, "-q:v", "4", path.join(dir, "f%05d.jpg")])
const jpgs = readdirSync(dir).filter((n) => n.endsWith(".jpg")).sort()
const { faces, scenes } = await readScenes(jpgs.map((n) => readFileSync(path.join(dir, n))))
const faces: Faces[] = []
const scenes: Scene[] = []
for (let i = 0; i < jpgs.length; i += 300) {
const body = JSON.stringify({ frames: jpgs.slice(i, i + 300).map((n) => readFileSync(path.join(dir, n)).toString("base64")) })
const r = await post("/v1/scene", body, "application/json")
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
for (const g of (JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames) {
if (!g) {
faces.push(null)
scenes.push(null)
continue
}
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 })
// 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)
}
}
if (whole && scenes.length) {
try {
writeFileSync(`${stem(file)}.${SCENE_EXT}`, `${JSON.stringify({ rate: RATE, side: SIDE, faces, scenes })}\n`)
@@ -245,36 +262,6 @@ export async function scene(file: string, at?: number[]): Promise<{ rate: number
}
}
/** frames (JPEGs, a null where there's none) read by the farm's scene reader, 300 a request: each one's faces and seams,
* and its scene (people, faces, things, words in the shot) */
export async function readScenes(jpgs: (Buffer | null)[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
if (!farm()) throw new Unmet("no scene reader on this machine (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)")
const faces: Faces[] = []
const scenes: Scene[] = []
const real = jpgs.flatMap((j, i) => (j ? [i] : []))
const got = new Map<number, Record<string, any> | null>()
for (let i = 0; i < real.length; i += 300) {
const part = real.slice(i, i + 300)
const body = JSON.stringify({ frames: part.map((k) => jpgs[k]!.toString("base64")) })
const r = await post("/v1/scene", body, "application/json")
if (!r.ok) throw new Unmet(`the farm reads no scenes yet (POST /v1/scene: ${r.status})`)
;(JSON.parse(r.text) as { frames: (Record<string, any> | null)[] }).frames.forEach((g, n) => got.set(part[n], g))
}
for (let i = 0; i < jpgs.length; i++) {
const g = got.get(i)
if (!g) {
faces.push(null)
scenes.push(null)
continue
}
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 })
// 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 { faces, scenes }
}
/** a video's contact sheet beside it (FILE.sheet.jpg, `raea media sheet`), made again when older than the video */
export function sheet(file: string): string {
const out = `${stem(file)}.sheet.jpg`
+5 -8
View File
@@ -16,8 +16,7 @@
// 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 { RATE, type Word } from "../media.ts"
import { samples, textFrames } from "../plan.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 */
@@ -236,15 +235,13 @@ export function uncaptioned(shown: Shown[], heard: Word[], textUp: (t: number) =
}
export default check<FileFacts>(
{ id: "captions", text: "everything said is captioned, and every caption says exactly what's heard there, no word added, changed or left out", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
{ id: "captions", text: "everything said is captioned, and every caption 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" && !f.plan)) return
if (!f.made || f.kind !== "video") return
const heard = await f.words()
if (!heard.length) return
// a cut's plan (plan.ts): what it shows is its own text, as laid out, and what it says its takes' words where its
// clips put them; an export's is what the reader reads and hears in it
const sc = f.plan && f.manifest ? { rate: RATE, scenes: [] } : await f.scene()
const frames: Frame[] = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
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)
const rate = sc.rate || 2
+1 -8
View File
@@ -10,7 +10,6 @@ import path from "node:path"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RAEA, stem } from "../media.ts"
import { textRules, ZONE_FIX } from "../plan.ts"
import { bookkeeping } from "./naming.ts"
export type Measured = { level: "error" | "warn" | "note"; says: string; fix?: string | null; frames?: [number, number] | null }
@@ -54,13 +53,7 @@ export function floorOf(abs: string, manifest: string | undefined, cwd: string,
const say = (x: Measured) => found({ level: x.level, says: x.says, fix: x.fix ?? undefined, frames: x.frames ?? undefined })
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["edit", "render", "publish", "done"] }, async (f) => {
// a cut's plan (plan.ts): the text rules raea check holds a manifest to, on every frame, before it's drawn; what only
// the picture and the mix show (contrast, freezes, flashing, loudness, blotching) waits for the export
if (f.plan && f.manifest) {
for (const x of textRules(f.manifest)) found({ level: x.level, says: x.says, fix: x.rule === "safe-area" ? ZONE_FIX : undefined, seconds: x.at })
return
}
export const floorPack = check<FileFacts>({ id: "floor", text: "no clipped text, low contrast, freeze, flash or loudness out of range", over: "file", at: ["render", "publish", "done"] }, async (f) => {
if (!f.made || f.kind !== "video" || bookkeeping(f.path)) return
const m = [`${stem(f.abs)}.render.json`, `${stem(f.abs)}.manifest.json`].find(existsSync)
for (const x of floorOf(f.abs, m, f.root)) say(x)
+3 -8
View File
@@ -13,7 +13,6 @@ import { existsSync, readFileSync } from "node:fs"
import { check, found } from "raea/check"
import type { FileFacts } from "../facts.ts"
import { RATE, stem, type Faces } from "../media.ts"
import { PLAN_SOFT } from "../plan.ts"
/** a face this share of the frame's height or more is someone in the shot, not a passer-by far behind */
export const FACE_MIN = 0.05
@@ -142,17 +141,13 @@ export const despite = (abs: string) => {
}
export default check<FileFacts>(
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
{ id: "frames", text: "no face cut by the frame or a split screen's seam, no text too small to read", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
async (f) => {
// at edit only a cut's plan (plan.ts): its faces are its sources' frames, mapped into the cut's
if (!f.made || (f.kind !== "video" && !f.plan)) return
if (!f.made || f.kind !== "video") return
const say = (x: Finding) => found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
if (f.manifest) for (const x of smallText(f.manifest)) say(x)
// the text's sizes are said even where the faces wait for a scene reader
const why = despite(f.abs)
// on a plan a face cut by the edge is a warning (plan.ts ON_PLAN_WARNS): its source frames are read without the cut's
// text over them, and the render's check holds it
for (const x of cutFaces((await f.scene()).faces, RATE))
say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : f.plan && x.kind === "face-cut" && x.level === "error" ? { ...x, level: "warn", says: `${x.says}${PLAN_SOFT}` } : x)
for (const x of cutFaces((await f.scene()).faces, RATE)) say(why && x.kind === "face-cut" ? { ...x, level: "warn", says: `${x.says} (despite: ${why})` } : x)
},
)
+2 -2
View File
@@ -294,9 +294,9 @@ export function placeReport(file: string, scenes: Scene[], size: [number, number
}
export default check<FileFacts>(
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["edit", "render", "publish", "done"], needs: ["scene"] },
{ id: "place", text: "no text over a face, hands or what the shot is about where a clear place of its size exists", over: "file", at: ["render", "publish", "done"], needs: ["scene"] },
async (f) => {
if (!f.made || (f.kind !== "video" && !f.plan) || !f.manifest?.frames?.length) return
if (!f.made || f.kind !== "video" || !f.manifest?.frames?.length) return
const { scenes } = await f.scene()
for (const x of textOver(f.manifest, scenes, RATE)) found({ level: x.level, says: x.says, seconds: x.at === null ? undefined : x.until === undefined ? x.at : [x.at, x.until] })
},
+5 -9
View File
@@ -11,8 +11,7 @@
// 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 { RATE, type Word } from "../media.ts"
import { samples, textFrames } from "../plan.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 }
@@ -106,14 +105,11 @@ export function reading(blocks: Block[]): Finding[] {
}
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: ["edit", "render", "publish", "done"], needs: ["words", "scene"] },
{ 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" && !f.plan)) return
// a cut's plan (plan.ts): its own text as laid out (a sign in the footage isn't meant to be read); an export's,
// what the reader reads in it
const planned = f.plan && f.manifest ? textFrames(f.manifest, samples(f.manifest)) : null
const sc = planned ? { rate: RATE, scenes: [] } : await f.scene()
const frames: Frame[] = planned ?? sc.scenes.map((s) => ({ h: s?.h ?? 1, lines: (s?.texts ?? []) as Read[] }))
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()
+2 -3
View File
@@ -229,10 +229,9 @@ export async function soundOf(f: FileFacts): Promise<{ findings: Finding[]; voic
}
export default check<FileFacts>(
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["edit", "render", "publish", "done"], needs: ["words", "levels"] },
{ id: "sound", text: "edit points in the pauses, every line within 6 dB of the others, every effect heard", over: "file", at: ["render", "publish", "done"], needs: ["words", "levels"] },
async (f) => {
// at edit only a cut's plan (plan.ts), whose clips are the export's
if (f.kind !== "video" && f.kind !== "audio" && !f.plan) return
if (f.kind !== "video" && f.kind !== "audio") return
if (!f.made) return
if (!f.manifest) {
if (f.moment !== "edit") found({ level: "note", says: `${path.basename(f.path)} has no render manifest beside it (FILE.render.json), so its edit points and levels aren't checked: render it with raea, which writes one` })
-475
View File
@@ -1,475 +0,0 @@
// A cut checked before it's drawn (12-04, round 22: every run missed its budget the same way, a full render of every cut
// and only then dozens of errors, fixed, and everything rendered again). `raea render EDIT.tsx --composition ID --plan
// -o OUT.plan.json` runs each frame through React and layout and gathers the sound, drawing nothing: its plan is a render
// manifest of every frame. `raea goal check --at edit --manifest OUT.plan.json EDIT.tsx` holds the plan to what can be
// known from it:
//
// floor its text clipped by the frame or in the app's UI zones, and up too briefly (apps/check/text's rules)
// frames text too small, and faces cut by the frame or a split screen's seam
// place text over a face, a person or what the shot is about
// sound clips cut inside a word or on sound, lines and effects at uneven levels (from each take's words and level)
// captions what's said with no caption over it, and a caption that isn't what's said there
// reading text up too briefly to read
//
// What the cut says is its voice clips' takes' words, laid where the clips put them. What its frames show is the scene of
// each SOURCE frame a video shows there (the farm's POST /v1/scene, as for an export), mapped through the video's box,
// fit and object-position into the cut's frame: the picture the render would draw, read without drawing it. Each
// source frame's reading is kept under review/scenes/, so a plan checked again asks only for frames it hasn't read.
// What only the export has (the words heard in the mix, its loudness, contrast, blotching) waits for --at render.
//
// A plan's errors stop the renders (raea cloud renders a batch only when every cut's plan passes), so on a plan an error
// is only what the plan knows as exactly as the export's check: floor's text rules, text too small, sound's edit points
// and levels. Place, captions, reading and faces cut by the edge are read from the source frames without the cut's own
// text over them, or held against the takes' words rather than the mix, and on round 22's Body Shop each cut had one
// such error the export's check didn't give (ON_PLAN_WARNS): on a plan they're warnings, and the render's check holds
// them. The plan holds its own cut alone: the project's checks and the goals' job checks (the count, the brief's quotes)
// don't run on it, and a check that can't run (the farm busy) waits instead of failing it.
import { spawnSync } from "node:child_process"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import type { Clip, Manifest, ManifestVideo } from "./facts.ts"
import * as media from "./media.ts"
import type { Faces, Word } from "./media.ts"
import { busOf } from "./packs/sound.ts"
import type { Scene, Thing } from "./packs/place.ts"
/** a file a plan is checked for: a composition (the plan of one of its compositions) */
export const COMPOSITION = /\.(tsx|jsx|ts|js|mjs)$/i
/** the export a plan is of: OUT.plan.json (or OUT.render.json, OUT.manifest.json) is OUT's */
export const outOf = (plan: string) => media.stem(plan).replace(/\.(plan|render|manifest)$/i, "")
/** checks whose errors are warnings on a plan (frames' faces cut by the edge too, in frames.ts; its text sizes stay
* errors): each is read or heard otherwise than the export's check reads and hears it */
export const ON_PLAN_WARNS = new Set(["place", "captions", "reading"])
/** said after each error a plan tells and doesn't hold */
export const PLAN_SOFT = " (on the plan a warning: the render's check holds it)"
/** the width the scene reader reads a frame at (media.ts SIDE), so sizes are the export's */
const SIDE = 540
/** a grid cell's side, as the farm's scene reader makes them (540x960: 27x48) */
const CELL = 20
/** a video under this opacity is fading: what's under it, or over it, is what's seen */
const SEEN = 0.5
/** a thing or a face with less than this share of it inside its video's visible box is out of the shot */
const VISIBLE = 0.25
/** a thing this much covered by a video drawn over it is hidden */
const HIDDEN = 0.75
type Rect = [number, number, number, number]
/** the times a plan's frames are read at: RATE a second, from 0 to its end */
export function samples(m: Manifest, rate = media.RATE): number[] {
const fps = Number(m.fps) || 30
const len = Number(m.length) || m.frames?.length || 0
const n = Math.max(0, Math.ceil((len / fps) * rate - 1e-9))
return Array.from({ length: n }, (_, i) => i / rate)
}
/** where a picture sw x sh is drawn in a video's box: its fit, then its object-position ([x px, x share of the free
* space, y px, y share], centred when unset); `native`: the picture's own size, for fit none and scale-down */
export function drawn(v: ManifestVideo, sw: number, sh: number, native: [number, number] = [sw, sh]): Rect {
const [bx, by, bw, bh] = v.box
let dw = bw
let dh = bh
const contain = Math.min(bw / sw, bh / sh)
const fit = v.fit ?? "fill"
if (fit === "cover" || fit === "contain" || fit === "scale-down" || fit === "none") {
const s = fit === "cover" ? Math.max(bw / sw, bh / sh) : fit === "contain" ? contain : fit === "none" ? native[0] / sw : Math.min(contain, native[0] / sw)
dw = sw * s
dh = sh * s
}
const p = v.position ?? [0, 0.5, 0, 0.5]
return [bx + p[0] + p[1] * (bw - dw), by + p[2] + p[3] * (bh - dh), dw, dh]
}
const meet = (a: Rect, b: Rect): Rect | null => {
const x0 = Math.max(a[0], b[0])
const y0 = Math.max(a[1], b[1])
const x1 = Math.min(a[0] + a[2], b[0] + b[2])
const y1 = Math.min(a[1] + a[3], b[1] + b[3])
return x1 > x0 && y1 > y0 ? [x0, y0, x1 - x0, y1 - y0] : null
}
const area = (r: Rect | null) => (r ? r[2] * r[3] : 0)
/** what a video shows in a frame: where its picture (`size`, as decoded: rotation applied) is drawn, what of it is seen
* in the frame (cut px), and that part of the picture as shares of it ([x, y, w, h], the `crop` read for its scene) */
export type Layer = { v: ManifestVideo; size: [number, number]; draw: Rect; seen: Rect; crop: Rect }
/** the videos a frame shows, bottom first: each drawn by its box, fit and position, cut to what its box (and the box
* clipping it) leaves showing in the frame. A fading video (under SEEN) only when nothing else shows */
export function layersOf(videos: ManifestVideo[], W: number, H: number, sizeOf: (v: ManifestVideo) => [number, number] | null): Layer[] {
const frame: Rect = [0, 0, W, H]
const opaque = videos.filter((v) => (v.opacity ?? 1) >= SEEN)
const shown = opaque.length ? opaque : [...videos].sort((a, b) => (b.opacity ?? 1) - (a.opacity ?? 1)).slice(0, 1)
const out: Layer[] = []
for (const v of shown) {
if (!v.box || v.box.length < 4) continue
const size = sizeOf(v)
if (!size) continue
const seen = meet(meet(v.box as Rect, (v.clip as Rect | undefined) ?? frame) ?? [0, 0, 0, 0], frame)
if (!seen) continue
const draw = drawn(v, size[0], size[1], size)
const round = (x: number) => Math.round(x * 1000) / 1000
const x0 = Math.max(0, (seen[0] - draw[0]) / draw[2])
const y0 = Math.max(0, (seen[1] - draw[1]) / draw[3])
const x1 = Math.min(1, (seen[0] + seen[2] - draw[0]) / draw[2])
const y1 = Math.min(1, (seen[1] + seen[3] - draw[1]) / draw[3])
if (x1 <= x0 || y1 <= y0) continue
out.push({ v, size, draw, seen, crop: [round(x0), round(y0), round(x1 - x0), round(y1 - y0)] })
}
return out
}
/** the scene read of the part of a source frame a layer shows (its crop, at the reader's size, as the export's reader
* sees it: a face half out of the shot is read as the export reads it) */
export type Source = { scene: NonNullable<Scene>; faces: NonNullable<Faces> }
/** what a frame of the cut shows, from the scenes of the parts of the source frames its videos show: each one's things,
* faces and person mask mapped through its crop and its drawn box into the cut's frame (SIDE wide), and hidden where a
* video is drawn over it. A video's edge inside the frame is a seam (a split screen, a picture in a picture). Null
* when no video shows there */
export function compose(all: Layer[], W: number, H: number, sourceOf: (l: Layer) => Source | null): { scene: Scene; faces: Faces } {
const k = SIDE / Math.min(W, H)
const w = Math.round(W * k)
const h = Math.round(H * k)
const layers = all.flatMap((l) => {
const src = sourceOf(l)
return src ? [{ ...l, src }] : []
})
if (!layers.length) return { scene: null, faces: null }
type Read = (typeof layers)[number]
// a box in a crop's scene, in the cut's pixels
const toCut = (l: Read, t: readonly unknown[]): Rect => {
const [x, y, bw, bh] = [0, 1, 2, 3].map((i) => Number(t[i]) || 0)
const sx = (v: number) => (l.crop[0] + (v / l.src.scene.w) * l.crop[2]) * l.draw[2]
const sy = (v: number) => (l.crop[1] + (v / l.src.scene.h) * l.crop[3]) * l.draw[3]
return [l.draw[0] + sx(x), l.draw[1] + sy(y), sx(x + bw) - sx(x), sy(y + bh) - sy(y)]
}
const scaled = (r: Rect): [number, number, number, number] => [r[0] * k, r[1] * k, r[2] * k, r[3] * k]
// what of a box is seen: inside its layer's visible box, and not hidden by a layer over it
const seenOf = (i: number, b: readonly unknown[]): Rect | null => {
const l = layers[i]
const r = toCut(l, b)
const vis = meet(r, l.seen)
if (!vis || area(vis) < VISIBLE * area(r)) return null
for (const o of layers.slice(i + 1)) if (area(meet(vis, o.seen)) >= HIDDEN * area(vis)) return null
return vis
}
const things: Thing[] = []
const faces: Thing[] = []
layers.forEach((l, i) => {
for (const t of l.src.scene.things) {
const r = seenOf(i, t)
if (r) things.push([...scaled(r), t[4], t[5]] as Thing)
}
for (const f of l.src.scene.faces) {
const r = seenOf(i, f)
if (r) faces.push([...scaled(r), "face", Number(f[5] ?? f[4]) || 0] as Thing)
}
})
// the person mask: each cell's centre, in the topmost layer that shows there, read from its crop's grid
const cols = Math.round(w / CELL)
const rows = Math.round(h / CELL)
const people: string[] = []
for (let r = 0; r < rows; r++) {
let line = ""
for (let c = 0; c < cols; c++) {
const x = ((c + 0.5) / cols) * W
const y = ((r + 0.5) / rows) * H
const l = layers.findLast((o) => x >= o.seen[0] && x < o.seen[0] + o.seen[2] && y >= o.seen[1] && y < o.seen[1] + o.seen[3])
if (!l) {
line += "0"
continue
}
const g = l.src.scene.grid
const sc = Math.floor((((x - l.draw[0]) / l.draw[2] - l.crop[0]) / l.crop[2]) * g.cols)
const sr = Math.floor((((y - l.draw[1]) / l.draw[3] - l.crop[1]) / l.crop[3]) * g.rows)
line += g.people[sr]?.[sc] ?? "0"
}
people.push(line)
}
// a video's edge inside the frame: a seam, where it shows over a good part of the frame's other side
const seams: media.Seam[] = []
for (const l of layers) {
const [x, y, sw, sh] = l.seen
if (sw >= W * 0.5) for (const e of [y, y + sh]) if (e > H * 0.02 && e < H * 0.98) seams.push(["h", Math.round(e * k), sw / W])
if (sh >= H * 0.5) for (const e of [x, x + sw]) if (e > W * 0.02 && e < W * 0.98) seams.push(["v", Math.round(e * k), sh / H])
}
const texts = layers.flatMap((l, i) => (l.src.scene.texts ?? []).flatMap((t) => {
const r = seenOf(i, t)
return r ? [[...scaled(r), t[4], t[5]] as [number, number, number, number, string, number]] : []
}))
return {
scene: { w, h, grid: { cols, rows, people }, things, faces, texts },
faces: { w, h, faces: faces.map((f) => [f[0], f[1], f[2], f[3], f[5]]), seams },
}
}
/** what a plan's cut says: each voice clip's take's words that fall inside it, laid where the clip puts them (a word
* the clip cuts into is said if most of it is inside; the sound pack holds the cut itself) */
export function said(clips: Clip[], fps: number, wordsOf: (src: string) => Word[] | null): Word[] {
const out: Word[] = []
for (const c of clips) {
if (busOf(c) !== "voice") continue
const ws = wordsOf(c.src)
if (!ws) continue
const a = c.at
const b = c.at + (c.to - c.from) / fps
for (const w of ws) {
const inside = Math.min(b, w.end) - Math.max(a, w.start)
// a word the clip cuts into is heard when much of it is in (a transcriber hears half a word)
if (inside <= 0 || inside < Math.min(0.12, 0.4 * Math.max(0.01, w.end - w.start))) continue
const shift = c.from / fps - a
out.push({ text: w.text, start: Math.max(c.from / fps, w.start + shift), end: Math.min(c.to / fps, w.end + shift) })
}
}
return out.sort((x, y) => x.start - y.start)
}
/** a plan's frames by number */
export function byFrame(m: Manifest): Map<number, NonNullable<Manifest["frames"]>[number]> {
return new Map((m.frames ?? []).map((f) => [Number(f.frame), f]))
}
type Line = [number, number, number, number, string, number]
/** a text laid out on `n` lines, as the reader reads it: a line each, its words shared out by their letters (where
* layout broke it isn't in the manifest, only how many lines it made) */
export function linesOf(text: string, b: number[], n: number): Line[] {
const words = text.split(/\s+/).filter(Boolean)
if (n <= 1 || words.length < 2) return [[b[0], b[1], b[2], b[3], text, 1]]
const k = Math.min(n, words.length)
const total = words.reduce((s, w) => s + w.length + 1, 0)
const parts: string[][] = Array.from({ length: k }, () => [])
let at = 0
for (const w of words) {
// each word on the line its middle letter falls on
parts[Math.min(k - 1, Math.floor(((at + w.length / 2) / total) * k))].push(w)
at += w.length + 1
}
return parts.flatMap((p, l) => (p.length ? [[b[0], b[1] + (b[3] * l) / k, b[2], b[3] / k, p.join(" "), 1] as Line] : []))
}
/** the frame nearest a time, and the text it shows, as the scene reader would read lines: [x, y, w, h, text, score] in
* the pixels of a frame `h` high, a text laid out on several lines a line each */
export function textFrames(m: Manifest, at: number[]): { h: number; lines: Line[] }[] {
const fps = Number(m.fps) || 30
const H = Number(m.height) || 1920
const frames = byFrame(m)
return at.map((t) => {
const fr = frames.get(Math.round(t * fps))
const lines = (fr?.text ?? []).filter((x) => (x.opacity ?? 1) > 0.3 && String(x.text ?? "").trim()).flatMap((x) => linesOf(String(x.text).trim(), (x.ink ?? x.box ?? [0, 0, 0, 0]) as number[], Number(x.lines) || 1))
return { h: H, lines }
})
}
/** a frame's opaque fills over the whole frame: a cut's backgrounds are on every frame, so a frame with more than the
* fewest any frame with a video has holds a card over its videos (an end card), which hides them. (The manifest says
* where a fill is, not whether it's over a video or under it.) */
const covers = (fr: NonNullable<Manifest["frames"]>[number] | undefined, W: number, H: number) =>
(fr?.pictures ?? []).filter((p) => (p.opacity ?? 1) >= 0.9 && p.box && p.box[0] <= 1 && p.box[1] <= 1 && p.box[0] + p.box[2] >= W - 1 && p.box[1] + p.box[3] >= H - 1).length
// ---- the source frames' scenes, read by the farm and kept ------------------------------------------------------------
type Kept = { stamp: string; side: number; at: Record<string, Source> }
/** a read's key in a source's keeping: its second and its crop */
export const readKey = (at: number, crop: Rect) => `${at.toFixed(2)} ${crop.join(",")}`
type Want = { file: string; at: number; crop: Rect }
/** parts of source frames read for a plan, each (file, second, crop) once: from review/scenes/ when read before, else
* extracted (several ffmpeg at once where there's a shell) and read by the farm. Unmet when there's no farm here */
export async function sourceScenes(root: string, wants: Want[]): Promise<Map<string, Source>> {
const out = new Map<string, Source>()
const byFile = new Map<string, Map<string, Want>>()
for (const w of wants) byFile.set(w.file, (byFile.get(w.file) ?? new Map()).set(readKey(w.at, w.crop), w))
const dir = path.join(root, "review", "scenes")
for (const [file, mine] of byFile) {
const st = statSync(file)
const stamp = `${Math.round(st.mtimeMs)} ${st.size}`
const keep = path.join(dir, `${path.basename(file)}.json`)
let kept: Kept = { stamp, side: SIDE, at: {} }
try {
const k = JSON.parse(readFileSync(keep, "utf8")) as Kept
if (k.stamp === stamp && k.side === SIDE) kept = k
} catch {}
const need = [...mine.entries()].filter(([k]) => !kept.at[k])
if (need.length) {
const read = await readAt(file, need.map(([, w]) => w))
need.forEach(([k], i) => {
const s = read.scenes[i]
const f = read.faces[i]
if (s && f) kept.at[k] = { scene: s, faces: f }
})
try {
mkdirSync(dir, { recursive: true })
// read again just before writing: a plan of another cut may have read other frames of the same file meanwhile
try {
const now = JSON.parse(readFileSync(keep, "utf8")) as Kept
if (now.stamp === stamp && now.side === SIDE) kept.at = { ...now.at, ...kept.at }
} catch {}
const tmp = `${keep}.${process.pid}.tmp`
writeFileSync(tmp, JSON.stringify(kept))
renameSync(tmp, keep)
} catch {}
}
for (const k of mine.keys()) if (kept.at[k]) out.set(`${file}@${k}`, kept.at[k])
}
return out
}
/** parts of a file's frames (a second and a crop, in shares of the picture), read by the farm's scene reader at the
* reader's size, as the export's reader reads that part of the cut's frame */
async function readAt(file: string, wants: Want[]): Promise<{ faces: Faces[]; scenes: Scene[] }> {
if (!process.env.RAEA_CLOUD_GPU_URL) throw new media.Unmet(`no scene reader on this machine for ${path.basename(file)}'s frames (people, faces and things are read by raea cloud's farm: set RAEA_CLOUD_GPU_URL)`)
const dir = mkdtempSync(path.join(os.tmpdir(), "raea-plan-"))
try {
const scale = `scale='if(gt(iw,ih),-2,${SIDE})':'if(gt(iw,ih),${SIDE},-2)'`
const jpgs = wants.map((_, i) => path.join(dir, `f${String(i + 1).padStart(5, "0")}.jpg`))
const one = (w: Want, i: number) => {
const [x, y, cw, ch] = w.crop
const crop = `crop=iw*${cw}:ih*${ch}:iw*${x}:ih*${y}`
return ["-v", "error", "-y", "-ss", w.at.toFixed(3), "-i", file, "-frames:v", "1", "-vf", `${crop},${scale}`, "-q:v", "4", jpgs[i]]
}
if (process.platform !== "win32" && spawnSync("ffmpeg", ["-version"], { encoding: "utf8" }).status === 0) {
// eight at a time through the shell: this runtime has only spawnSync, and a plan reads 60-80 frames
const q = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
const lines = wants.map((w, i) => `ffmpeg ${one(w, i).map(q).join(" ")} &${(i + 1) % 8 === 0 ? "\nwait" : ""}`)
spawnSync("sh", ["-c", `${lines.join("\n")}\nwait`], { encoding: "utf8", maxBuffer: 1 << 24 })
}
wants.forEach((w, i) => {
if (!existsSync(jpgs[i])) media.ffmpeg(one(w, i))
})
return await media.readScenes(jpgs.map((j) => (existsSync(j) ? readFileSync(j) : null)))
} finally {
rmSync(dir, { recursive: true, force: true })
}
}
/** a video file's picture as decoded: its width and height, swapped when it's stored rotated a quarter turn */
export function pictureOf(file: string): [number, number] | null {
const r = spawnSync("ffprobe", ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height:stream_tags=rotate:stream_side_data=rotation", "-of", "json", file], { encoding: "utf8" })
try {
const s = JSON.parse(r.stdout ?? "").streams?.[0]
if (s?.width) {
const rot = Math.abs(Number(s.tags?.rotate ?? s.side_data_list?.find((d: { rotation?: number }) => d.rotation !== undefined)?.rotation ?? 0)) % 180
return rot === 90 ? [s.height, s.width] : [s.width, s.height]
}
} catch {}
const sh = media.shape(file)
return sh ? [sh.width, sh.height] : null
}
/** the scenes of a plan's frames, RATE a second: each composed from the parts of its videos' source frames it shows
* (`file`: a source on this machine, or null) */
export async function planScene(root: string, m: Manifest, file: (src: string) => string | null): Promise<{ rate: number; faces: Faces[]; scenes: Scene[] }> {
const W = Number(m.width) || 1080
const H = Number(m.height) || 1920
const fps = Number(m.fps) || 30
const at = samples(m)
const frames = byFrame(m)
const withVideo = [...frames.values()].filter((f) => f.videos?.length)
const backgrounds = withVideo.length ? Math.min(...withVideo.map((f) => covers(f, W, H))) : 0
const missing = new Set<string>()
const sizes = new Map<string, [number, number] | null>()
const sizeOf = (v: ManifestVideo) => {
const f = file(v.src)
if (!f) {
missing.add(v.src)
return null
}
if (!sizes.has(f)) sizes.set(f, pictureOf(f))
return sizes.get(f) ?? null
}
const shows = at.map((t) => {
const fr = frames.get(Math.round(t * fps))
return covers(fr, W, H) > backgrounds ? [] : layersOf((fr?.videos ?? []) as ManifestVideo[], W, H, sizeOf)
})
const wants = shows.flatMap((ls) => ls.map((l) => ({ file: file(l.v.src)!, at: l.v.at, crop: l.crop })))
if (!wants.length && missing.size) throw new media.Unmet(`the plan's videos aren't on this machine (${[...missing].slice(0, 3).join(", ")}), so what its frames show can't be read`)
const read = await sourceScenes(root, wants)
const out = shows.map((ls) => compose(ls, W, H, (l) => read.get(`${file(l.v.src)}@${readKey(l.v.at, l.crop)}`) ?? null))
return { rate: media.RATE, faces: out.map((o) => o.faces), scenes: out.map((o) => o.scene) }
}
// ---- the floor's text rules, from the plan (apps/check/text's text_runs and text_rules) --------------------------------
export type Run = { text: string; from: number; to: number; box: Rect; boxes: Rect[]; size: number }
/** a text as it stays on screen, from the frame it comes on to the frame it leaves; typing (a text growing into the next)
* and counting (only its digits changing) are one run, judged by its last text */
export function textRuns(m: Manifest): Run[] {
const fps = Number(m.fps) || 30
const key = (s: string) => s.replace(/[0-9]/g, "").trim().toLowerCase()
let open: Run[] = []
const done: Run[] = []
for (const f of [...(m.frames ?? [])].sort((a, b) => a.frame - b.frame)) {
const t = Number(f.frame) / fps
const next: Run[] = []
for (const x of f.text ?? []) {
const text = String(x.text ?? "").trim()
if ((x.opacity ?? 1) <= 0.05 || !text) continue
const quad = (b?: number[]): Rect | null => (b ? [0, 1, 2, 3].map((i) => Number(b[i]) || 0) as Rect : null)
const b = quad(x.box) ?? [0, 0, 0, 0]
const ink = quad(x.ink)
const k = key(text)
const i = open.findIndex((r) => {
const rk = key(r.text)
return rk === k || (rk !== "" && k.startsWith(rk)) || (k !== "" && rk.startsWith(k) && k.length * 2 > rk.length)
})
const r: Run = i >= 0 ? open.splice(i, 1)[0] : { text, from: t, to: t, box: b, boxes: [], size: 0 }
if (text.length > r.text.length) r.boxes = []
if (text.length >= r.text.length) {
r.text = text
r.box = b
r.boxes.push(ink ?? b)
}
r.to = t + 1 / fps
r.size = Number(x.size) || 0
next.push(r)
}
done.push(...open)
open = next
}
done.push(...open)
return done.sort((a, b) => a.from - b.from)
}
/** the zones where text can't go, [top, right, bottom, left] at the frame's width (apps/check/text zones(): default) */
export function zones(w: number, h: number): [number, number, number, number] {
const r = w / h
const z: [number, number, number, number] | null = r < 0.7 ? [220, 140, 420, 60] : r < 0.9 ? [110, 60, 170, 60] : r < 1.2 ? [70, 60, 120, 60] : null
if (!z) return [(120 * h) / 1080, (60 * w) / 1920, (120 * h) / 1080, (60 * w) / 1920]
return z.map((v) => (v * w) / 1080) as [number, number, number, number]
}
const quote = (s: string) => `“${[...s].slice(0, 40).join("")}”`
/** what `raea check` says of a render's text from its manifest: clipped off the frame (an error), in the app's UI zones
* (an error), up too briefly to read (a warning, the reading pack holds it to its words) */
export function textRules(m: Manifest): { level: "error" | "warn"; rule: string; at: number; says: string }[] {
const w = Number(m.width) || 1080
const h = Number(m.height) || 1920
const [zt, zr, zb, zl] = zones(w, h)
const out: { level: "error" | "warn"; rule: string; at: number; says: string }[] = []
for (const r of textRuns(m)) {
const [x, y, bw, bh] = r.box
const q = quote(r.text)
const boxes = r.boxes.length ? r.boxes : [r.box]
const off = ([x, y, bw, bh]: Rect) => x < -1 || y < -1 || x + bw > w + 1 || y + bh > h + 1
const zoned = ([x, y, bw, bh]: Rect) => y < zt || x + bw > w - zr || y + bh > h - zb || x < zl
if (boxes.every(off)) out.push({ level: "error", rule: "clipped", at: r.from, says: `${q} runs off the frame (box ${x.toFixed(0)},${y.toFixed(0)} ${bw.toFixed(0)}x${bh.toFixed(0)} in ${w}x${h}); fit it or break the line` })
else if (boxes.every(zoned)) {
const [ix, iy, iw, ih] = boxes[boxes.length - 1]
const edge = iy < zt ? `the top (keep ${zt.toFixed(0)} px clear)` : iy + ih > h - zb ? `the bottom (keep ${zb.toFixed(0)} px clear)` : ix < zl ? `the left (keep ${zl.toFixed(0)} px clear)` : `the right (keep ${zr.toFixed(0)} px clear)`
out.push({ level: "error", rule: "safe-area", at: r.from, says: `${q} sits in the app's UI zone at ${edge}: its ${r.boxes.length && boxes[boxes.length - 1] !== r.box ? "letters" : "box"} ${ix.toFixed(0)},${iy.toFixed(0)} ${iw.toFixed(0)}x${ih.toFixed(0)} in ${w}x${h}` })
}
const words = r.text.split(/\s+/).filter(Boolean).length
const need = Math.max(1, 0.3 * words)
const held = r.to - r.from
if (held + 0.05 < need && r.size >= 24) out.push({ level: "warn", rule: "reading", at: r.from, says: `${q} is on for ${held.toFixed(1)} s; ${words} words need ${need.toFixed(1)} s to read` })
}
return out
}
/** the fix a UI-zone finding asks for, said once */
export const ZONE_FIX = "keep text inside the safe area: 220 px from the top, 420 px from the bottom, 140 px from the right and 60 px from the left of a 1080x1920 frame"
+17 -54
View File
@@ -3,9 +3,6 @@
// several in order (a workflow): each is checked alone, and the report says each one's verdict and the whole's.
//
// raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
// (EDIT.tsx --at edit --manifest OUT.plan.json: one cut of the composition checked on its plan, `raea render
// --plan`, before it's drawn: plan.ts. Only that cut's file checks run, only what the plan knows exactly is an
// error, and a check that can't run waits, so exit 1 always names something in the cut to fix)
// the project is the folder with brief.ts (from FILE's folder or this one, upwards); its goals are brief.ts's
// `goal`, and with none, the floor (every made video looked at, its faces whole and its text big enough). The
// files are the ones named, else (publish, done) every deliverable and every video or still made under out/.
@@ -17,13 +14,12 @@
// raea goal tasks [DIR] [--json] | --apply EDITS.json|- the brief's plan as tasks, and edits written back (tasks.ts)
// raea goal seen FILE "WHAT" [--surprise "S s: WHAT"] what was seen of FILE as it is now, and its surprise
// raea goal judge [--goal NAME] a goal's `says` rules judged now (review/judge/); raea goal check asks it itself
import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs"
import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
import path from "node:path"
import { pathToFileURL } from "node:url"
import { type Check, type Finding, type Moment, MOMENTS, runOnce, type Threw } from "raea/check"
import { type Contract, type Goals, goalsOf, momentsOf, nameOf, packsOf, saysOf, unknownPacks } from "./contract.ts"
import { fileFacts, type FileFacts, type Job, kindOf, planFacts, runIn } from "./facts.ts"
import { COMPOSITION, ON_PLAN_WARNS, PLAN_SOFT } from "./plan.ts"
import { fileFacts, type FileFacts, type Job, kindOf, runIn } from "./facts.ts"
import * as media from "./media.ts"
import { registeredPack } from "./packs/job.ts"
import { tastePack } from "./packs/taste.ts"
@@ -141,22 +137,13 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
const broke: Report["broke"] = []
const keep = (goal: string | null, file: FileFacts | null, r: { findings: Finding[]; threw: Threw[] }) => {
const fps = file?.fps ?? 30
for (const x of r.findings) {
// on a plan, what's read from the source frames or held against the takes' words is told, not held (ON_PLAN_WARNS)
const soft = file?.plan && x.level === "error" && ON_PLAN_WARNS.has(x.check)
findings.push({ goal, check: x.check, level: soft ? "warn" : x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: soft ? `${x.says}${PLAN_SOFT}` : x.says, fix: x.fix, by: x.by })
}
// on a plan, a check that couldn't run (the farm busy or down, a frame that wouldn't extract) waits: nothing in the
// cut to fix, and the render's own check runs it again
for (const t of r.threw) (t.waits || file?.plan ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.waits || !file?.plan ? t.says : `couldn't check the plan, so the render's check holds it: ${t.says}` })
for (const x of r.findings)
findings.push({ goal, check: x.check, level: x.level, file: file?.path ?? (x.about[0]?.name ?? null), seconds: x.frames ? [x.frames[0] / fps, x.frames[1] / fps] : null, says: x.says, fix: x.fix, by: x.by })
for (const t of r.threw) (t.waits ? waits : broke).push({ check: t.check, file: file?.path ?? null, says: t.says })
}
const job = (contract: Contract | null, deliverables: string[], files: FileFacts[]): Job => ({ root, brief, briefText: null, contract, project, moment: at, deliverables, files, run: runIn(root) })
// a composition named with a manifest: one of its cuts checked on its plan (`raea render --plan`), before it's drawn
// (plan.ts). It holds that cut alone: the project's own checks and the goals' job checks (the count, the brief's
// quotes) are the render's and publish's to hold, never a reason not to draw one cut
const planned = cutPlan(o.manifest, named, cwd)
// the project's own: once, whatever its goals
const once = planned ? [] : ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
const once = ALWAYS.filter((c) => momentsOf(c).includes(at) && (!o.only?.length || o.only.includes(c.id)))
for (const c of once) keep(null, null, await runOnce([{ check: c, on: job(null, [], []) }]))
const verdicts: GoalVerdict[] = []
const allFiles = new Set<string>()
@@ -168,16 +155,10 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
: at === "publish" || at === "done"
? [...new Set([...deliverables.flatMap((d) => d.split("|")).filter((d) => !d.endsWith("/") && existsSync(path.join(root, d))), ...madeUnder(root)])]
: []
// a cut's plan (above), else a render's manifest kept away from its export (`raea render --manifest M`): the one
// file named reads it
const files: FileFacts[] = planned
? [planFacts(planned.manifest, planned.abs, root, at, contract)]
: wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
if (o.manifest && !planned && files.length === 1) {
files[0].manifest = JSON.parse(readFileSync(path.resolve(cwd, o.manifest), "utf8")) as FileFacts["manifest"]
files[0].fps = files[0].manifest?.fps ?? files[0].fps
}
const checks = checksOf(contract, at, o.only).filter((c) => !planned || c.over !== "job")
const files: FileFacts[] = wanted.filter((f) => existsSync(path.join(root, f)) && statSync(path.join(root, f)).isFile()).map((f) => fileFacts(f, root, at, contract))
// a render's manifest kept away from its export (`raea render --manifest M`): the one file named reads it
if (o.manifest && files.length === 1) files[0].manifest = JSON.parse(readFileSync(path.resolve(o.manifest), "utf8")) as FileFacts["manifest"]
const checks = checksOf(contract, at, o.only)
const before = findings.length
const brokeBefore = broke.length
const j = job(contract, deliverables, files)
@@ -210,32 +191,16 @@ export async function goalCheck(o: { files?: string[]; at?: Moment; goal?: strin
}
}
/** a composition's plan: `--manifest` naming a plan (or any manifest) with one composition named */
export function cutPlan(manifest: string | undefined, named: string[], cwd = process.cwd()): { abs: string; manifest: FileFacts["manifest"] & object } | null {
if (!manifest || named.length !== 1 || !COMPOSITION.test(named[0])) return null
const abs = path.resolve(cwd, manifest)
return { abs, manifest: JSON.parse(readFileSync(abs, "utf8")) }
}
/** written whole or not at all: plans of several cuts are checked at once, each writing review/goal.json */
const writeWhole = (p: string, text: string) => {
const tmp = `${p}.${process.pid}.tmp`
writeFileSync(tmp, text)
renameSync(tmp, p)
}
/** the report written where the review, the hook and raea cloud read it: review/goal.json, and FILE.check.json beside
* each file named (a plan's beside the plan: OUT.plan.check.json) */
export function writeReport(r: Report, named: string[], plan?: string) {
* each file named */
export function writeReport(r: Report, named: string[]) {
const dir = path.join(r.root, "review")
mkdirSync(dir, { recursive: true })
writeWhole(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
const one = (f: string, out: string) => {
writeFileSync(path.join(dir, "goal.json"), `${JSON.stringify(r, null, 1)}\n`)
for (const f of named) {
const mine = r.findings.filter((x) => x.file === f)
writeWhole(out, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
writeFileSync(`${media.stem(path.join(r.root, f))}.check.json`, `${JSON.stringify({ object: "goal.check.file", at: r.at, file: f, passed: !mine.some((x) => x.level === "error"), findings: mine }, null, 1)}\n`)
}
for (const f of named) one(f, `${media.stem(path.join(r.root, f))}.check.json`)
if (plan) for (const f of r.files) one(f, `${media.stem(plan)}.check.json`)
}
const secs = (s: [number, number] | null) => (!s ? "" : s[1] - s[0] <= 0.1 ? `${s[0].toFixed(1)} s ` : `${s[0].toFixed(1)}-${s[1].toFixed(1)} s `)
@@ -261,8 +226,7 @@ function flag(a: string[], name: string): string | undefined {
}
const positional = (a: string[], valued: string[]) => a.filter((x, i) => !x.startsWith("-") && !valued.includes(a[i - 1] ?? ""))
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--manifest M] [--json]
raea goal check EDIT.tsx --at edit --manifest OUT.plan.json (a cut checked on its plan, raea render --plan, before it's drawn)
const USAGE = `raea goal check [FILE...] [--at edit|render|publish|done] [--goal NAME] [--only ID,...] [--json]
raea goal tasks [DIR] [--json] | raea goal tasks [DIR] --apply EDITS.json|-
raea goal seen FILE (its contact sheet and its frames at full size, to look at)
raea goal seen FILE "what you see and would change" --look "its design at full size, beside a reference" [--surprise "SECONDS s: what it is"]
@@ -285,8 +249,7 @@ export async function main(argv: string[]): Promise<number> {
console.error(`raea goal check: ${(e as Error).message}`)
return 2
}
const plan = cutPlan(flag(a, "--manifest"), files.map((n) => path.relative(r.root, path.resolve(n))))
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))), plan?.abs)
writeReport(r, r.files.filter((f) => files.some((n) => path.resolve(n) === path.join(r.root, f))))
console.log(a.includes("--json") ? JSON.stringify(r, null, 1) : text(r))
return r.passed ? 0 : 1
}
-201
View File
@@ -1,201 +0,0 @@
// A cut checked on its plan before it's drawn (src/plan.ts): what its frames show read from its sources' frames, what it
// says from its takes' words, and the floor's text rules on every frame
import { expect, test } from "bun:test"
import { existsSync, readFileSync } from "node:fs"
import path from "node:path"
import { type Answer, useSender } from "../src/media.ts"
import { compose, drawn, layersOf, linesOf, PLAN_SOFT, said, samples, textRules, textRuns } from "../src/plan.ts"
import { goalCheck, text, writeReport } from "../src/run.ts"
import { CLIP, project, put } from "./project.ts"
const full = (over: Record<string, unknown> = {}) => ({ src: "a.mp4", at: 1, box: [0, 0, 1080, 1920], fit: "cover", ...over })
test("a video is drawn by its fit and object-position, and what of it the frame shows is its crop", () => {
// a 16:9 picture covering a 9:16 frame, centred: 3413 px wide, 1167 px of it off each side
const c = drawn(full(), 1920, 1080)
expect(c.map(Math.round)).toEqual([-1167, 0, 3413, 1920])
// object-position 76% across (as `position: [0, 0.76, 0, 0.5]` says it)
expect(Math.round(drawn(full({ position: [0, 0.76, 0, 0.5] }), 1920, 1080)[0])).toBe(Math.round(0.76 * (1080 - 3413.33)))
// contain letterboxes it; fill stretches it
expect(drawn(full({ fit: "contain" }), 1920, 1080).map(Math.round)).toEqual([0, 656, 1080, 608])
expect(drawn(full({ fit: "fill" }), 1920, 1080)).toEqual([0, 0, 1080, 1920])
const [l] = layersOf([full() as never], 1080, 1920, () => [1920, 1080])
expect(l.crop).toEqual([0.342, 0, 0.316, 1])
// a box clipped by its parent (`clip`) shows only that part of it
const [h] = layersOf([full({ box: [-566, 0, 4096, 2304], clip: [0, 0, 1080, 1920] }) as never], 1080, 1920, () => [3840, 2160])
expect(h.seen).toEqual([0, 0, 1080, 1920])
expect(h.crop[3]).toBeCloseTo(1920 / 2304, 3)
// a fading video is left out while another shows; alone it's what's seen
expect(layersOf([full() as never, full({ opacity: 0.2 }) as never], 1080, 1920, () => [1920, 1080])).toHaveLength(1)
})
test("a source's scene, read of its crop, lands in the cut's frame: a face at the crop's edge is a face at the frame's", () => {
// the reader read the crop (304x540 of a 960x540 picture) at 540 wide: a face touching its right edge, a person
const scene = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array.from({ length: 48 }, (_, r) => (r > 20 ? "7".repeat(27) : "0".repeat(27))) }, things: [[100, 300, 300, 660, "person", 0.9]], faces: [[480, 200, 60, 80, "face", 0.9]] }
const faces = { w: 540, h: 960, faces: [[480, 200, 60, 80, 0.9]] }
const ls = layersOf([full() as never], 1080, 1920, () => [960, 540])
const out = compose(ls, 1080, 1920, () => ({ scene, faces }) as never)
expect(out.scene?.w).toBe(540)
const [x, y, w, h] = out.faces!.faces[0]
expect(Math.round(x + w)).toBe(540)
expect([Math.round(y), Math.round(h)]).toEqual([200, 80])
expect(out.scene!.grid.people[30]).toBe("7".repeat(27))
expect(out.scene!.things[0][4]).toBe("person")
// a video drawn over the bottom half hides what's under it there, and its top edge is a seam
const two = layersOf([full() as never, full({ box: [0, 960, 1080, 960] }) as never], 1080, 1920, () => [960, 540])
const low = { ...scene, things: [[100, 600, 300, 300, "dog", 0.9]] }
const o2 = compose(two, 1080, 1920, (l) => (l.v.box[1] ? ({ scene: { ...scene, things: [], faces: [] }, faces: { ...faces, faces: [] } } as never) : ({ scene: low, faces } as never)))
expect(o2.faces!.seams).toContainEqual(["h", 480, 1])
expect(o2.scene!.things).toEqual([])
})
test("what a plan's cut says is its voice clips' takes' words, where the clips put them", () => {
const take = [{ text: "one", start: 10, end: 10.4 }, { text: "two", start: 10.5, end: 10.9 }, { text: "three", start: 11, end: 11.5 }, { text: "four", start: 11.6, end: 12 }]
// frames 30-75 at 30 fps (1.0-2.5 s) show the take from 10.45 s: "one" is out, "three" whole, "four" cut a little
const w = said([{ from: 30, to: 75, src: "media/take.mp4", at: 10.45 }], 30, () => take)
expect(w.map((x) => x.text)).toEqual(["two", "three", "four"])
expect(w[0].start).toBeCloseTo(1.05, 5)
// music isn't speech
expect(said([{ from: 0, to: 30, src: "music/bed.mp3", at: 0 }], 30, () => take)).toEqual([])
})
test("the floor's text rules hold every frame of a plan: the UI zones, the frame's edges", () => {
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, text: [
{ text: "In the zone at the right", box: [100, 830, 900, 93], ink: [139, 830, 860, 93], size: 58 },
{ text: "Clear of everything", box: [200, 1000, 680, 93], size: 58 },
{ text: "Off the frame entirely here", box: [900, 1200, 600, 93], ink: [900, 1200, 600, 93], size: 58 },
] }))
const m = { width: 1080, height: 1920, fps: 30, length: 60, frames }
const r = textRules(m)
expect(r.map((x) => [x.rule, x.level])).toEqual([["safe-area", "error"], ["clipped", "error"]])
expect(r[0].says).toMatch(/sits in the app's UI zone at the right \(keep 140 px clear\)/)
// a typed text (growing into the next) is one run, judged by its last text
const typed = textRuns({ fps: 30, frames: ["Hel", "Hello", "Hello there"].map((t, f) => ({ frame: f, text: [{ text: t, box: [300, 900, 400, 80], size: 60 }] })) })
expect(typed.map((x) => x.text)).toEqual(["Hello there"])
expect(samples(m)).toEqual([0, 0.5, 1, 1.5])
// a text laid out on several lines is read a line each, as the export's reader reads it
expect(linesOf("Make your Wishlist and organize your Gift Exchange", [0, 100, 600, 200], 2).map((l) => l[4])).toEqual(["Make your Wishlist and", "organize your Gift Exchange"])
})
test("raea goal check --at edit --manifest PLAN EDIT.tsx: the cut's plan is checked, named for its export, before it's drawn", async () => {
const d = project(null)
put(d, "edit.tsx", "export default 1\n")
put(d, "media/take.mp4", readFileSync(CLIP))
const frames = Array.from({ length: 90 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Down in the bottom zone", box: [140, 1600, 800, 90], size: 60 }] }))
const plan = put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 90, plan: true, frames, sounds: { fps: 30, clips: [] } }))
// the farm's reader, standing in: every crop read has a face cut by its right edge
const before = process.env.RAEA_CLOUD_GPU_URL
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
let read = 0
useSender(async (_url, body): Promise<Answer> => {
const n = (JSON.parse(String(body)) as { frames: string[] }).frames.length
read += n
const g = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [[470, 300, 70, 120, "face", 0.9]], seams: [] }
return { status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(g) }) }
})
try {
const r = await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
const mine = r.findings.filter((x) => x.file === "out/cuts/ad_concept_v1_9x16.mp4")
expect(mine.some((x) => x.check === "floor" && x.level === "error" && /UI zone at the bottom/.test(x.says))).toBe(true)
// a face cut by the edge is read from the source frames: on a plan it's told, and the render's check holds it
expect(mine.some((x) => x.check === "frames" && x.level === "warn" && /right edge/.test(x.says) && x.says.endsWith(PLAN_SOFT))).toBe(true)
// only what the plan knows exactly holds it: floor, sound and text sizes
expect(mine.filter((x) => x.level === "error").every((x) => x.check === "floor" || x.check === "sound" || (x.check === "frames" && /px/.test(x.says)))).toBe(true)
expect(r.passed).toBe(false)
expect(read).toBe(6)
// each source frame's reading is kept: the plan checked again reads nothing
await goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan })
expect(read).toBe(6)
writeReport(r, [], plan)
expect(existsSync(path.join(d, "out/cuts/ad_concept_v1_9x16.plan.check.json"))).toBe(true)
} finally {
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
else process.env.RAEA_CLOUD_GPU_URL = before
}
})
/** a plan of one cut with nothing in it to fix: its text inside the safe area, over the test clip */
function cleanPlan(d: string, name = "out/cuts/ad_concept_v1_9x16.plan.json") {
put(d, "edit.tsx", "export default 1\n")
put(d, "media/take.mp4", readFileSync(CLIP))
const frames = Array.from({ length: 60 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: f / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: [{ text: "Safe in the middle", box: [140, 900, 800, 90], size: 60 }] }))
return put(d, name, JSON.stringify({ width: 1080, height: 1920, fps: 30, length: 60, plan: true, frames, sounds: { fps: 30, clips: [] } }))
}
/** the farm's reader, standing in for a test: `answer` gives each POST's reply */
async function withFarm<T>(answer: (n: number) => Answer, run: () => Promise<T>): Promise<T> {
const before = process.env.RAEA_CLOUD_GPU_URL
process.env.RAEA_CLOUD_GPU_URL = "http://farm.test"
useSender(async (_url, body) => answer((JSON.parse(String(body)) as { frames: string[] }).frames.length))
try {
return await run()
} finally {
if (before === undefined) delete process.env.RAEA_CLOUD_GPU_URL
else process.env.RAEA_CLOUD_GPU_URL = before
}
}
const EMPTY = { w: 540, h: 960, grid: { cols: 27, rows: 48, people: Array(48).fill("0".repeat(27)) }, things: [], faces: [], seams: [] }
test("a plan holds its own cut alone: the brief's count, its quotes and the project's checks don't stop it being drawn", async () => {
// the brief asks for 10 cuts, 1 is planned, and the open item about the count waits for a person (who answers at the
// first stop, after the first render); the brief's text isn't in the project either
const asked = { question: "Only 2 interviews came: cut fewer?", from: "10 total videos", about: "count" }
const d = project({ kind: "cut", packs: { naming: false }, cut: { brief: "media/brief.txt", count: { value: 10, from: "10 total videos" }, formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }], open: [asked] } })
const plan = cleanPlan(d)
const r = await withFarm(
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(EMPTY) }) }),
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
expect(r.checks).not.toContain("count")
expect(r.checks).not.toContain("quotes")
expect(r.checks).not.toContain("registered")
expect(r.passed).toBe(true)
// the same project checked at edit without a plan still holds the count
const whole = await goalCheck({ cwd: d, at: "edit" })
expect(whole.findings.some((x) => x.check === "count" && x.level === "error")).toBe(true)
})
test("a plan the farm can't read waits: nothing to fix, so it doesn't fail", async () => {
const d = project(null)
const plan = cleanPlan(d)
let asked = 0
const r = await withFarm(
() => {
asked++
return { status: 503, ok: false, text: "busy" }
},
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
expect(asked).toBeGreaterThan(0)
expect(r.broke).toEqual([])
expect(r.waits.map((w) => w.check)).toContain("frames")
expect(r.waits.find((w) => w.check === "frames")?.says).toMatch(/render's check holds it.*503/)
expect(r.errors).toBe(0)
expect(r.passed).toBe(true)
expect(text(r)).toMatch(/^PASSED .*waiting/m)
})
test("on a plan, text over a face and talking with no captions are warnings: the render's check holds them", async () => {
const d = project({ kind: "cut", packs: { naming: false }, cut: { formats: ["9:16"], cuts: [{ id: "ad_concept_v1" }] } })
// a caption with nothing said under it, straight over a face the farm reads in every frame
const plan = cleanPlan(d)
const m = JSON.parse(readFileSync(plan, "utf8"))
m.length = 240
m.frames = Array.from({ length: 240 }, (_, f) => ({ frame: f, videos: [{ src: "media/take.mp4", at: (f % 90) / 30, box: [0, 0, 1080, 1920], fit: "cover", opacity: 1 }], text: f < 60 ? [{ text: "Nobody says this at all", box: [140, 300, 800, 300], size: 60 }] : [] }))
// ... and from 5 s, past a text hook's opening, the take talks with no caption up
put(d, "media/take.words.json", JSON.stringify("so this is what we said".split(" ").map((t, i) => ({ text: t, start: 0.3 + i * 0.4, end: 0.6 + i * 0.4 }))))
m.sounds.clips = [{ key: "v", from: 150, to: 240, src: "media/take.mp4", at: 0 }]
put(d, "out/cuts/ad_concept_v1_9x16.plan.json", JSON.stringify(m))
const face = { ...EMPTY, faces: [[170, 150, 200, 200, "face", 0.95]] }
const r = await withFarm(
(n) => ({ status: 200, ok: true, text: JSON.stringify({ frames: Array(n).fill(face) }) }),
() => goalCheck({ cwd: d, files: [path.join(d, "edit.tsx")], at: "edit", manifest: plan }),
)
const soft = r.findings.filter((x) => x.says.endsWith(PLAN_SOFT))
expect(soft.length).toBeGreaterThan(0)
expect(soft.every((x) => x.level === "warn" && ["place", "captions", "reading", "frames"].includes(x.check))).toBe(true)
expect(soft.some((x) => x.check === "place" && /covers a face/.test(x.says))).toBe(true)
expect(soft.some((x) => x.check === "captions" && /no captions over the talking/.test(x.says))).toBe(true)
expect(r.findings.filter((x) => x.level === "error")).toEqual([])
expect(r.passed).toBe(true)
})
+10 -5
View File
@@ -19,20 +19,25 @@ const near = (a: number, b: number) => expect(Math.abs(a - b)).toBeLessThan(1e-6
describe("Region", () => {
test("auto takes the taller band clear of the face", () => {
renderFrame(<Region><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
// m = 65; top band 153.6..435, bottom band 1045..1536
// m = 65; clear of the UI zones (220 top, 420 bottom, 140 right): top band 220..435, bottom band 1045..1500
expect(got.name).toBe("auto");
expect(got.x).toBe(65); expect(got.w).toBe(875);
near(got.y, 1045); near(got.h, 455);
});
test("keepOut={false}: the older bands, 0.08 H to 0.80 H, inset by the margin alone", () => {
renderFrame(<Region keepOut={false}><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
expect(got.x).toBe(65); expect(got.w).toBe(950);
near(got.y, 1045); near(got.h, 491);
});
test("top and center by name", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
near(got.y, 153.6); near(got.h, 435 - 153.6);
near(got.y, 220); near(got.h, 435 - 220);
renderFrame(<Region name="center"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
near(got.y, 0.33 * 1920); near(got.h, 0.34 * 1920);
});
test("without a face: top is 0.08 H to 0.45 H, and auto picks it", () => {
test("without a face: top is the top zone's edge to 0.45 H, and auto picks it", () => {
renderFrame(<Region><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0 });
near(got.y, 153.6); near(got.h, 864 - 153.6);
near(got.y, 220); near(got.h, 864 - 220);
});
test("the safe area moves the edges", () => {
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { safe: { top: 200, bottom: 1500 } } });
@@ -49,7 +54,7 @@ describe("Region", () => {
const html = renderFrame(<Region name="bottom" />, { ...base, frame: 0, perception: { face } });
expect(html).toContain('data-region="bottom"');
expect(html).toContain("--face-top:500px");
expect(html).toContain("--region-height:491px");
expect(html).toContain("--region-height:455px");
});
});
+218
View File
@@ -0,0 +1,218 @@
// Safe defaults (12-04, round 22): text kept out of the app's UI zones by default, and a talking clip's ends moved off
// words, so the floor's safe-area rule and the sound pack's edit points (sdk/goal packs/sound.ts) aren't broken in the
// first place.
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { AbsoluteFill, Region, SafeArea, Sequence, Series, Video, snapClip, uiZones, useRegion, useUiZones } from "../src";
import { forgetTakeWords, takeWordsFiles } from "@raea/video/snap";
import { renderFrame } from "../src/test";
const base = { fps: 30, width: 1080, height: 1920, durationInFrames: 300, frame: 0 };
const attr = (html: string, name: string) => new RegExp(`${name}="([^"]*)"`).exec(html)?.[1];
let got: any;
function Ask({ f }: { f: () => any }) { got = f(); return null; }
describe("uiZones: the floor's zones (apps/check/text/src/lib.rs)", () => {
test("9:16 at 1080 x 1920, and each platform's", () => {
expect(uiZones(1080, 1920)).toEqual({ top: 220, right: 140, bottom: 420, left: 60 });
expect(uiZones(1080, 1920, { platform: "tiktok" })).toEqual({ top: 108, right: 120, bottom: 320, left: 60 });
expect(uiZones(1080, 1920, { platform: "reels" })).toEqual({ top: 210, right: 84, bottom: 310, left: 60 });
expect(uiZones(1080, 1920, { platform: "shorts" })).toEqual({ top: 120, right: 96, bottom: 300, left: 60 });
});
test("scaled with the width, and by shape", () => {
const z = uiZones(720, 1280);
expect(z.top).toBeCloseTo(220 * (720 / 1080), 9);
expect(z.bottom).toBeCloseTo(280, 9);
expect(uiZones(1080, 1350)).toEqual({ top: 110, right: 60, bottom: 170, left: 60 });
expect(uiZones(1080, 1080)).toEqual({ top: 70, right: 60, bottom: 120, left: 60 });
expect(uiZones(1920, 1080)).toEqual({ top: 120, right: 60, bottom: 120, left: 60 });
});
test("useUiZones reads the composition's size", () => {
renderFrame(<Ask f={() => useUiZones()} />, base);
expect(got).toEqual({ top: 220, right: 140, bottom: 420, left: 60 });
});
});
describe("text keeps out of the UI zones by default", () => {
test("a Region's bands start under the top zone, end over the bottom one and clear the right-hand buttons", () => {
renderFrame(<Region name="bottom"><Ask f={() => useRegion()} /></Region>, base);
// 0.55 H to 1920 - 420; across: 65 from the left (the margin), 140 from the right (the zone)
expect(got.y).toBeCloseTo(1056, 6);
expect(got.y + got.h).toBeCloseTo(1500, 6);
expect(got.x).toBe(65);
expect(got.x + got.w).toBe(940);
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, base);
expect(got.y).toBe(220);
});
test("keepOut={false} places it there on purpose: the older bands", () => {
renderFrame(<Region name="full" keepOut={false}><Ask f={() => useRegion()} /></Region>, base);
expect(got.y).toBeCloseTo(153.6, 6);
expect(got.y + got.h).toBeCloseTo(1536, 6);
expect(got.w).toBe(950);
});
test("a platform's zones, and perception's safe area over them", () => {
renderFrame(<Region name="full" platform="tiktok"><Ask f={() => useRegion()} /></Region>, base);
expect(got.y).toBe(108);
expect(got.y + got.h).toBe(1600);
renderFrame(<Region name="full"><Ask f={() => useRegion()} /></Region>, { ...base, perception: { safe: { top: 300, bottom: 1400 } } });
expect(got.y).toBe(300);
expect(got.y + got.h).toBe(1400);
});
test("SafeArea is a layer inset by the zones", () => {
const html = renderFrame(<SafeArea><div>Save 20% today</div></SafeArea>, base);
expect(html).toContain("left:60px");
expect(html).toContain("top:220px");
expect(html).toContain("width:880px");
expect(html).toContain("height:1280px");
expect(html).toContain("--ui-right:140px");
});
});
// a take's words, as raea words writes them: a pause after "first", two words that run together ("have" "found"),
// and two speakers over each other ("nervous" under "yeah")
const W = [
["So", 10.0, 10.2], ["first", 10.2, 10.6], ["we", 11.2, 11.35], ["have", 11.35, 11.53], ["found", 11.53, 11.8], ["it", 11.8, 11.95],
["are", 20.0, 20.15], ["you", 20.15, 20.25], ["nervous", 20.25, 20.79], ["yeah", 20.45, 21.17], ["fine", 22.0, 22.4],
].map(([text, s, e]) => ({ text: text as string, start: s as number, end: e as number }));
describe("snapClip: both ends in gaps, the clip moved whole", () => {
test("an in inside a word moves to the nearest gap; the clip keeps its length", () => {
// in at 10.5 cuts "first" (10.2-10.6): its gap after, 0.08 s before "we", is 0.62 s on, past the 0.4 s limit;
// the gap before it is at 10.2 (it runs on from "So"): -0.3 s
const s = snapClip(W, 10.5, 11.0);
expect(s.by).toBeCloseTo(-0.3, 6);
expect(s.moved[0]).toMatchObject({ edge: "in", word: "first" });
expect(s.left).toEqual([]);
});
test("a split between two clips inside a word moves both to the same boundary", () => {
// "have" 11.35-11.53 runs into "found": a cut at 11.45 goes to 11.53 for the clip that ends there and the one
// that starts there, so nothing plays twice or not at all
const a = snapClip(W, 10.9, 11.45);
const b = snapClip(W, 11.45, 13.0);
expect(a.by).toBeCloseTo(0.08, 6);
expect(b.by).toBeCloseTo(0.08, 6);
});
test("a cut on a boundary where words run together is tight, not cut (the sound pack warns): it stays", () => {
expect(snapClip(W, 10.9, 11.5).by).toBe(0);
});
test("an out inside a word, with its in clear", () => {
const s = snapClip(W, 9.5, 11.9);
// out at 11.9 cuts "it" (11.8-11.95): its start, where "found" runs into it, is -0.1 s, but 0.08 s after it, in a
// gap, is +0.13 s, and a gap is cleaner than a boundary between words
expect(s.by).toBeCloseTo(0.13, 6);
expect(s.moved).toEqual([expect.objectContaining({ edge: "out", word: "it" })]);
});
test("ends clear of words stay where they are", () => {
expect(snapClip(W, 10.8, 13.0)).toEqual({ by: 0, moved: [], left: [] });
expect(snapClip(W, 10.8, Infinity)).toEqual({ by: 0, moved: [], left: [] });
});
test("speech with no gap within 0.4 s (people over each other): it stays, and says the end it couldn't clear", () => {
const over = [["one", 0, 1.0], ["two", 0.9, 2.0], ["three", 1.9, 3.0]].map(([text, s, e]) => ({ text: text as string, start: s as number, end: e as number }));
const s = snapClip(over, 0, 1.5);
expect(s.by).toBe(0);
expect(s.left).toEqual([{ edge: "out", at: 1.5, word: "two" }]);
});
});
describe("a Video on a talking take snaps", () => {
const words = JSON.stringify(W.map((w) => ({ text: w.text, start_ms: Math.round(w.start * 1000), end_ms: Math.round(w.end * 1000) })));
const asked: string[] = [];
let warn: ReturnType<typeof spyOn>;
beforeEach(() => {
forgetTakeWords();
asked.length = 0;
(globalThis as any).__raea_call = (name: string, json: string) => {
if (name !== "asset.read") throw new Error(`no ${name} here`);
const { path } = JSON.parse(json);
asked.push(path);
if (path !== "/media/take01.words.json") throw new Error(`asset ${path}: not found`);
return JSON.stringify({ path, base64: btoa(words) });
};
warn = spyOn(console, "warn").mockImplementation(() => {});
});
afterEach(() => {
delete (globalThis as any).__raea_call;
warn.mockRestore();
forgetTakeWords();
});
// a clip from 10.5 s for 15 frames, placed in the edit's tree: its in cuts "first"
const clip = (props: object = {}, frame = 0) =>
renderFrame(<AbsoluteFill><Sequence from={0} durationInFrames={15}><Video src="/media/take01.mp4" startFrom={10.5 * 30} endAt={10.5 * 30 + 15} {...props} /></Sequence></AbsoluteFill>, { ...base, frame });
test("its ends move off words, its length kept, and the log says so once", () => {
const html = clip();
expect(Number(attr(html, "data-start-from"))).toBeCloseTo((10.5 - 0.3) * 30, 6);
expect(Number(attr(html, "data-end-at"))).toBeCloseTo((10.5 - 0.3) * 30 + 15, 6);
expect(Number(attr(html, "data-source-time"))).toBeCloseTo(10.2, 6);
expect(Number(attr(html, "data-raea-snapped"))).toBeCloseTo(-0.3, 6);
clip({}, 5);
expect(warn).toHaveBeenCalledTimes(1);
expect(String(warn.mock.calls[0][0])).toContain("cut “first”");
expect(String(warn.mock.calls[0][0])).toContain("300 ms earlier");
});
test("snap={false}, a muted clip and a sped one play as given", () => {
for (const p of [{ snap: false }, { muted: true }, { playbackRate: 2 }]) {
expect(Number(attr(clip(p), "data-start-from"))).toBe(10.5 * 30);
}
});
test("a Video inside a component of your own is out of the edit's reach: as given, or moved on its own with snap", () => {
const Mine = (p: object) => <Video src="/media/take01.mp4" startFrom={10.5 * 30} endAt={10.5 * 30 + 15} {...p} />;
const at = (p: object) => Number(attr(renderFrame(<AbsoluteFill><Sequence durationInFrames={15}><Mine {...p} /></Sequence></AbsoluteFill>, base), "data-start-from"));
expect(at({})).toBe(10.5 * 30);
expect(at({ snap: true })).toBeCloseTo((10.5 - 0.3) * 30, 6);
});
test("clips of one take that play on from each other move together, so the take plays on unbroken", () => {
// 10.85-11.45 then 11.45-12.5 of the same take, split only to reframe: the join at 11.45 is inside "have", but it's
// no edit. Alone, each would move to clear it; together, by what clears the stretch's own ends
// (10.85 and 12.517 are in gaps): not at all
const html = renderFrame(
<AbsoluteFill>
<Series>
<Series.Sequence durationInFrames={18}><Video src="/media/take01.mp4" startFrom={10.85 * 30} style={{ objectPosition: "20% 50%" }} /></Series.Sequence>
<Series.Sequence durationInFrames={32}><Video src="/media/take01.mp4" startFrom={11.45 * 30} style={{ objectPosition: "80% 50%" }} /></Series.Sequence>
</Series>
</AbsoluteFill>,
{ ...base, frame: 20 },
);
expect(Number(attr(html, "data-start-from"))).toBeCloseTo(11.45 * 30, 6);
expect(attr(html, "data-raea-snapped")).toBeUndefined();
expect(warn).not.toHaveBeenCalled();
});
test("a stretch whose own ends cut words moves whole: each clip of it by the same amount", () => {
// Sequences placed by \`from\`, mapped from data: 10.5-11.0 then 11.0-11.6 of the take, its in inside "first" and
// its out inside "found"
const clips = [{ at: 0, from: 10.5, to: 11.0 }, { at: 15, from: 11.0, to: 11.6 }];
const tree = (frame: number) => renderFrame(
<AbsoluteFill>
{clips.map((c, i) => (
<Sequence key={i} from={c.at} durationInFrames={Math.round((c.to - c.from) * 30)}>
<Video src="/media/take01.mp4" startFrom={Math.round(c.from * 30)} endAt={Math.round(c.to * 30)} />
</Sequence>
))}
</AbsoluteFill>,
{ ...base, frame },
);
const a = Number(attr(tree(0), "data-raea-snapped"));
const b = Number(attr(tree(20), "data-raea-snapped"));
expect(a).not.toBe(0);
expect(a).toBe(b);
expect(Number(attr(tree(20), "data-start-from"))).toBeCloseTo((11.0 + a) * 30, 6);
});
test("a take with no words beside it plays as given", () => {
const html = renderFrame(<AbsoluteFill><Video src="/media/broll.mp4" startFrom={315} /></AbsoluteFill>, base);
expect(Number(attr(html, "data-start-from"))).toBe(315);
expect(asked).toContain("/media/broll.words.json");
});
test("in a Series, each clip's own Sequence end is its out", () => {
// 10.85 s for 18 frames: out 11.45, inside "have"; moved +80 ms to the boundary with "found"
const html = renderFrame(
<Series><Series.Sequence durationInFrames={18}><Video src="/media/take01.mp4" startFrom={10.85 * 30} /></Series.Sequence></Series>,
base,
);
expect(Number(attr(html, "data-start-from"))).toBeCloseTo((10.85 + 0.08) * 30, 6);
});
});
test("a take's words are looked for beside it, then in footage/", () => {
expect(takeWordsFiles("/media/Take%2001.mp4")).toEqual(["/media/Take 01.words.json", "/media/Take 01.mp4.words.json", "footage/Take 01.words.json"]);
expect(takeWordsFiles("/abs/x/take.mov")).toEqual(["/abs/x/take.words.json", "/abs/x/take.mov.words.json"]);
});
+21 -3
View File
@@ -190,9 +190,13 @@ Feature: raea, the behaviour of its API
Scenario: Placement from perception
Then the Clock takes `perception = {face?: {x, y, w, h}, safe?: {top, bottom}}` for the frame, in composition px
(perception's largest face; the platform's safe area)
And `<Region name = "auto" margin = 0.06>` (names: auto, top, bottom, center, full) is a box positioned
absolutely at the band it names, inset across by m = round(margin * width) on each side. With W and H the
composition's size, top = safe.top or 0.08 H and bottom = safe.bottom or (H > W ? 0.80 : 0.92) H:
And `<Region name = "auto" margin = 0.06 keepOut = true platform?>` (names: auto, top, bottom, center, full) is
a box positioned absolutely at the band it names, inset across by m = round(margin * width) on each side, or
by the app's UI zone at that side where it reaches further in. With W and H the composition's size and Z the
UI zones (`uiZones(W, H, {platform})`, the floor's own numbers: 220, 140, 420 and 60 px from the top, right,
bottom and left of 1080 x 1920, scaled with the width), top = safe.top or Z.top and bottom = safe.bottom or
H - Z.bottom; with keepOut = false (placed in the UI zones on purpose), top = safe.top or 0.08 H, bottom =
safe.bottom or (H > W ? 0.80 : 0.92) H, and the sides are m alone:
| name | band (from y to y) |
| top | top to face.y - m, or top to 0.45 H without a face |
| bottom | face.y + face.h + m to bottom, or 0.55 H to bottom without a face |
@@ -204,6 +208,20 @@ Feature: raea, the behaviour of its API
And the Region sets CSS custom properties on its box for what's inside: --face-top, --face-bottom, --face-left,
--face-right (when there's a face), --region-width and --region-height (px), and data-region, data-band-top,
data-band-bottom for the renderer; `useRegion()` returns {name, x, y, w, h} inside it
Scenario: Safe defaults: text out of the UI zones, a talking clip's ends off words (12-04, round 22)
Then `uiZones(W, H, {platform?, shape?})` is the floor's zones (apps/check/text/src/lib.rs `zones`) and
`<SafeArea platform?>` a layer over the frame inset by them, its zones as --ui-top, --ui-right, --ui-bottom
and --ui-left
And a `<Video>` placed straight in the edit's tree (under an AbsoluteFill or a Series, in its Sequence or
Series.Sequence) on a take with its words beside it (TAKE.words.json, TAKE.mp4.words.json, or for a take in
media/ footage/TAKE.words.json) is moved in its take by the least amount within 0.4 s that leaves neither its
in (startFrom) nor its out (endAt, or its Sequence's end) inside a word (a cut on a boundary where two words run
together is tight, as the sound pack's edit points judge it, not a cut word), in and out together so its place
and length in the edit stay; clips of one take whose spans meet (within a frame) move together, by what clears
the stretch's own ends, so the take plays on unbroken where they join. `data-raea-snapped` says by how much,
and the render's log each move and each end it couldn't clear, once. `snap = false`, muted, looped, sped and
curved clips play as given; `snap = true` moves a Video on its own wherever it is (one inside a component the
tree doesn't reach)
Scenario: The proof
Then `proofBoxes({width, height, face?, parts: [{name, x, y, w, h, band?: [top, bottom]}]})` returns one fault
string per problem, empty when all is well: a part leaving the frame ("<name> runs off the frame"), taller
+2
View File
@@ -76,6 +76,8 @@ export { speedLength, speedPoints, speedSource, type SpeedPoint } from "@raea/vi
export { Transition, type TransitionProps, type TransitionEdge, type TransitionKind } from "@raea/video/transition";
export { Region, useRegion, proofBoxes, regionBand, type RegionName, type RegionBox, type RegionProps, type ProofInput, type ProofPart } from "@raea/video/region";
export { InputRegion } from "@raea/video/input-region";
export { SafeArea, uiZones, useUiZones, type SafeAreaProps, type UiPlatform, type UiShape, type UiZoneOptions, type UiZones } from "@raea/video/zones";
export { snapClip, takeWords, SNAP_NEAR, type Snap, type SnapMove, type TakeWord } from "@raea/video/snap";
export { HugText, hugPath, EmojiText, EMOJI_FONTS, type HugTextProps } from "./hug-text";
export { lyria, sao, fish, isGeneratedAsset, type AssetKind, type GeneratedAsset } from "@raea/asset/assets";
export { useInput, useGameState, useGameEvents, stepAll, keyEdges, type Playtest } from "@raea/app/games";
+2
View File
@@ -12,3 +12,5 @@ export * from "./airgaps";
export * from "./region";
export * from "./overlay";
export * from "./panel";
export * from "./zones";
export * from "./snap";
+55 -2
View File
@@ -6,6 +6,7 @@ import { isGeneratedAsset, type GeneratedAsset } from "@raea/asset/assets";
import { useClockState, useLocalTime } from "@raea/app/clock";
import { jsx } from "react/jsx-runtime";
import { SPEEDS, speedLength, speedPoints, speedSource, type SpeedPoint } from "./speed";
import { snapClip, takeWords, tellSnap, type Snap } from "./snap";
export type VolumeProp = number | ((mediaFrame: number) => number);
@@ -60,6 +61,14 @@ export interface VideoProps extends MediaProps {
/** ours: its cutout (docs/timeline.feature TL7l, CapCut's Auto cutout): the mattes made of its file, which it wears as
* its mask, so what is cut out shows what is under it */
matte?: VideoMatte;
/** ours: whether its ends are moved off words. A Video placed straight in the edit's tree (under an AbsoluteFill or
* a Series, in its Sequence) on a talking take (one with its words beside it, TAKE.words.json) is moved, by default,
* to the nearest place within 0.4 s in the take where neither its in nor its out cuts a word: in and out together, so
* its place and length in the edit stay, and together with the clips of the same take that play on from it, so the
* take still plays on unbroken where they join. The render's log says each move. false plays it from exactly
* startFrom; true moves it on its own wherever it is (a Video inside a component of your own, which the edit's tree
* doesn't reach), not knowing the clips it joins (snap.ts) */
snap?: boolean;
}
/** A clip's mattes: PNGs whose alpha is what is kept, m00001.png on, in one folder of the media folder. */
@@ -245,9 +254,53 @@ function useMediaAttrs(owner: string, props: MediaProps, src = props.src as stri
return attrs;
}
/** A video clip in step with the frame; `data-source-time` is the source time (seconds) to show. */
export function Video(props: VideoProps) {
const NO_SNAP: Snap = { by: 0, moved: [], left: [] };
/** each take's words' snaps, by clip: worked out once, not each frame */
const snaps = new WeakMap<object, Map<string, Snap>>();
const fileName = (src: string) => {
const name = src.split(/[?#]/)[0].split("/").pop() || src;
try {
return decodeURIComponent(name);
} catch {
return name;
}
};
/** The clip as it plays once its ends are moved off words on its own (`snap` true; snap.ts): its props, and how far it
* moved in seconds. A muted, looped, sped or curved clip, or one on a take with no words beside it, is as given. */
function useSnapped(props: VideoProps): { props: VideoProps; by: number } {
const { fps } = useClockState("Video").config;
const { origin } = useLocalTime("Video");
const end = useContext(MediaEndContext);
if (props.snap !== true || props.muted || props.loop || props.speedCurve !== undefined || (props.playbackRate ?? 1) !== 1) return { props, by: 0 };
if (typeof props.src !== "string" || props.src === "") return { props, by: 0 };
const words = takeWords(props.src);
if (!words?.length) return { props, by: 0 };
const startFrom = props.startFrom ?? props.trimBefore ?? 0;
const endAt = props.endAt ?? props.trimAfter;
// what it plays of the take: from startFrom to endAt, or to its Sequence's end, whichever comes first
const out = Math.min(endAt ?? Infinity, end === Infinity ? Infinity : startFrom + (end - origin));
const key = `${startFrom}|${out}|${fps}`;
const mine = snaps.get(words) ?? new Map<string, Snap>();
snaps.set(words, mine);
let s = mine.get(key);
if (!s) {
s = Number.isFinite(startFrom) && startFrom >= 0 ? snapClip(words, startFrom / fps, out / fps) : NO_SNAP;
mine.set(key, s);
if (s.moved.length || s.left.length) tellSnap(props.name ?? fileName(props.src), s);
}
if (!s.by) return { props, by: 0 };
const d = s.by * fps;
return { props: { ...props, startFrom: startFrom + d, endAt: endAt === undefined ? undefined : endAt + d, trimBefore: undefined, trimAfter: undefined }, by: s.by };
}
/** A video clip in step with the frame; `data-source-time` is the source time (seconds) to show. On a talking take its
* ends are moved off words (`snap`). */
export function Video(given: VideoProps) {
const { props, by } = useSnapped(given);
const attrs = useMediaAttrs("Video", props);
// how far it was moved in its take (s), here or by the edit's tree (snapPlaced)
if (by) attrs["data-raea-snapped"] = by;
if (props.punchIn !== undefined && !(props.punchIn > 0)) {
throw new RangeError(`Video ${props.src}: punchIn must be a positive number, got ${props.punchIn}`);
}
+20 -7
View File
@@ -1,6 +1,7 @@
// Placement from perception, and the proof (spec: "Placement from perception", "The proof").
import { createContext, useContext, type CSSProperties, type ReactNode } from "react";
import { useClockState, type Perception, type Rect } from "@raea/app/clock";
import { uiZones, type UiPlatform, type UiZones } from "./zones";
export type RegionName = "auto" | "top" | "bottom" | "center" | "full";
const NAMES: readonly RegionName[] = ["auto", "top", "bottom", "center", "full"];
@@ -28,11 +29,13 @@ interface Band {
bottom: number;
}
/** Works out the vertical band each name stands for, given perception and the composition size. */
export function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin = 0.06): Band {
/** Works out the vertical band each name stands for, given perception and the composition size. Its edges are the
* platform's safe area when perception gives one, else clear of the app's UI zones (`keepOut`: uiZones of the frame);
* with keepOut false, 0.08 H from the top and 0.80 H (0.92 H landscape) down, which reach into them. */
export function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin = 0.06, keepOut: UiZones | false = uiZones(width, height)): Band {
const m = Math.round(margin * width);
const edgeTop = perception.safe?.top ?? MIN_BAND * height;
const edgeBottom = perception.safe?.bottom ?? (height > width ? 0.8 : 0.92) * height;
const edgeTop = perception.safe?.top ?? (keepOut ? keepOut.top : MIN_BAND * height);
const edgeBottom = perception.safe?.bottom ?? (keepOut ? height - keepOut.bottom : (height > width ? 0.8 : 0.92) * height);
const face = perception.face;
const top: Band = { name: "top", top: edgeTop, bottom: face ? face.y - m : 0.45 * height };
const bottom: Band = { name: "bottom", top: face ? face.y + face.h + m : 0.55 * height, bottom: edgeBottom };
@@ -64,6 +67,12 @@ export interface RegionProps {
name?: RegionName;
/** the gap kept from the face and the sides, as a share of the width (0.06) */
margin?: number;
/** keep the band out of the app's UI zones (true): its edges and sides clear the strips a social app draws its
* buttons and captions over (uiZones). false places it there on purpose: the older bands, 0.08 H from the top to
* 0.80 H down, inset by `margin` alone */
keepOut?: boolean;
/** the platform whose UI it keeps out of (tiktok, reels, shorts); none: the strictest, as the floor checks */
platform?: UiPlatform;
/** merged under the box's own placement */
style?: CSSProperties;
/** Tailwind or CSS classes */
@@ -75,7 +84,7 @@ export interface RegionProps {
const px = (n: number) => `${+n.toFixed(3)}px`;
/** A box at the band its name stands for, clear of the face perception found at this frame. */
export function Region({ name = "auto", margin = 0.06, style, className, children }: RegionProps) {
export function Region({ name = "auto", margin = 0.06, keepOut = true, platform, style, className, children }: RegionProps) {
if (!NAMES.includes(name)) throw new RangeError(`Region: name must be one of ${NAMES.join(", ")}, got "${name}"`);
if (typeof margin !== "number" || !(margin >= 0 && margin < 0.5)) {
throw new RangeError(`Region "${name}": margin must be a share of the width in [0, 0.5), got ${margin}`);
@@ -83,9 +92,13 @@ export function Region({ name = "auto", margin = 0.06, style, className, childre
const clock = useClockState("Region");
const { width, height } = clock.config;
const face = clock.perception.face;
const band = regionBand(name, width, height, clock.perception, margin);
const zones = keepOut ? uiZones(width, height, { platform }) : false;
const band = regionBand(name, width, height, clock.perception, margin, zones);
const m = Math.round(margin * width);
const box: RegionBox = { name, x: m, y: band.top, w: width - 2 * m, h: band.bottom - band.top };
// across: the margin, or the app's UI at that side when it reaches further in (its buttons down the right)
const left = zones ? Math.max(m, zones.left) : m;
const right = zones ? Math.max(m, zones.right) : m;
const box: RegionBox = { name, x: left, y: band.top, w: width - left - right, h: band.bottom - band.top };
const attrs = {
className,
+228
View File
@@ -0,0 +1,228 @@
// A talking clip's in and out in the gaps between words (12-04, round 22: 10 to 20 clips a render pass started or
// ended inside a word, and `raea goal check`'s sound pack found each only after the full render; sdk/goal
// packs/sound.ts editPoints). A <Video> on a take that has its words beside it (TAKE.words.json, as `raea words`,
// `raea cut` and the goal check write them) moves its clip to the nearest place where neither end cuts a word.
//
// The clip moves whole: its in and out by the same amount, in the take's own time. Its place in the edit and its length
// are its Sequence's and stay as they are, so nothing after it moves and its picture never freezes; what it plays is
// the take a moment earlier or later. Anything timed by hand to this clip's words moves by that much too.
//
// Clips of one take that play on from each other (one's out is the next one's in: a take split only to reframe it, 65%
// of round 22's ends inside words) are one stretch of sound with no edit in it: they move together, by what clears the
// stretch's own ends (snapChains), so the take still plays on unbroken where they join. That needs every clip of the
// edit at once, so it's done where they are placed (timeline.tsx: AbsoluteFill and Series), not by each Video.
import { hasNative, native } from "@raea/app/native";
/** a word of a take, in seconds */
export type TakeWord = { text: string; start: number; end: number };
/** how far a cut may lie inside a word's edge and not cut it (s): word timings are good to about 30 ms, and the sound
* pack's edit points allow 20 ms (packs/sound.ts) */
const EDGE = 0.02;
/** how far into a gap a cut sits from the word it leaves or meets, when the gap is wide enough (s): airgaps.ts's pad */
const PAD = 0.08;
/** the most a clip is moved to clear its ends (s): the sound pack's NEAR, where it looks for a gap */
export const SNAP_NEAR = 0.4;
/** the word `t` (s) cuts in two: inside it by more than EDGE */
function wordAt(words: readonly TakeWord[], t: number): TakeWord | undefined {
return words.find((w) => w.start + EDGE < t && w.end - EDGE > t);
}
/** where in the gaps either side of the word `t` cuts a cut could go instead: the gap before it and the gap after it,
* each PAD from the word it meets, or its middle when narrower than two PADs. `edge` says which end of a clip it is:
* an in sits near the word it starts on, an out near the word it ends on. */
function gapsAround(words: readonly TakeWord[], w: TakeWord, edge: "in" | "out"): number[] {
const i = words.indexOf(w);
const prev = words[i - 1];
const next = words[i + 1];
const place = (a: number, b: number) => {
// [a, b]: the gap; open at either end before the first word or after the last
if (b - a < 2 * PAD) return (a + b) / 2;
return edge === "in" ? b - PAD : a + PAD;
};
return [place(prev ? prev.end : Math.max(0, w.start - 2 * PAD), w.start), place(w.end, next ? next.start : w.end + 2 * PAD)];
}
/** how close (s) a cut is to a boundary where two words run together to count as on it: the sound pack's SEAM, where
* it calls the cut tight (a warning), not a cut word */
const SEAM = 0.03;
/** boundaries between words with no pause (under 80 ms) between them, or over each other: the sound pack's `seams` */
function seamsOf(words: readonly TakeWord[]): number[] {
const out: number[] = [];
for (let i = 1; i < words.length; i++) {
const a = words[i - 1];
const b = words[i];
if (b.start - a.end < 0.08) out.push(Math.round(((a.end + b.start) / 2) * 1000) / 1000);
}
return out;
}
/** One move of a clip's end: where it was, where it went, and the word it cut. */
export type SnapMove = { edge: "in" | "out"; from: number; to: number; word: string; wordFrom: number; wordTo: number };
/** What snapping a clip did: `by` seconds (0 when it stays), the ends it moved off words, and the ends it couldn't. */
export type Snap = { by: number; moved: SnapMove[]; left: { edge: "in" | "out"; at: number; word: string }[] };
/**
* The clip [tin, tout] of a take (seconds in the take; tout Infinity when it plays to the take's end or its length isn't
* known) moved by the least amount, within SNAP_NEAR, that leaves neither end inside a word, as the sound pack's edit
* points judge it (a cut on a boundary where words run together is tight, not a cut word): in a gap if one is near, else
* on such a boundary. Failing that, the move that leaves the fewest ends inside words. Never moved before the take's
* start.
*/
export function snapClip(words: readonly TakeWord[], tin: number, tout: number): Snap {
const ws = [...words].filter((w) => Number.isFinite(w.start) && Number.isFinite(w.end) && w.end > w.start).sort((a, b) => a.start - b.start);
const seams = seamsOf(ws);
const onSeam = (t: number) => seams.some((x) => Math.abs(x - t) <= SEAM);
const ends: ["in" | "out", number][] = [["in", tin], ...(Number.isFinite(tout) ? [["out", tout] as ["out", number]] : [])];
const cut = (by: number) => ends.filter(([, t]) => !onSeam(t + by) && wordAt(ws, t + by));
if (!cut(0).length) return { by: 0, moved: [], left: [] };
const tries = [0];
const near = (by: number) => {
for (const [edge, t] of cut(by)) {
for (const g of gapsAround(ws, wordAt(ws, t + by)!, edge)) tries.push(g - t);
for (const x of seams) if (Math.abs(x - (t + by)) <= SNAP_NEAR) tries.push(x - t);
}
};
near(0);
// a try made for one end can land the other in a word: the other's places from there are tried too
for (const by of [...tries]) near(by);
// fewest ends in words, then fewest on a boundary between words (a gap is cleaner), then the least move
const score = (by: number): [number, number, number] => [cut(by).length, ends.filter(([, t]) => onSeam(t + by)).length, Math.abs(by)];
let best = 0;
let bs = score(0);
for (const raw of tries) {
const by = Math.round(raw * 1000) / 1000;
if (Math.abs(by) > SNAP_NEAR + 1e-9 || tin + by < 0) continue;
const sc = score(by);
if (sc[0] < bs[0] || (sc[0] === bs[0] && (sc[1] < bs[1] || (sc[1] === bs[1] && sc[2] < bs[2])))) [best, bs] = [by, sc];
}
// a move that clears no end isn't made
const by = bs[0] < cut(0).length ? best : 0;
const moved: SnapMove[] = [];
for (const [edge, t] of cut(0)) {
const w = wordAt(ws, t)!;
if (by !== 0 && !cut(by).some(([e]) => e === edge)) moved.push({ edge, from: t, to: t + by, word: w.text, wordFrom: w.start, wordTo: w.end });
}
const left = cut(by).map(([edge, t]) => ({ edge, at: t + by, word: wordAt(ws, t + by)!.text }));
return { by, moved, left };
}
const stretches = new WeakMap<readonly TakeWord[], Map<string, Snap>>();
/** A clip as the edit places it: its take, and its in and out in the take (s; out Infinity when it plays on to the
* take's end). */
export type ClipSpan = { src: string; in: number; out: number };
/**
* How far (s) to move each clip in its take: clips of one take whose spans meet (one's out within a frame of the next
* one's in, `join` s) are one stretch, moved together by snapClip of the stretch's first in and last out; `told` names
* a clip in the render's log.
*/
export function snapChains(clips: readonly ClipSpan[], join: number, told: (i: number) => string = (i) => clips[i].src): number[] {
const by = clips.map(() => 0);
const order = clips.map((_, i) => i).sort((a, b) => (clips[a].src < clips[b].src ? -1 : clips[a].src > clips[b].src ? 1 : clips[a].in - clips[b].in));
let i = 0;
while (i < order.length) {
const run = [order[i]];
while (i + run.length < order.length) {
const last = clips[run[run.length - 1]];
const next = clips[order[i + run.length]];
if (next.src !== last.src || !(Math.abs(next.in - last.out) <= join)) break;
run.push(order[i + run.length]);
}
i += run.length;
const words = takeWords(clips[run[0]].src);
if (!words?.length) continue;
// worked out once a stretch, not each frame the edit's tree is looked through
const tin = clips[run[0]].in;
const tout = clips[run[run.length - 1]].out;
const mine = stretches.get(words) ?? new Map<string, Snap>();
stretches.set(words, mine);
let s = mine.get(`${tin}|${tout}`);
if (s) {
for (const k of run) by[k] = s.by;
continue;
}
s = snapClip(words, tin, tout);
mine.set(`${tin}|${tout}`, s);
if (s.moved.length || s.left.length) tellSnap(run.length > 1 ? `${told(run[0])} (and ${run.length - 1} more of it, played on from it)` : told(run[0]), s);
for (const k of run) by[k] = s.by;
}
return by;
}
/** a words.json as raea writes it ([{text, start_ms, end_ms}], {words: [...]}, or seconds), as the take's words */
export function parseTakeWords(raw: unknown): TakeWord[] {
const list = (Array.isArray(raw) ? raw : ((raw as { words?: unknown[] } | null)?.words ?? [])) as Record<string, unknown>[];
return list
.map((w) => {
const start = typeof w.start_ms === "number" ? w.start_ms / 1000 : Number(w.start);
const end = typeof w.end_ms === "number" ? w.end_ms / 1000 : Number(w.end ?? start);
return { text: String(w.text ?? w.word ?? ""), start, end };
})
.filter((w) => w.text && Number.isFinite(w.start) && Number.isFinite(w.end));
}
/** where a take's words may be: beside it (TAKE.words.json, or TAKE.mp4.words.json), or, for a take in media/, under
* its name in the project's footage/ folder, where raea cloud's projects keep each take's words */
export function takeWordsFiles(src: string): string[] {
let path = src.split(/[?#]/)[0];
try {
path = decodeURI(path);
} catch {
// a name with a stray %: as it is
}
const stem = path.replace(/\.[^./]+$/, "");
const out = [`${stem}.words.json`, `${path}.words.json`];
const name = stem.split("/").pop();
if (/(^|\/)media\//.test(path) && name) out.push(`footage/${name}.words.json`);
return out;
}
const read = new Map<string, TakeWord[] | null>();
/** The words of the take `src`, read once from the first words file found (takeWordsFiles); null when there is none or
* this isn't the engine (plain bun has no files to read). */
export function takeWords(src: string): TakeWord[] | null {
if (read.has(src)) return read.get(src)!;
let got: TakeWord[] | null = null;
if (hasNative() && !/^[a-z][a-z0-9+.-]*:/i.test(src)) {
for (const file of takeWordsFiles(src)) {
try {
const b64 = native("asset.read", { path: file }).base64;
const bin = atob(b64);
const text = typeof TextDecoder === "function" ? new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0))) : bin;
got = parseTakeWords(JSON.parse(text));
break;
} catch {
// not there, or not words: the next place
}
}
}
read.set(src, got);
return got;
}
/** forget the words read (a test's, or a take transcribed again while a live edit plays) */
export function forgetTakeWords(): void {
read.clear();
}
const told = new Set<string>();
/** Says once, on the render's log, what snapping did to a clip of `name`. */
export function tellSnap(name: string, s: Snap): void {
const t = (x: number) => `${x.toFixed(2)} s`;
const way = `${Math.round(Math.abs(s.by) * 1000)} ms ${s.by < 0 ? "earlier" : "later"}`;
const lines = [
...s.moved.map((m) => `raea: Video ${name}: its ${m.edge} point at ${t(m.from)} cut “${m.word}” (${t(m.wordFrom)}–${t(m.wordTo)}), so the clip plays ${way} in the take: its ${m.edge} is at ${t(m.to)}, in the gap ${m.to <= m.wordFrom ? "before" : "after"} the word (snap={false} keeps it where it was)`),
...s.left.map((l) => `raea: Video ${name}: its ${l.edge} point at ${t(l.at)} still cuts “${l.word}”: no move within ${SNAP_NEAR * 1000} ms clears both ends. Cut it at a pause yourself`),
];
for (const l of lines) {
if (told.has(l)) continue;
told.add(l);
console.warn(l);
}
}
+77 -7
View File
@@ -1,9 +1,10 @@
// AbsoluteFill, Sequence, Series, Loop and Freeze (spec: "Sequence shifts time and limits it").
import { Children, Fragment, isValidElement, useContext, useRef, type CSSProperties, type ReactElement, type ReactNode } from "react";
import { LocalTimeContext, TimeBaseContext, timeBase, useClockState, useLocalTime, type LocalTime, type TimeBase } from "@raea/app/clock";
import { Children, Fragment, cloneElement, isValidElement, useContext, useRef, type CSSProperties, type ReactElement, type ReactNode } from "react";
import { ClockContext, LocalTimeContext, TimeBaseContext, timeBase, useClockState, useLocalTime, type LocalTime, type TimeBase } from "@raea/app/clock";
// assets stays in raea until it moves to @raea/asset (docs/sdk.feature S1d)
import { isGeneratedAsset } from "@raea/asset/assets";
import { Audio, MediaEndContext } from "./media";
import { Audio, MediaEndContext, Video, type VideoProps } from "./media";
import { snapChains, type ClipSpan } from "./snap";
export interface AbsoluteFillProps {
/** merged over the fill's own style (absolute, inset 0, a flex column) */
@@ -25,15 +26,81 @@ const FILL_BASE: CSSProperties = {
flexDirection: "column",
};
/** A box over the whole of its parent, laid out as a flex column; `style` is merged over that. */
/** A box over the whole of its parent, laid out as a flex column; `style` is merged over that. The talking clips placed
* in it are moved off words first (snapPlaced). */
export function AbsoluteFill({ style, children, ...rest }: AbsoluteFillProps) {
const fps = useContext(ClockContext)?.config.fps;
return (
<div {...rest} style={{ ...FILL_BASE, ...style }}>
{children}
{fps ? snapPlaced(children, fps) : children}
</div>
);
}
/** Calls `f` on each <Video> element placed in `node` as an edit places its clips: through arrays, fragments,
* AbsoluteFill and plain elements, and Sequence, Series and Series.Sequence, whose lengths bound it (`len`, frames).
* A Video made inside a component of your own isn't reached: that component hasn't run yet. Answers the node with
* each Video `f` gave back, the same node where nothing changed. */
function placed(node: ReactNode, len: number, f: (el: ReactElement<VideoProps>, len: number) => ReactElement): ReactNode {
if (Array.isArray(node)) {
let changed = false;
const out = node.map((c) => {
const n = placed(c, len, f);
changed ||= n !== c;
return n;
});
return changed ? out : node;
}
if (!isValidElement(node)) return node;
const t = node.type;
const p = node.props as { children?: ReactNode; from?: number; durationInFrames?: number };
if (t === Video) return f(node as ReactElement<VideoProps>, len);
let inner = len;
if (t === Sequence) inner = Math.min(p.durationInFrames ?? Infinity, len - (p.from ?? 0));
else if (t === SeriesSequence) inner = p.durationInFrames ?? Infinity;
else if (!(t === Fragment || t === AbsoluteFill || t === SeriesImpl || typeof t === "string")) return node;
if (p.children === undefined) return node;
const kids = placed(p.children, inner, f);
return kids === p.children ? node : cloneElement(node as ReactElement<{ children?: ReactNode }>, { children: kids });
}
/** `children` with the talking clips placed in them moved off words (snap.ts): each <Video> found as an edit places
* it (`placed`), with sound at its own speed and no `snap` of its own, is moved in its take together with the clips
* of the same take that play on from it, and marked done (snap false), so a fill inside this one leaves it be. */
export function snapPlaced(children: ReactNode, fps: number): ReactNode {
const found: { el: ReactElement<VideoProps>; span: ClipSpan }[] = [];
const snappable = (v: VideoProps) =>
v.snap === undefined && !v.muted && !v.loop && v.speedCurve === undefined && (v.playbackRate ?? 1) === 1 && typeof v.src === "string" && v.src !== "";
placed(children, Infinity, (el, len) => {
const v = el.props;
if (snappable(v)) {
const from = v.startFrom ?? v.trimBefore ?? 0;
const end = v.endAt ?? v.trimAfter;
found.push({ el, span: { src: v.src, in: from / fps, out: Math.min(end ?? Infinity, from + len) / fps } });
}
return el;
});
if (!found.length) return children;
const by = snapChains(found.map((x) => x.span), 1.01 / fps, (i) => found[i].el.props.name ?? found[i].span.src.split("/").pop()!);
const moved = new Map(found.map((x, i) => [x.el, by[i]]));
return placed(children, Infinity, (el) => {
const d = moved.get(el);
if (d === undefined) return el;
if (d === 0) return cloneElement(el, { snap: false });
const v = el.props;
const from = v.startFrom ?? v.trimBefore ?? 0;
const end = v.endAt ?? v.trimAfter;
return cloneElement(el, {
snap: false,
startFrom: from + d * fps,
endAt: end === undefined ? undefined : end + d * fps,
trimBefore: undefined,
trimAfter: undefined,
"data-raea-snapped": d,
} as Partial<VideoProps>);
});
}
export type SequenceLayout = "absolute-fill" | "none";
export interface SequenceProps {
@@ -215,8 +282,11 @@ export interface SeriesProps {
children?: ReactNode;
}
/** Plays its Series.Sequence children back to back, each shifted by its own offset. */
function SeriesImpl({ children }: SeriesProps) {
/** Plays its Series.Sequence children back to back, each shifted by its own offset; the talking clips in them are moved
* off words first (snapPlaced). */
function SeriesImpl({ children: given }: SeriesProps) {
const fps = useContext(ClockContext)?.config.fps;
const children = fps ? snapPlaced(given, fps) : given;
const slots = flatten(children);
let start = 0;
const placed: ReactNode[] = [];
+105
View File
@@ -0,0 +1,105 @@
// The app's UI zones: the strips of a frame a social app draws its own buttons, captions and bars over (12-04, round
// 22: up to 54 texts a render pass landed there, each a floor error found only after minutes of rendering). These are
// the floor's own numbers, apps/check/text/src/lib.rs `zones`, so text kept out of them here passes `raea check` and
// `raea goal check` there; change both together.
//
// uiZones(1080, 1920) { top: 220, right: 140, bottom: 420, left: 60 }: how far in from each edge text keeps
// <SafeArea> a layer inset by them: what is placed inside it is clear of the zones
// <Region> keeps its bands out of them too (region.tsx)
import type { CSSProperties, ReactNode } from "react";
import { useClockState } from "@raea/app/clock";
/** The platform the cut is for: each draws its UI in a different place. None: the strictest of them, which is what the
* floor checks when the brief names no platform. */
export type UiPlatform = "tiktok" | "reels" | "shorts";
/** The frame's shape; by default the nearest to its width over height. */
export type UiShape = "9:16" | "4:5" | "1:1" | "16:9";
/** How far in from each edge of the frame the app's UI reaches, in the composition's px. */
export interface UiZones {
/** the status bar and the app's top tabs */
top: number;
/** the like, comment and share buttons */
right: number;
/** the app's own caption, sound name and bar */
bottom: number;
/** the edge's margin */
left: number;
}
export interface UiZoneOptions {
/** the platform's own zones (tiktok, reels, shorts); none: the strictest */
platform?: UiPlatform;
/** the shape to take the zones of; by default the nearest to width / height */
shape?: UiShape;
}
/** The zones, as [top, right, bottom, left] at 1080 wide (lib.rs's table) */
const TABLE: Record<string, [number, number, number, number]> = {
"9:16 tiktok": [108, 120, 320, 60],
"9:16 reels": [210, 84, 310, 60],
"9:16 shorts": [120, 96, 300, 60],
"9:16": [220, 140, 420, 60],
"4:5": [110, 60, 170, 60],
"1:1": [70, 60, 120, 60],
};
/** The app's UI zones of a `width` x `height` frame: how far in from each edge its text keeps, in px. The floor's
* numbers (apps/check/text/src/lib.rs `zones`), scaled with the width. */
export function uiZones(width: number, height: number, o: UiZoneOptions = {}): UiZones {
if (!(width > 0) || !(height > 0)) throw new RangeError(`uiZones: give the frame's width and height in px, got ${width} x ${height}`);
const r = width / height;
const shape = o.shape ?? (r < 0.7 ? "9:16" : r < 0.9 ? "4:5" : r < 1.2 ? "1:1" : "16:9");
if (shape === "16:9") {
const v = (120 * height) / 1080;
const h = (60 * width) / 1920;
return { top: v, right: h, bottom: v, left: h };
}
const z = (shape === "9:16" && o.platform && TABLE[`9:16 ${o.platform}`]) || TABLE[shape];
if (!z) throw new RangeError(`uiZones: shape must be 9:16, 4:5, 1:1 or 16:9, got "${shape}"`);
const s = width / 1080;
return { top: z[0] * s, right: z[1] * s, bottom: z[2] * s, left: z[3] * s };
}
/** The app's UI zones of the composition being rendered (its width and height). */
export function useUiZones(o: UiZoneOptions = {}): UiZones {
const { width, height } = useClockState("useUiZones").config;
return uiZones(width, height, o);
}
export interface SafeAreaProps extends UiZoneOptions {
/** merged over the layer's own placement */
style?: CSSProperties;
/** Tailwind or CSS classes */
className?: string;
/** what goes inside: placed in the layer, which keeps clear of the app's UI */
children?: ReactNode;
}
/** A layer over the whole frame but the app's UI zones: text and captions placed inside it (absolutely, or in its
* flex column) are clear of them. Its top, right, bottom and left are the zones, as CSS custom properties --ui-top,
* --ui-right, --ui-bottom and --ui-left on it. */
export function SafeArea({ platform, shape, style, className, children }: SafeAreaProps) {
const { width, height } = useClockState("SafeArea").config;
const z = uiZones(width, height, { platform, shape });
const px = (n: number) => `${+n.toFixed(3)}px`;
const box = {
"--ui-top": px(z.top),
"--ui-right": px(z.right),
"--ui-bottom": px(z.bottom),
"--ui-left": px(z.left),
display: "flex",
flexDirection: "column",
...style,
position: "absolute",
left: z.left,
top: z.top,
width: width - z.left - z.right,
height: height - z.top - z.bottom,
} as CSSProperties;
return (
<div data-safe-area={platform ?? "any"} className={className} style={box}>
{children}
</div>
);
}