mirror of
https://github.com/shinyobjectz/raea.git
synced 2026-12-06 08:46:06 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
559b23482f |
No files matched your search
@@ -43,9 +43,7 @@ pub fn rendered(args: &[String]) -> i32 {
|
|||||||
let excused: Vec<Despite> = through.iter().map(|(c, w)| Despite { check: c.clone(), why: w.clone() }).collect();
|
let excused: Vec<Despite> = through.iter().map(|(c, w)| Despite { check: c.clone(), why: w.clone() }).collect();
|
||||||
let out = raea_runtime_bundle::flag(args, "-o").or_else(|| raea_runtime_bundle::flag(args, "--review")).map(PathBuf::from);
|
let out = raea_runtime_bundle::flag(args, "-o").or_else(|| raea_runtime_bundle::flag(args, "--review")).map(PathBuf::from);
|
||||||
// the manifest every render writes beside its output (DR2), or where --manifest put it
|
// the manifest every render writes beside its output (DR2), or where --manifest put it
|
||||||
// a plan's manifest is its -o (render --plan)
|
let manifest = raea_runtime_bundle::flag(args, "--manifest").map(PathBuf::from).or_else(|| Some(raea_runtime_world::manifest_for(out.as_deref()?, std::path::Path::new(args.get(1)?))));
|
||||||
let plan = args.iter().any(|a| a == "--plan");
|
|
||||||
let manifest = if plan { out.clone() } else { raea_runtime_bundle::flag(args, "--manifest").map(PathBuf::from).or_else(|| Some(raea_runtime_world::manifest_for(out.as_deref()?, std::path::Path::new(args.get(1)?)))) };
|
|
||||||
if let Some(m) = manifest {
|
if let Some(m) = manifest {
|
||||||
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {
|
if let Some(mut v) = std::fs::read(&m).ok().and_then(|b| serde_json::from_slice::<Value>(&b).ok()) {
|
||||||
// a video's text, held to the check's text rules as it finishes, a check's round sooner
|
// a video's text, held to the check's text rules as it finishes, a check's round sooner
|
||||||
@@ -64,8 +62,7 @@ pub fn rendered(args: &[String]) -> i32 {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
|
// a render that is part of another (a review's tiles, a quick check's stills) leaves the entry to that one
|
||||||
// and a plan, which drew nothing, isn't a render to keep
|
let file = args.get(1).filter(|a| !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
|
||||||
let file = args.get(1).filter(|a| !plan && !a.starts_with('-') && std::env::var("RAEA_RECORD").as_deref() != Ok("off")).map(PathBuf::from);
|
|
||||||
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
|
if let Some(e) = file.and_then(|f| record::keep("raea render", &f, out.as_deref(), &found, excused, &raea_io_trace::utc(SystemTime::now()).1)) {
|
||||||
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
|
println!("raea render: kept in the project's record as {} (raea findings reads it)", e.id);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,7 +19,6 @@ raea render piece.tsx --quality master -o final.mp4 # constant quality for
|
|||||||
raea render scene.tsx --review review/ # a 3D scene from six fixed cameras, in colour and clay
|
raea render scene.tsx --review review/ # a 3D scene from six fixed cameras, in colour and clay
|
||||||
raea render piece.tsx -o piece.wav # the sound alone, no frames drawn
|
raea render piece.tsx -o piece.wav # the sound alone, no frames drawn
|
||||||
raea render piece.tsx -o piece.mp4 --audio piece.wav # the video, and its sound beside it from the same pass
|
raea render piece.tsx -o piece.mp4 --audio piece.wav # the video, and its sound beside it from the same pass
|
||||||
raea render piece.tsx --plan -o piece.plan.json # what every frame shows and plays, nothing drawn
|
|
||||||
```
|
```
|
||||||
|
|
||||||
What `-o` names decides what you get: a name ending in `.mp4` is a video, `.png` is one frame, `.wav` is the sound
|
What `-o` names decides what you get: a name ending in `.mp4` is a video, `.png` is one frame, `.wav` is the sound
|
||||||
@@ -42,14 +41,6 @@ frames), or where `--manifest` says. It holds what each frame showed as laid out
|
|||||||
size, each video's source and time, each picture's box), the sounds heard and what the render found. `raea check`
|
size, each video's source and time, each picture's box), the sounds heard and what the render found. `raea check`
|
||||||
reads it, and so does [`raea world`](world.md), which measures the output against it when a check asks.
|
reads it, and so does [`raea world`](world.md), which measures the output against it when a check asks.
|
||||||
|
|
||||||
`--plan` writes that manifest without drawing: every frame is stepped through React and laid out, and its sounds are
|
|
||||||
gathered, but no video frame is decoded, nothing is painted and nothing is encoded, so a 30-second cut is planned in
|
|
||||||
seconds where its render takes minutes. `-o` names the JSON file. It has a frame entry for every frame (each video's
|
|
||||||
source, time, box and fit, each text's words, box and size), the sounds heard (each clip's source, in point and
|
|
||||||
frames) and `"plan": true`; what only drawing finds (exposure, 3D clipping, layers) is left out. `raea goal check --at
|
|
||||||
edit --manifest PLAN.json` holds a cut to the rules a plan can answer (text in a UI zone, a cut inside a word, text over
|
|
||||||
a face) before any render.
|
|
||||||
|
|
||||||
A render checks what it draws: 3D parts passing into each other (the clipping check), how its 3D is staged (3D type
|
A render checks what it draws: 3D parts passing into each other (the clipping check), how its 3D is staged (3D type
|
||||||
too small or turned to read, page type over a part, parts that snap, a camera that lurches, frames with almost nothing
|
too small or turned to read, page type over a part, parts that snap, a camera that lurches, frames with almost nothing
|
||||||
on screen; `raea scene stage` runs these without drawing, all but the page's) and its pictures' exposure (clipping to
|
on screen; `raea scene stage` runs these without drawing, all but the page's) and its pictures' exposure (clipping to
|
||||||
@@ -70,7 +61,6 @@ the reason in the manifest. A render of a file in a raea project also keeps its
|
|||||||
|
|
||||||
```sh
|
```sh
|
||||||
raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)
|
raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)
|
||||||
raea render EDIT.tsx --plan -o PLAN.json [--composition ID] [--props JSON|P.json] [--words W.json] [--perception P.json] (every frame through React and layout and its sounds gathered, nothing decoded, drawn or encoded: the render manifest with "plan": true, in seconds, for raea goal check --at edit)
|
|
||||||
raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)
|
raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)
|
||||||
raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)
|
raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)
|
||||||
raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
|
raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
|
||||||
@@ -105,7 +95,6 @@ Headless: it needs nothing running and opens no window. Takes up to 1 argument b
|
|||||||
| `--lite` | – | Draw with raea's live view runtime instead of React, as a live game does. Used by the app when it opens a game. |
|
| `--lite` | – | Draw with raea's live view runtime instead of React, as a live game does. Used by the app when it opens a game. |
|
||||||
| `--manifest` | `render.json` | Write the render's manifest to this file instead of beside the output: the composition's length in frames (`length`, whichever frames were rendered), every frame's element boxes as drawn, what the render found and the sounds heard, which `raea check` and `raea world` read. |
|
| `--manifest` | `render.json` | Write the render's manifest to this file instead of beside the output: the composition's length in frames (`length`, whichever frames were rendered), every frame's element boxes as drawn, what the render found and the sounds heard, which `raea check` and `raea world` read. |
|
||||||
| `--perception` | `P.json` | The perception the composition's Clock reads (faces, boxes, one for every frame or by frame), when it isn't the `perception.json` beside it. |
|
| `--perception` | `P.json` | The perception the composition's Clock reads (faces, boxes, one for every frame or by frame), when it isn't the `perception.json` beside it. |
|
||||||
| `--plan` | – | Write the render manifest of every frame to `-o PLAN.json` without drawing: React and layout run for each frame and its sounds are gathered, but no video is decoded, nothing painted and nothing encoded. The file has `"plan": true`; `raea goal check --at edit --manifest PLAN.json` reads it. |
|
|
||||||
| `--props` | `JSON\|P.json` | Input props, as a JSON object or a file holding one. `getInputProps()` returns them, and they go over the composition's `defaultProps` before `calculateMetadata` runs. |
|
| `--props` | `JSON\|P.json` | Input props, as a JSON object or a file holding one. `getInputProps()` returns them, and they go over the composition's `defaultProps` before `calculateMetadata` runs. |
|
||||||
| `--quality` | `draft\|high\|master\|0..1` | Constant-quality encoding: `draft` for previews, `high` for most deliveries, `master` for type and hard edges, or a number from 0 to 1. On Windows and Linux (OpenH264) it scales the bitrate instead, and once a frame fits at OpenH264's finest quantiser (12), a higher setting writes the same file. |
|
| `--quality` | `draft\|high\|master\|0..1` | Constant-quality encoding: `draft` for previews, `high` for most deliveries, `master` for type and hard edges, or a number from 0 to 1. On Windows and Linux (OpenH264) it scales the bitrate instead, and once a frame fits at OpenH264's finest quantiser (12), a higher setting writes the same file. |
|
||||||
| `--review` | `DIR` | Render a 3D scene from six fixed cameras (hero, front, right, top, iso, low), in colour and in clay, to `DIR/colour.png`, `DIR/clay.png` and `DIR/review.json`. |
|
| `--review` | `DIR` | Render a 3D scene from six fixed cameras (hero, front, right, top, iso, low), in colour and in clay, to `DIR/colour.png`, `DIR/clay.png` and `DIR/review.json`. |
|
||||||
|
|||||||
@@ -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"
|
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
|
## Components
|
||||||
|
|
||||||
### `AbsoluteFill`
|
### `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 |
|
| 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 |
|
| `framing` | `"face"` | ours: frame the take on the largest face |
|
||||||
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
|
| `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 |
|
| `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).
|
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 |
|
| `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) |
|
| `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 |
|
| `style` | `CSSProperties` | merged under the box's own placement |
|
||||||
| `className` | `string` | Tailwind or CSS classes |
|
| `className` | `string` | Tailwind or CSS classes |
|
||||||
| `children` | `ReactNode` | what goes in the band; `useRegion()` reads its box |
|
| `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`
|
### `Sequence`
|
||||||
|
|
||||||
Shifts time by `from` and shows its children only for `durationInFrames` frames.
|
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`
|
### `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 |
|
| 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`
|
### `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 |
|
| Prop | Type | What it does |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `framing` | `"face"` | ours: frame the take on the largest face |
|
| `framing` | `"face"` | ours: frame the take on the largest face |
|
||||||
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
|
| `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 |
|
| `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).
|
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; }
|
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`
|
### `useVideoConfig`
|
||||||
|
|
||||||
The settings of the composition being rendered (inside a Sequence, its width, height and length win).
|
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`
|
### `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
|
```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`
|
### `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
|
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`
|
### `song`
|
||||||
|
|
||||||
A song map bound to a frame rate (and where frame 0 sits in the song): frames from song times, and the reverse.
|
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
|
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`
|
### `tick`
|
||||||
|
|
||||||
a number counting from `from` (0) to `to` over `frames` (24), written as the element's text: `digits` decimals,
|
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
|
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`
|
### `wipe`
|
||||||
|
|
||||||
a reveal wiping across from `from` (left) over `frames` (8), in-out-cubic, by clipping.
|
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.
|
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`
|
### `SPACE_KEY`
|
||||||
|
|
||||||
The prefix of the key the app holds on the stage for each panel that publishes (`data-feed-publish` on an element):
|
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 }
|
type RegisteredControl = Control & { cost: ControlCost }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### `SafeAreaProps`
|
||||||
|
|
||||||
|
The props of [`SafeArea`](#safearea), tabled there.
|
||||||
|
|
||||||
### `SequenceLayout`
|
### `SequenceLayout`
|
||||||
|
|
||||||
```ts
|
```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) |
|
| `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) |
|
| `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`
|
### `Snapshot`
|
||||||
|
|
||||||
The machine's runtime state, kept in the context it drives. `path` is the active states outermost first ([] before
|
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 |
|
| `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 |
|
| `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`
|
### `TextControl`
|
||||||
|
|
||||||
A string: a title, a caption, a name.
|
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>)[]
|
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`
|
### `UseSongOptions`
|
||||||
|
|
||||||
| Field | Type | What it is |
|
| Field | Type | What it is |
|
||||||
|
|||||||
@@ -79,7 +79,8 @@ Shifts time by `from` and shows its children only for `durationInFrames` frames.
|
|||||||
|
|
||||||
### `Series`
|
### `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 |
|
| Prop | Type | What it does |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
@@ -87,13 +88,15 @@ Plays its Series.Sequence children back to back, each shifted by its own offset.
|
|||||||
|
|
||||||
### `Video`
|
### `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 |
|
| Prop | Type | What it does |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `framing` | `"face"` | ours: frame the take on the largest face |
|
| `framing` | `"face"` | ours: frame the take on the largest face |
|
||||||
| `punchIn` | `number` | ours: multiplies the framing's scale (1.15 is the usual) |
|
| `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 |
|
| `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).
|
Also takes the props of [`MediaProps`](#mediaprops).
|
||||||
|
|
||||||
|
|||||||
@@ -384,7 +384,7 @@ pub fn run(args: &[String]) -> R<String> {
|
|||||||
}
|
}
|
||||||
if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
|
if args.first().map(String::as_str) != Some("render") || args.len() < 2 {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--keys keys.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --plan -o PLAN.json [--composition ID] [--props JSON|P.json] [--words W.json] [--perception P.json] (every frame through React and layout and its sounds gathered, nothing decoded, drawn or encoded: the render manifest with \"plan\": true, in seconds, for raea goal check --at edit)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
|
"raea render EDIT.tsx -o OUT.mp4|OUT.png|OUT.wav|DIR [--audio OUT.wav] [--frame N | --at A,B] [--composition ID] [--w W] [--h H] [--fps FPS] [--frames N] [--words W.json] [--perception P.json] [--input I.json|inputs.rrl] [--props JSON|P.json] [--scale S] [--hold FRAME[:FRAMES]] [--manifest render.json] [--keys keys.json] [--layers] [--stage WxH] [--10bit] [--aov] [--alpha [--alpha-codec prores|hevc|rle|png]] [--kbps N | --quality draft|high|master|0..1] [--clay] [--despite CHECK WHY] (also: --lite --comps)\n raea render EDIT.tsx --review DIR [--frame N] (fixed cameras hero, front, right, top, iso, low in colour and clay: DIR/colour.png, clay.png, review.json)\n raea render PAGE.html -o OUT.mp4|OUT.png|DIR [--at A,B] [--alpha] (an HTML composition)\n raea render --bundle NAME.comp.js -o OUT.png|DIR [--dir DIR] [--frame N] (a bundle from raea bundle, as render_bundle draws it)
|
||||||
raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|share|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)
|
raea media probe|still|sheet|audio|loudness|motion|cuts|freezes|proxy|share|lod|trim|concat FILE ... | ffmpeg ARGS | ffprobe ARGS (media work, native: media help)
|
||||||
raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea make sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",
|
raea bundle EDIT.tsx --composition-bundle -o OUT.js [--portable DIR] (a composition for render_bundle, on the Mac or the iPhone)\n raea add PKG[@RANGE]... [--dev] | remove NAME... | install [--offline] [--in DIR] (npm packages for the project: raea.lock, node_modules)\n {} (foley, local)\n {} (an instrument's notes, local)\n raea setup-audio [--check] [sao|tokensynth] (install or check the local audio models)\n {} (the song's energy map: beats, sections, builds, drops, stops, hits, cuts per bar; also: --backend NAME)\n raea make sounds [WORDS] | sounds get PACK/INSTRUMENT [--notes ..|--all] [-o DIR] (open sample libraries for a Sampler)\n {} (the clip's camera solved, for <Matchmove>)",
|
||||||
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
|
tools::sound::SAO_USAGE, tools::sound::TOKENSYNTH_USAGE, tools::song::USAGE, motion::track::USAGE
|
||||||
|
|||||||
@@ -59,7 +59,6 @@ fn a_verb_refuses_what_it_doesnt_take() {
|
|||||||
&["render", "e.tsx", "-o", "o.mp4", "--frame", "20", "--input", "i.json", "--manifest", "m.json", "--stage", "1080x1920", "--words", "w.json"][..],
|
&["render", "e.tsx", "-o", "o.mp4", "--frame", "20", "--input", "i.json", "--manifest", "m.json", "--stage", "1080x1920", "--words", "w.json"][..],
|
||||||
&["render", "e.tsx", "-o", "d", "--at", "0,30", "--composition", "Main", "--w", "1080", "--h", "1920", "--fps", "30", "--frames", "90", "--lite"],
|
&["render", "e.tsx", "-o", "d", "--at", "0,30", "--composition", "Main", "--w", "1080", "--h", "1920", "--fps", "30", "--frames", "90", "--lite"],
|
||||||
&["render", "e.tsx", "-o", "o.mp4", "--kbps", "-6"],
|
&["render", "e.tsx", "-o", "o.mp4", "--kbps", "-6"],
|
||||||
&["render", "edit.tsx", "--composition", "cut-a", "--plan", "-o", "out/cuts/cut-a.plan.json"],
|
|
||||||
&["render", "--bundle", "a.comp.js", "-o", "o.png", "--dir", "d", "--frame", "3"],
|
&["render", "--bundle", "a.comp.js", "-o", "o.png", "--dir", "d", "--frame", "3"],
|
||||||
&["play", "g.tsx", "--input-script", "k.json", "--input-log", "l.json", "--offscreen", "--seconds", "end", "--size", "540x960", "--snapshot", "1.5", "a.png", "--seek", "30", "b.png", "--json", "p.json"],
|
&["play", "g.tsx", "--input-script", "k.json", "--input-log", "l.json", "--offscreen", "--seconds", "end", "--size", "540x960", "--snapshot", "1.5", "a.png", "--seek", "30", "b.png", "--json", "p.json"],
|
||||||
&["play", "g.tsx", "--input", "--baked", "--scrub", "8", "--autoplay", "--no-vsync", "--master", "--3d"],
|
&["play", "g.tsx", "--input", "--baked", "--scrub", "8", "--autoplay", "--no-vsync", "--master", "--3d"],
|
||||||
|
|||||||
@@ -33,8 +33,6 @@ mod bevy_frame;
|
|||||||
use bevy_frame::*;
|
use bevy_frame::*;
|
||||||
mod keys;
|
mod keys;
|
||||||
mod pages;
|
mod pages;
|
||||||
mod plan;
|
|
||||||
pub use plan::plan_refused;
|
|
||||||
use pages::*;
|
use pages::*;
|
||||||
mod program;
|
mod program;
|
||||||
use program::*;
|
use program::*;
|
||||||
@@ -70,30 +68,20 @@ pub(crate) struct Sound {
|
|||||||
/// `render --keys PATH`: each frame's key written there and nothing drawn (keys.rs).
|
/// `render --keys PATH`: each frame's key written there and nothing drawn (keys.rs).
|
||||||
pub(crate) static KEYS: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
|
pub(crate) static KEYS: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
|
||||||
|
|
||||||
/// `render --plan -o PLAN.json`: every frame stepped through React and laid out, its sounds gathered, nothing decoded,
|
|
||||||
/// drawn or encoded; the render manifest written to MANIFEST with "plan": true (plan.rs).
|
|
||||||
pub(crate) static PLAN: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
|
||||||
|
|
||||||
/// `render --manifest PATH` (the CLI's; render_bundle keeps its signature for the iPhone): where render.json goes.
|
/// `render --manifest PATH` (the CLI's; render_bundle keeps its signature for the iPhone): where render.json goes.
|
||||||
static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
|
static MANIFEST: std::sync::Mutex<Option<PathBuf>> = std::sync::Mutex::new(None);
|
||||||
|
|
||||||
/// The manifest, its folder made first (2D stills write it before their frames): the composition's length in frames
|
/// The manifest, its folder made first (2D stills write it before their frames): the composition's length in frames
|
||||||
/// (whatever was rendered of it; raea check --quick samples by it, #86), boxes as drawn, findings, sounds, and whether
|
/// (whatever was rendered of it; raea check --quick samples by it, #86), boxes as drawn, findings, sounds, and whether
|
||||||
/// it drew 3D (an export in layers draws the 3D in the layer under the page, docs/layers.feature LA2a).
|
/// it drew 3D (an export in layers draws the 3D in the layer under the page, docs/layers.feature LA2a).
|
||||||
fn write_manifest(cx: &mut Ctx, size: (u32, u32, f64, i64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {
|
fn write_manifest(cx: &mut Ctx, (w, h, fps, length): (u32, u32, f64, i64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value) -> R<()> {
|
||||||
write_manifest_with(cx, size, found, heard, |_| {})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// write_manifest, with `more` given the document before it's written (a plan's own fields, plan.rs).
|
|
||||||
fn write_manifest_with(cx: &mut Ctx, (w, h, fps, length): (u32, u32, f64, i64), found: Vec<raea_core_facts::Finding>, heard: impl FnOnce(&Ctx) -> Value, more: impl FnOnce(&mut Value)) -> R<()> {
|
|
||||||
let (Some(path), Some(frames)) = (MANIFEST.lock().unwrap().clone(), cx.manifest.take()) else { return Ok(()) };
|
let (Some(path), Some(frames)) = (MANIFEST.lock().unwrap().clone(), cx.manifest.take()) else { return Ok(()) };
|
||||||
path.parent().filter(|d| !d.as_os_str().is_empty()).map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", path.display()))?;
|
path.parent().map_or(Ok(()), std::fs::create_dir_all).map_err(|e| format!("{}: {e}", path.display()))?;
|
||||||
let mut v = json!({"width": w, "height": h, "fps": fps, "length": length, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps), "has3d": cx.scene3d.is_some() || cx.live3d.is_some()});
|
let mut v = json!({"width": w, "height": h, "fps": fps, "length": length, "frames": frames, "findings": raea_core_facts::finding::ranked(found), "sounds": heard(cx), "not_applied": not_applied::seen(), "layers": raea_sys_layers::finish(fps), "has3d": cx.scene3d.is_some() || cx.live3d.is_some()});
|
||||||
// the parts SG9 needs (scene.rs's SEEN: stills' parts on screen, a longer render's remounts), and --props and --scale
|
// the parts SG9 needs (scene.rs's SEEN: stills' parts on screen, a longer render's remounts), and --props and --scale
|
||||||
for given in [scene::SEEN.lock().unwrap().take(), GIVEN.lock().unwrap().clone()] {
|
for more in [scene::SEEN.lock().unwrap().take(), GIVEN.lock().unwrap().clone()] {
|
||||||
v.as_object_mut().into_iter().zip(given.and_then(|m| m.as_object().cloned())).for_each(|(m, given)| m.extend(given));
|
v.as_object_mut().into_iter().zip(more.and_then(|m| m.as_object().cloned())).for_each(|(m, more)| m.extend(more));
|
||||||
}
|
}
|
||||||
more(&mut v);
|
|
||||||
std::fs::write(&path, v.to_string()).map_err(|e| format!("{}: {e}", path.display()))
|
std::fs::write(&path, v.to_string()).map_err(|e| format!("{}: {e}", path.display()))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,119 +0,0 @@
|
|||||||
//! `render --plan -o PLAN.json`: what a render would show and play, frame by frame, with nothing drawn. React is stepped
|
|
||||||
//! through every frame as a render steps it, the page made to match each frame's tree and laid out (styles, fonts,
|
|
||||||
//! layout: Blitz's main world, never its render world), and each frame's sounds gathered as a render gathers them, but
|
|
||||||
//! no video's frame is decoded (the page syncs as `render --keys` does), nothing is painted and nothing is encoded.
|
|
||||||
//!
|
|
||||||
//! PLAN.json is the render manifest (`render --manifest`): width, height, fps, length, a frame entry for every frame of
|
|
||||||
//! the composition (its videos' sources, times and boxes, its text's words, boxes and sizes, its pictures), the sounds
|
|
||||||
//! heard (each clip's source, in point and frames), with "plan": true and whether a frame holds 3D. What a render's
|
|
||||||
//! manifest says that only drawing finds isn't in it: its exposure, its 3D's clipping and its layers (null).
|
|
||||||
//!
|
|
||||||
//! It is the edit moment's input (`raea goal check --at edit --manifest PLAN.json`): a cut's text in a UI zone, a
|
|
||||||
//! clip's in point inside a word, a caption over a face are known from it before any frame is drawn. A 32 s cut (952
|
|
||||||
//! frames at 1080x1920, 5 clips of one interview, a caption a line) is planned in 4 s on a raea cloud box's 8 CPUs (8 s
|
|
||||||
//! with nothing cached), where its render took 130 s on the same box and 152 s on the farm's 32 CPU containers; the
|
|
||||||
//! plan's frames and sounds are the render's own manifest's, box for box (12-04, on three projects' cuts).
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// Why `--plan` can't be taken with the other flags in `args`, or None. A plan is every frame of the composition, has
|
|
||||||
/// no picture, and is written where -o says.
|
|
||||||
pub fn plan_refused(args: &[String]) -> Option<String> {
|
|
||||||
if !args.iter().any(|a| a == "--plan") {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
for f in ["--frame", "--at", "--keys", "--review", "--hold", "--aov", "--alpha", "--layers", "--audio", "--bundle"] {
|
|
||||||
if args.iter().any(|a| a == f) {
|
|
||||||
return Some(format!("--plan lays out every frame of the composition and draws none, so it doesn't take {f}"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let out = flag(args, "-o");
|
|
||||||
if !out.as_deref().is_some_and(|o| o.to_lowercase().ends_with(".json")) {
|
|
||||||
return Some("--plan writes the render manifest of every frame: -o PLAN.json".into());
|
|
||||||
}
|
|
||||||
if flag(args, "--manifest").is_some_and(|m| Some(&m) != out.as_ref()) {
|
|
||||||
return Some("--plan writes its manifest where -o says (PLAN.json): leave --manifest out".into());
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn write(app: &mut App, page: &mut raea_runtime_page::BevyPage, cx: &mut Ctx, (w, h, fps, total): (u32, u32, f64, i64)) -> R<String> {
|
|
||||||
let t0 = std::time::Instant::now();
|
|
||||||
// a keyed sync places no video's frame: nothing decoded (bevy_page.rs)
|
|
||||||
page.keyed = Some(0);
|
|
||||||
let (mut frames, mut tones) = (Vec::with_capacity(total.max(0) as usize), Vec::new());
|
|
||||||
let mut has3d = false;
|
|
||||||
// RAEA_TIMES: where the plan's time goes, totals in ms
|
|
||||||
let times = raea_io_trace::stat("RAEA_TIMES");
|
|
||||||
let (mut t_react, mut t_sync, mut t_lay) = (0f64, 0f64, 0f64);
|
|
||||||
for f in 0..total {
|
|
||||||
let a = std::time::Instant::now();
|
|
||||||
step_react(app, page, cx, (f, fps), true)?;
|
|
||||||
let b = std::time::Instant::now();
|
|
||||||
page.at_frame(f, fps);
|
|
||||||
bevy_page_sync(app.world_mut(), page, cx)?;
|
|
||||||
let c = std::time::Instant::now();
|
|
||||||
page.lay_out();
|
|
||||||
if let Some(m) = cx.manifest.as_mut() {
|
|
||||||
m.push(page.manifest_frame(f));
|
|
||||||
}
|
|
||||||
has3d |= !cx.scene.is_empty();
|
|
||||||
tones.push(raea_runtime_sound::tone_at(app.world_mut(), f, fps, cx.dir, media_path, true));
|
|
||||||
frames.push((f, Frame { mix: cx.mix, page: None, sounds: cx.sounds.clone(), scene: Vec::new(), clear: None, same: false, screens: Vec::new() }));
|
|
||||||
if times {
|
|
||||||
t_react += (b - a).as_secs_f64() * 1e3;
|
|
||||||
t_sync += (c - b).as_secs_f64() * 1e3;
|
|
||||||
t_lay += c.elapsed().as_secs_f64() * 1e3;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if times {
|
|
||||||
eprintln!("raea times: react {t_react:.0} ms, page synced {t_sync:.0} ms, laid out and read {t_lay:.0} ms over {total} frames");
|
|
||||||
}
|
|
||||||
let to = MANIFEST.lock().unwrap().clone().ok_or("--plan: no -o PLAN.json")?;
|
|
||||||
write_manifest_with(cx, (w, h, fps, total), Vec::new(), |cx| heard(&frames, &tones, cx, fps), |v| mark(v, has3d))?;
|
|
||||||
Ok(format!("APPLIED {total} frames planned in {} (laid out with nothing drawn, {:.1} s)", to.display(), t0.elapsed().as_secs_f64()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A manifest made a plan: "plan": true, and whether any frame holds 3D (the plan draws none, so the manifest's own
|
|
||||||
/// "has3d", the drawn 3D's, would say no). Its other keys stay as a render's manifest has them.
|
|
||||||
fn mark(v: &mut Value, has3d: bool) {
|
|
||||||
if let Some(o) = v.as_object_mut() {
|
|
||||||
o.insert("plan".into(), json!(true));
|
|
||||||
o.insert("has3d".into(), json!(has3d));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn a(s: &[&str]) -> Vec<String> {
|
|
||||||
s.iter().map(|a| a.to_string()).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_plan_is_every_frame_written_where_o_says() {
|
|
||||||
assert_eq!(plan_refused(&a(&["render", "e.tsx", "--composition", "c", "--plan", "-o", "out/c.plan.json"])), None);
|
|
||||||
assert_eq!(plan_refused(&a(&["render", "e.tsx", "--plan", "-o", "p.json", "--manifest", "p.json", "--props", "{}"])), None);
|
|
||||||
// not a plan: nothing to refuse
|
|
||||||
assert_eq!(plan_refused(&a(&["render", "e.tsx", "--at", "3", "-o", "d/"])), None);
|
|
||||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan", "-o", "c.mp4"])).unwrap().contains("-o PLAN.json"));
|
|
||||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan"])).unwrap().contains("-o PLAN.json"));
|
|
||||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan", "--at", "0,30", "-o", "p.json"])).unwrap().contains("--at"));
|
|
||||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan", "--keys", "k.json", "-o", "p.json"])).unwrap().contains("--keys"));
|
|
||||||
assert!(plan_refused(&a(&["render", "e.tsx", "--plan", "-o", "p.json", "--manifest", "m.json"])).unwrap().contains("--manifest"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_plan_says_so_in_the_manifests_own_shape() {
|
|
||||||
let mut v = json!({"width": 1080, "height": 1920, "fps": 30.0, "length": 2, "frames": [{"frame": 0}, {"frame": 1}], "has3d": false, "layers": null, "sounds": {"clips": []}});
|
|
||||||
mark(&mut v, true);
|
|
||||||
assert_eq!(v["plan"], true);
|
|
||||||
assert_eq!(v["has3d"], true);
|
|
||||||
// every key a render's manifest has stays, so a reader of one reads the other
|
|
||||||
for k in ["width", "height", "fps", "length", "frames", "layers", "sounds"] {
|
|
||||||
assert!(v.get(k).is_some(), "{k}");
|
|
||||||
}
|
|
||||||
assert_eq!(v["frames"].as_array().unwrap().len(), 2);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -28,9 +28,6 @@ pub fn render(args: &[String]) -> R<String> {
|
|||||||
if args.iter().any(|a| a == "--clay") {
|
if args.iter().any(|a| a == "--clay") {
|
||||||
raea_runtime_scene3d::clay::CLAY.store(true, std::sync::atomic::Ordering::Relaxed);
|
raea_runtime_scene3d::clay::CLAY.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
if let Some(why) = plan_refused(args) {
|
|
||||||
return Err(why);
|
|
||||||
}
|
|
||||||
let tsx = dunce::canonicalize(&PathBuf::from(&args[1])).map_err(|e| format!("{}: {e}", args[1]))?;
|
let tsx = dunce::canonicalize(&PathBuf::from(&args[1])).map_err(|e| format!("{}: {e}", args[1]))?;
|
||||||
let out = PathBuf::from(flag(args, "-o").ok_or("-o OUT.mp4|OUT.png|DIR")?);
|
let out = PathBuf::from(flag(args, "-o").ok_or("-o OUT.mp4|OUT.png|DIR")?);
|
||||||
let dir = tsx.parent().unwrap().to_path_buf();
|
let dir = tsx.parent().unwrap().to_path_buf();
|
||||||
@@ -68,15 +65,6 @@ pub fn render(args: &[String]) -> R<String> {
|
|||||||
(_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?),
|
(_, Some(at)) => Some(at.split(',').map(|f| f.trim().parse::<i64>().map_err(|_| "--at takes frame numbers".to_string())).collect::<R<_>>()?),
|
||||||
_ => None,
|
_ => None,
|
||||||
};
|
};
|
||||||
// --plan: every frame laid out and its sounds gathered, nothing decoded, drawn or encoded; the manifest at -o (plan.rs)
|
|
||||||
if args.iter().any(|a| a == "--plan") {
|
|
||||||
*MANIFEST.lock().unwrap() = Some(out.clone());
|
|
||||||
PLAN.store(true, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
let said = render_bundle_with(&js, &dir, &out, None, false, None, false);
|
|
||||||
PLAN.store(false, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
let _ = std::fs::remove_file(&js);
|
|
||||||
return said;
|
|
||||||
}
|
|
||||||
if let Some(k) = flag(args, "--keys") {
|
if let Some(k) = flag(args, "--keys") {
|
||||||
*KEYS.lock().unwrap() = Some(PathBuf::from(k));
|
*KEYS.lock().unwrap() = Some(PathBuf::from(k));
|
||||||
let said = render_bundle_with(&js, &dir, &out, None, false, None, false);
|
let said = render_bundle_with(&js, &dir, &out, None, false, None, false);
|
||||||
@@ -318,9 +306,6 @@ pub(crate) fn render_bundle_with(js: &Path, dir: &Path, out: &Path, wanted: Opti
|
|||||||
if let Some(to) = KEYS.lock().unwrap().take() {
|
if let Some(to) = KEYS.lock().unwrap().take() {
|
||||||
return crate::keys::write(&to, &mut app, &mut page, &mut cx, (w, h, fps, total));
|
return crate::keys::write(&to, &mut app, &mut page, &mut cx, (w, h, fps, total));
|
||||||
}
|
}
|
||||||
if PLAN.load(std::sync::atomic::Ordering::Relaxed) {
|
|
||||||
return crate::plan::write(&mut app, &mut page, &mut cx, (w, h, fps, total));
|
|
||||||
}
|
|
||||||
if fed {
|
if fed {
|
||||||
if let Some(p) = scene {
|
if let Some(p) = scene {
|
||||||
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
aov_on(raea_render::engine::Engine::open_in(&mut cx.scene3d, &p, dir)?);
|
||||||
|
|||||||
@@ -2,10 +2,6 @@
|
|||||||
# raea in raea cloud's image (docs/cloud.feature CL15): with RAEA_CLOUD_GPU_URL set, `raea render ...` (each command in
|
# raea in raea cloud's image (docs/cloud.feature CL15): with RAEA_CLOUD_GPU_URL set, `raea render ...` (each command in
|
||||||
# RAEA_CLOUD_GPU_COMMANDS) goes to that GPU worker (server/offload.ts); everything else, and everything when it isn't
|
# RAEA_CLOUD_GPU_COMMANDS) goes to that GPU worker (server/offload.ts); everything else, and everything when it isn't
|
||||||
# set, is raea itself. The server, the agents and their shells all reach raea through this one.
|
# set, is raea itself. The server, the agents and their shells all reach raea through this one.
|
||||||
# A render's plan (`raea render EDIT.tsx --plan -o PLAN.json`) draws nothing: it runs here, on the box's CPU, in seconds.
|
|
||||||
for a in "$@"; do
|
|
||||||
[ "$a" = "--plan" ] && exec /opt/raea/bin/raea "$@"
|
|
||||||
done
|
|
||||||
if [ -n "${RAEA_CLOUD_GPU_URL:-}" ] && [ -n "${1:-}" ]; then
|
if [ -n "${RAEA_CLOUD_GPU_URL:-}" ] && [ -n "${1:-}" ]; then
|
||||||
case " ${RAEA_CLOUD_GPU_COMMANDS:-render} " in
|
case " ${RAEA_CLOUD_GPU_COMMANDS:-render} " in
|
||||||
*" $1 "*) exec node /opt/raea-cloud/server/offload.ts "$@" ;;
|
*" $1 "*) exec node /opt/raea-cloud/server/offload.ts "$@" ;;
|
||||||
|
|||||||
@@ -19,20 +19,25 @@ const near = (a: number, b: number) => expect(Math.abs(a - b)).toBeLessThan(1e-6
|
|||||||
describe("Region", () => {
|
describe("Region", () => {
|
||||||
test("auto takes the taller band clear of the face", () => {
|
test("auto takes the taller band clear of the face", () => {
|
||||||
renderFrame(<Region><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { 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.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);
|
expect(got.x).toBe(65); expect(got.w).toBe(950);
|
||||||
near(got.y, 1045); near(got.h, 491);
|
near(got.y, 1045); near(got.h, 491);
|
||||||
});
|
});
|
||||||
test("top and center by name", () => {
|
test("top and center by name", () => {
|
||||||
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { face } });
|
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 } });
|
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);
|
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 });
|
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", () => {
|
test("the safe area moves the edges", () => {
|
||||||
renderFrame(<Region name="top"><Ask f={() => useRegion()} /></Region>, { ...base, frame: 0, perception: { safe: { top: 200, bottom: 1500 } } });
|
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 } });
|
const html = renderFrame(<Region name="bottom" />, { ...base, frame: 0, perception: { face } });
|
||||||
expect(html).toContain('data-region="bottom"');
|
expect(html).toContain('data-region="bottom"');
|
||||||
expect(html).toContain("--face-top:500px");
|
expect(html).toContain("--face-top:500px");
|
||||||
expect(html).toContain("--region-height:491px");
|
expect(html).toContain("--region-height:455px");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -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"]);
|
||||||
|
});
|
||||||
@@ -190,9 +190,13 @@ Feature: raea, the behaviour of its API
|
|||||||
Scenario: Placement from perception
|
Scenario: Placement from perception
|
||||||
Then the Clock takes `perception = {face?: {x, y, w, h}, safe?: {top, bottom}}` for the frame, in composition px
|
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)
|
(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
|
And `<Region name = "auto" margin = 0.06 keepOut = true platform?>` (names: auto, top, bottom, center, full) is
|
||||||
absolutely at the band it names, inset across by m = round(margin * width) on each side. With W and H the
|
a box positioned absolutely at the band it names, inset across by m = round(margin * width) on each side, or
|
||||||
composition's size, top = safe.top or 0.08 H and bottom = safe.bottom or (H > W ? 0.80 : 0.92) H:
|
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) |
|
| name | band (from y to y) |
|
||||||
| top | top to face.y - m, or top to 0.45 H without a face |
|
| 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 |
|
| 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,
|
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,
|
--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
|
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
|
Scenario: The proof
|
||||||
Then `proofBoxes({width, height, face?, parts: [{name, x, y, w, h, band?: [top, bottom]}]})` returns one fault
|
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
|
string per problem, empty when all is well: a part leaving the frame ("<name> runs off the frame"), taller
|
||||||
|
|||||||
@@ -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 { 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 { 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 { 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 { HugText, hugPath, EmojiText, EMOJI_FONTS, type HugTextProps } from "./hug-text";
|
||||||
export { lyria, sao, fish, isGeneratedAsset, type AssetKind, type GeneratedAsset } from "@raea/asset/assets";
|
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";
|
export { useInput, useGameState, useGameEvents, stepAll, keyEdges, type Playtest } from "@raea/app/games";
|
||||||
|
|||||||
@@ -12,3 +12,5 @@ export * from "./airgaps";
|
|||||||
export * from "./region";
|
export * from "./region";
|
||||||
export * from "./overlay";
|
export * from "./overlay";
|
||||||
export * from "./panel";
|
export * from "./panel";
|
||||||
|
export * from "./zones";
|
||||||
|
export * from "./snap";
|
||||||
+55
-2
@@ -6,6 +6,7 @@ import { isGeneratedAsset, type GeneratedAsset } from "@raea/asset/assets";
|
|||||||
import { useClockState, useLocalTime } from "@raea/app/clock";
|
import { useClockState, useLocalTime } from "@raea/app/clock";
|
||||||
import { jsx } from "react/jsx-runtime";
|
import { jsx } from "react/jsx-runtime";
|
||||||
import { SPEEDS, speedLength, speedPoints, speedSource, type SpeedPoint } from "./speed";
|
import { SPEEDS, speedLength, speedPoints, speedSource, type SpeedPoint } from "./speed";
|
||||||
|
import { snapClip, takeWords, tellSnap, type Snap } from "./snap";
|
||||||
|
|
||||||
export type VolumeProp = number | ((mediaFrame: number) => number);
|
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
|
/** 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 */
|
* its mask, so what is cut out shows what is under it */
|
||||||
matte?: VideoMatte;
|
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. */
|
/** 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;
|
return attrs;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** A video clip in step with the frame; `data-source-time` is the source time (seconds) to show. */
|
const NO_SNAP: Snap = { by: 0, moved: [], left: [] };
|
||||||
export function Video(props: VideoProps) {
|
/** 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);
|
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)) {
|
if (props.punchIn !== undefined && !(props.punchIn > 0)) {
|
||||||
throw new RangeError(`Video ${props.src}: punchIn must be a positive number, got ${props.punchIn}`);
|
throw new RangeError(`Video ${props.src}: punchIn must be a positive number, got ${props.punchIn}`);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
// Placement from perception, and the proof (spec: "Placement from perception", "The proof").
|
// Placement from perception, and the proof (spec: "Placement from perception", "The proof").
|
||||||
import { createContext, useContext, type CSSProperties, type ReactNode } from "react";
|
import { createContext, useContext, type CSSProperties, type ReactNode } from "react";
|
||||||
import { useClockState, type Perception, type Rect } from "@raea/app/clock";
|
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";
|
export type RegionName = "auto" | "top" | "bottom" | "center" | "full";
|
||||||
const NAMES: readonly RegionName[] = ["auto", "top", "bottom", "center", "full"];
|
const NAMES: readonly RegionName[] = ["auto", "top", "bottom", "center", "full"];
|
||||||
@@ -28,11 +29,13 @@ interface Band {
|
|||||||
bottom: number;
|
bottom: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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
|
||||||
export function regionBand(name: RegionName, width: number, height: number, perception: Perception, margin = 0.06): Band {
|
* 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 m = Math.round(margin * width);
|
||||||
const edgeTop = perception.safe?.top ?? MIN_BAND * height;
|
const edgeTop = perception.safe?.top ?? (keepOut ? keepOut.top : MIN_BAND * height);
|
||||||
const edgeBottom = perception.safe?.bottom ?? (height > width ? 0.8 : 0.92) * height;
|
const edgeBottom = perception.safe?.bottom ?? (keepOut ? height - keepOut.bottom : (height > width ? 0.8 : 0.92) * height);
|
||||||
const face = perception.face;
|
const face = perception.face;
|
||||||
const top: Band = { name: "top", top: edgeTop, bottom: face ? face.y - m : 0.45 * height };
|
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 };
|
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;
|
name?: RegionName;
|
||||||
/** the gap kept from the face and the sides, as a share of the width (0.06) */
|
/** the gap kept from the face and the sides, as a share of the width (0.06) */
|
||||||
margin?: number;
|
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 */
|
/** merged under the box's own placement */
|
||||||
style?: CSSProperties;
|
style?: CSSProperties;
|
||||||
/** Tailwind or CSS classes */
|
/** Tailwind or CSS classes */
|
||||||
@@ -75,7 +84,7 @@ export interface RegionProps {
|
|||||||
const px = (n: number) => `${+n.toFixed(3)}px`;
|
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. */
|
/** 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 (!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)) {
|
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}`);
|
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 clock = useClockState("Region");
|
||||||
const { width, height } = clock.config;
|
const { width, height } = clock.config;
|
||||||
const face = clock.perception.face;
|
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 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 = {
|
const attrs = {
|
||||||
className,
|
className,
|
||||||
|
|||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
// AbsoluteFill, Sequence, Series, Loop and Freeze (spec: "Sequence shifts time and limits it").
|
// 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 { Children, Fragment, cloneElement, 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 { 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)
|
// assets stays in raea until it moves to @raea/asset (docs/sdk.feature S1d)
|
||||||
import { isGeneratedAsset } from "@raea/asset/assets";
|
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 {
|
export interface AbsoluteFillProps {
|
||||||
/** merged over the fill's own style (absolute, inset 0, a flex column) */
|
/** merged over the fill's own style (absolute, inset 0, a flex column) */
|
||||||
@@ -25,15 +26,81 @@ const FILL_BASE: CSSProperties = {
|
|||||||
flexDirection: "column",
|
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) {
|
export function AbsoluteFill({ style, children, ...rest }: AbsoluteFillProps) {
|
||||||
|
const fps = useContext(ClockContext)?.config.fps;
|
||||||
return (
|
return (
|
||||||
<div {...rest} style={{ ...FILL_BASE, ...style }}>
|
<div {...rest} style={{ ...FILL_BASE, ...style }}>
|
||||||
{children}
|
{fps ? snapPlaced(children, fps) : children}
|
||||||
</div>
|
</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 type SequenceLayout = "absolute-fill" | "none";
|
||||||
|
|
||||||
export interface SequenceProps {
|
export interface SequenceProps {
|
||||||
@@ -215,8 +282,11 @@ export interface SeriesProps {
|
|||||||
children?: ReactNode;
|
children?: ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 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
|
||||||
function SeriesImpl({ children }: SeriesProps) {
|
* 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);
|
const slots = flatten(children);
|
||||||
let start = 0;
|
let start = 0;
|
||||||
const placed: ReactNode[] = [];
|
const placed: ReactNode[] = [];
|
||||||
|
|||||||
@@ -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>
|
||||||
|
);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user