Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

TL6b: a speed curve on a composition's footage: a <Video>'s or an <Audio>'s speedCurve ([place, speed] points over startFrom to endAt, speedLength the frames it takes), its sound carried through the changing rate as one voice (raea-sys-mix Ev::Rate), and the timeline's reader and writer for a sequence's curve

shinyobjectz01076723f484
diff --git a/docs/manual/reference/sdk/index.md b/docs/manual/reference/sdk/index.md
index a5a33bbb..d7fa046e 100644
--- a/docs/manual/reference/sdk/index.md
+++ b/docs/manual/reference/sdk/index.md
@@ -31,7 +31,7 @@ The composition, the app, and the specs and notes an agent writes.
| Import | What it's for | Exports |
| --- | --- | --- |
-| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 19 components, 8 hooks, 55 functions, 9 values, 94 types |
+| [`raea`](raea.md) | The main entry: compositions, sequences, time, interpolation, springs, footage, sound and words. | 19 components, 8 hooks, 58 functions, 9 values, 95 types |
| [`raea/app`](app.md) | The App, its plugins and schedules, and the registry a video's compositions are kept in. | 1 component, 4 functions, 3 classes, 17 values, 8 types |
| [`raea/brief`](brief.md) | The specs an agent writes as data: brief, script, taste, plan and controller, checked against raea's schemas. | 6 functions, 32 types |
| [`raea/note`](note.md) | A person's note as a file in the project: their words kept as written, and the asks the agent restates it as. | 1 function, 4 types |
diff --git a/docs/manual/reference/sdk/raea.md b/docs/manual/reference/sdk/raea.md
index 236677f3..d5c1d3e2 100644
--- a/docs/manual/reference/sdk/raea.md
+++ b/docs/manual/reference/sdk/raea.md
@@ -38,7 +38,7 @@ See [Your first video](../../start/first-video.md) for the whole loop, and
import { AbsoluteFill, ACTION_KEY, actionsIn, Animate } from "raea"
```
-`raea` exports 19 components, 8 hooks, 55 functions, 9 values, 94 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
+`raea` exports 19 components, 8 hooks, 58 functions, 9 values, 95 types. Source: [sdk/raea/src/index.tsx](https://github.com/shinyobjectz/raea/blob/main/sdk/raea/src/index.tsx).
## Components
@@ -698,6 +698,30 @@ Where the song is at `t` seconds: a pure function of the map.
function songAt(map: SongMap, t: number): SongMoment
```
+### `speedLength`
+
+How many frames `span` source frames take under the curve (points from speedPoints).
+
+```ts
+function speedLength(ps: SpeedPoint[], span: number): number
+```
+
+### `speedPoints`
+
+The points checked and in order, one at each end.
+
+```ts
+function speedPoints(owner: string, curve: SpeedPoint[]): SpeedPoint[]
+```
+
+### `speedSource`
+
+The source frame, counted from the curve's start, showing `frame` frames in; `span` once the curve has run out.
+
+```ts
+function speedSource(ps: SpeedPoint[], span: number, frame: number): number
+```
+
### `spring`
A damped spring's value at `frame`: from `from` (0) to `to` (1), started `delay` frames late, by its `config`
@@ -1223,6 +1247,7 @@ The props of [`Loop`](#loop), tabled there.
| `fadeIn` | `number` | ours: seconds to ramp the sound in from silence at its start (applied by the renderer at the audio's rate) |
| `fadeOut` | `number` | ours: seconds to ramp the sound out to silence by its end: the end of its Sequence or Loop pass, or endAt, whichever comes first (one removed some other way fades out after it's gone) |
| `playbackRate` | `number` | how fast it plays (1): 2 is double speed |
+| `speedCurve` | `SpeedPoint[]` | ours: its speed as a curve over its source, [place, speed] points: the place from 0 (startFrom) to 1 (endAt, which it needs), the speed from 0.1 to 10 and changing in a straight line between two points. Wins over playbackRate; its Sequence is as long as the curve takes (`speedLength`) |
| `muted` | `boolean` | play no sound |
| `loop` | `boolean` | start again from `startFrom` when it reaches `endAt` |
| `bus` | `string` | the bus it plays into: a named channel of the edit's Tone graph (music, sfx, voice, ambience, ui), so it takes that bus's volume, effects and ducking (raea/tone `buses`) |
@@ -1580,6 +1605,12 @@ The props of [`SongPlot`](#songplot), tabled there.
| `energy` (required) | `number` | its mean energy, 0..1 |
| `cuts` (required) | `number` | suggested cuts per bar: 0.25, 0.5, 1, 2 or 4 |
+### `SpeedPoint`
+
+```ts
+type SpeedPoint = [place: number, speed: number]
+```
+
### `SpringConfig`
| Field | Type | What it is |
diff --git a/docs/manual/reference/sdk/video.md b/docs/manual/reference/sdk/video.md
index 3c3e6258..d9e3e819 100644
--- a/docs/manual/reference/sdk/video.md
+++ b/docs/manual/reference/sdk/video.md
@@ -120,6 +120,7 @@ The props of [`Loop`](#loop), tabled there.
| `fadeIn` | `number` | ours: seconds to ramp the sound in from silence at its start (applied by the renderer at the audio's rate) |
| `fadeOut` | `number` | ours: seconds to ramp the sound out to silence by its end: the end of its Sequence or Loop pass, or endAt, whichever comes first (one removed some other way fades out after it's gone) |
| `playbackRate` | `number` | how fast it plays (1): 2 is double speed |
+| `speedCurve` | `SpeedPoint[]` | ours: its speed as a curve over its source, [place, speed] points: the place from 0 (startFrom) to 1 (endAt, which it needs), the speed from 0.1 to 10 and changing in a straight line between two points. Wins over playbackRate; its Sequence is as long as the curve takes (`speedLength`) |
| `muted` | `boolean` | play no sound |
| `loop` | `boolean` | start again from `startFrom` when it reaches `endAt` |
| `bus` | `string` | the bus it plays into: a named channel of the edit's Tone graph (music, sfx, voice, ambience, ui), so it takes that bus's volume, effects and ducking (raea/tone `buses`) |
diff --git a/docs/timeline.feature b/docs/timeline.feature
index 9e5f740f..d9a30389 100644
--- a/docs/timeline.feature
+++ b/docs/timeline.feature
@@ -74,14 +74,17 @@ Feature: The timeline SDK (0.1.5): CapCut's timeline, on the composition, in the
Status, 11-13 (the first day). On raea main: sdk/timeline (model, ops with inverses, compound clips, keys and
bezier easing, speed curves, snapping, the frame store's decisions, live playback's mapping, readers for a
composition's sequences and its footage and sound, a film's scenes and a sound's tracks, the palette a plugin adds
- to; 57 tests), and in sdk/video <Nudge keys> and <Transition in out> (fade, slide, wipe, zoom). In raea-feed, draft
- PR #19: the new timeline is the timeline (localStorage raea.timeline-sdk = 0 brings the old strip back); 12 browser
- tests in Chrome, 5 of them also passing in a headless raea window (the rest stop at helpers its runner lacks):
- built TL0a-c, TL1a-c (a plugin's lane as a row under the tracks; collapse and the top edge's resize),
- TL2a-e, TL3a-e, TL3g, TL3i, TL4a-c, TL5a-c, TL6a-b's presets, TL7a, TL8a's waveform and level,
+ to; 63 tests), and in sdk/video <Nudge keys>, <Transition in out> (fade, slide, wipe, zoom) and a <Video>'s or an
+ <Audio>'s speedCurve (the mixer carries its sound through the changing rate as one voice). In raea-feed, draft
+ PR #19: the new timeline is the timeline (localStorage raea.timeline-sdk = 0 brings the old strip back); 15 browser
+ tests in Chrome, 10 of them also passing in a headless raea window (the rest stop at helpers its runner lacks):
+ built TL0a-d, TL1a-c (a plugin's lane as a row under the tracks; collapse and the top edge's resize),
+ TL2a-e, TL3a-e, TL3g, TL3h's freeze and reverse (played live from the film's own frames), TL3i,
+ TL4a-c, TL5a-c, TL6a-b, TL7a, TL8a (waveform, level line, fades),
TL11a for easings, speed curves and transitions as a plugin's data, TL12a-b, TL14a-c
in code a composition's sequences: move, trim, split, delete (E3), keys on x, y, scale, rotate and opacity
- (TL5d), a speed for a sequence that holds footage (TL6a), a transition on a cut (TL7a), a <Video>'s
+ (TL5d), a speed or a speed curve for a sequence that holds footage (TL6a-b), a transition on a cut
+ (TL7a), a <Video>'s
or an <Audio>'s level (TL8a); each written into the working version the moment it is made, its draft
played over the picture (TL9a, TL10d), finished and posted on Send with the agent told (TL9b). A
scene's sequences: move, trim, split, delete written into the scene's own file, which the stage
@@ -90,8 +93,7 @@ Feature: The timeline SDK (0.1.5): CapCut's timeline, on the composition, in the
decided TL10b, c and e in the SDK (which ranges an edit changes, a range's key, what goes first): a store of
drawn frames by range, under a size limit, isn't built; a composition's drafts are kept by their
source (the newest 24), so an undo plays its draft again at once
- not built TL0d (a feed item or a controller declaring a timeline of its own data), TL1d, TL3f, TL3h, a speed
- curve on a sequence, TL7b-c, TL8a's fades and volume line, TL8b-c, TL9d, TL10f for 3D beyond the
+ not built TL1d, TL3f, TL3h's mirror, rotate and crop, TL7b-c, TL8b-c, TL9d, TL10f for 3D beyond the
stage's own play, TL11a's track and clip kinds, tools and snapping targets, TL13's measurements
Background:
diff --git a/sdk/raea/conformance/speed-curve.test.tsx b/sdk/raea/conformance/speed-curve.test.tsx
new file mode 100644
index 00000000..68ac665a
--- /dev/null
+++ b/sdk/raea/conformance/speed-curve.test.tsx
@@ -0,0 +1,58 @@
+// A <Video>'s or an <Audio>'s speed as a curve over its source (docs/timeline.feature TL6b): the source frame each
+// frame shows, the rate its sound plays at, and how long the curve takes.
+import { expect, test } from "bun:test";
+import { Audio, Sequence, speedLength, Video } from "../src";
+import { renderFrame } from "../src/test";
+
+const base = { frame: 0, fps: 30, width: 1080, height: 1920, durationInFrames: 600 };
+const attr = (html: string, name: string) => new RegExp(`${name}="([^"]*)"`).exec(html)?.[1];
+const at = (frame: number, curve: [number, number][], more: object = {}) => {
+ const html = renderFrame(<Video src="media/v.mp4" startFrom={30} endAt={150} speedCurve={curve} {...more} />, { ...base, frame });
+ return { source: Number(attr(html, "data-source-frame")), rate: Number(attr(html, "data-playback-rate")), ended: attr(html, "data-ended") };
+};
+
+test("a flat curve is a playbackRate", () => {
+ expect(at(10, [[0, 2], [1, 2]]).source).toBeCloseTo(50, 6);
+ expect(at(10, [[0, 2], [1, 2]]).rate).toBeCloseTo(2, 6);
+ expect(speedLength([[0, 2], [1, 2]], 120)).toBeCloseTo(60, 6);
+});
+
+test("the source moves faster where the curve is higher, and each frame's rate is the source it passes", () => {
+ const curve: [number, number][] = [[0, 1], [0.5, 4], [1, 1]];
+ const steps = Array.from({ length: 20 }, (_, f) => at(f, curve));
+ for (let f = 0; f + 1 < steps.length; f++) {
+ // the next frame's source is where this frame's rate takes it: the sound stays with the picture
+ expect(steps[f + 1].source - steps[f].source).toBeCloseTo(steps[f].rate, 6);
+ expect(steps[f + 1].rate).toBeGreaterThan(steps[f].rate);
+ }
+ expect(steps[0].source).toBe(30);
+ expect(steps[0].rate).toBeGreaterThan(1);
+});
+
+test("it ends when the curve has played its source, holding the frame before endAt", () => {
+ const curve: [number, number][] = [[0, 1], [1, 3]];
+ const length = speedLength(curve, 120);
+ expect(length).toBeCloseTo((120 * Math.log(3)) / 2, 6);
+ expect(at(Math.floor(length) - 1, curve).ended).toBeUndefined();
+ const after = at(Math.ceil(length), curve);
+ expect(after.ended).toBe("true");
+ expect(after.source).toBe(149);
+});
+
+test("a looped curve starts over", () => {
+ const curve: [number, number][] = [[0, 2], [1, 2]];
+ expect(at(70, curve, { loop: true }).source).toBeCloseTo(30 + 10 * 2, 6);
+});
+
+test("a fadeOut ends where the curve does", () => {
+ const curve: [number, number][] = [[0, 2], [1, 2]];
+ const vol = (frame: number) => Number(attr(renderFrame(<Sequence from={0} durationInFrames={300}><Audio src="media/a.wav" endAt={120} speedCurve={curve} fadeOut={1} /></Sequence>, { ...base, frame }), "data-volume"));
+ expect(vol(20)).toBe(1);
+ expect(vol(45)).toBeCloseTo(0.5, 6);
+});
+
+test("a curve needs endAt, and its points stay in range", () => {
+ expect(() => renderFrame(<Video src="media/v.mp4" speedCurve={[[0, 1]]} />, base)).toThrow(/endAt/);
+ expect(() => renderFrame(<Video src="media/v.mp4" endAt={60} speedCurve={[[0, 20]]} />, base)).toThrow(/speed/);
+ expect(() => renderFrame(<Video src="media/v.mp4" endAt={60} speedCurve={[[2, 1]]} />, base)).toThrow(/place/);
+});
diff --git a/sdk/raea/src/index.tsx b/sdk/raea/src/index.tsx
index cd074f44..94d05bea 100644
--- a/sdk/raea/src/index.tsx
+++ b/sdk/raea/src/index.tsx
@@ -56,6 +56,7 @@ export {
} from "@raea/video/registry";
export { Nudge, type NudgeProps } from "@raea/video/nudge";
+export { speedLength, speedPoints, speedSource, type SpeedPoint } from "@raea/video/speed";
export { Transition, type TransitionProps, type TransitionEdge, type TransitionKind } from "@raea/video/transition";
export { Region, useRegion, proofBoxes, regionBand, type RegionName, type RegionBox, type RegionProps, type ProofInput, type ProofPart } from "@raea/video/region";
export { InputRegion } from "@raea/video/input-region";
diff --git a/sdk/timeline/src/read.ts b/sdk/timeline/src/read.ts
index 8b114a6e..d46284cd 100644
--- a/sdk/timeline/src/read.ts
+++ b/sdk/timeline/src/read.ts
@@ -19,6 +19,9 @@ export interface SeqRow {
keys?: Record<string, [number, number, Ease?][]>
/** how fast the footage it holds plays (its media's playbackRate), when it holds footage at one rate (TL6a) */
speed?: number
+ /** its footage's speed as a curve, each [place 0 to 1, speed] (its media's speedCurve), over `shows` source frames (TL6b) */
+ curve?: [number, number][]
+ shows?: number
/** how it comes in and goes out: its <Transition>'s in and out (TL7a) */
in?: { kind: string; frames: number }
out?: { kind: string; frames: number }
@@ -37,6 +40,9 @@ export type SeqEdit =
| { op: "keys"; i: number; keys: Record<string, [number, number, Ease?][]> }
/** the footage it holds played at `speed`, its length following (TL6a) */
| { op: "speed"; i: number; speed: number }
+ /** the footage it holds played by a speed curve over `source` frames of it, the sequence `frames` long (what the
+ * curve takes); null takes the curve off (TL6b) */
+ | { op: "curve"; i: number; curve: [number, number][] | null; source: number; frames: number }
/** how it comes in ("in") or goes out ("out"): its <Transition>'s edge set, or taken off with 0 frames (TL7a) */
| { op: "edge"; i: number; side: "in" | "out"; kind: string; frames: number }
/** a <Video>'s or an <Audio>'s own level (TL8a) */
@@ -57,7 +63,7 @@ export function fromSequences(rows: SeqRow[], fps: number): Timeline {
const media = rows.filter((r) => r.media)
rows = rows.filter((r) => !r.media)
const lanes = [...new Set(rows.map((r) => r.lane))].sort((a, b) => a - b)
- const clipsOf = (lane: number): Clip[] => rows.filter((r) => r.lane === lane).sort((a, b) => a.from - b.from).map((r) => ({ id: seqId(r.i), kind: "sequence", name: r.label ?? r.name, start: r.from, length: Math.max(1, r.to - r.from), ...(r.locked && { locked: r.locked }), ...(r.speed && r.speed !== 1 && { speed: r.speed }), ...(r.keys && Object.keys(r.keys).length && { keys: Object.fromEntries(Object.entries(r.keys).map(([p, ks]) => [p, ks.map(([at, value, ease]): Key => ({ at, value, ...(ease !== undefined && { ease }) }))])) }) }))
+ const clipsOf = (lane: number): Clip[] => rows.filter((r) => r.lane === lane).sort((a, b) => a.from - b.from).map((r) => ({ id: seqId(r.i), kind: "sequence", name: r.label ?? r.name, start: r.from, length: Math.max(1, r.to - r.from), ...(r.locked && { locked: r.locked }), ...(r.speed && r.speed !== 1 && { speed: r.speed }), ...(r.curve?.length && r.shows && { curve: r.curve.map(([at, speed]) => ({ at, speed })), shows: r.shows }), ...(r.keys && Object.keys(r.keys).length && { keys: Object.fromEntries(Object.entries(r.keys).map(([p, ks]) => [p, ks.map(([at, value, ease]): Key => ({ at, value, ...(ease !== undefined && { ease }) }))])) }) }))
const first = lanes.length ? clipsOf(lanes[0]) : []
const gapless = first.length > 0 && first.every((c, n) => c.start === (n ? end(first[n - 1]) : 0))
const tracks: Track[] = lanes.map((lane, n) => ({ id: n === 0 && gapless ? "main" : `overlay-${lane}`, kind: n === 0 && gapless ? "main" : "overlay", clips: clipsOf(lane) }))
@@ -166,9 +172,18 @@ export function seqEdits(t: Timeline, op: Op): SeqEdit[] | { why: string } {
]
}
case "set": {
- // a speed alone is the footage's rate; anything else a sequence has is its own code's
+ // a speed or a speed curve is the footage's rate; anything else a sequence has is its own code's
const only = Object.keys(op.set).filter((k) => op.set[k as keyof typeof op.set] !== undefined)
- if (only.length !== 1 || only[0] !== "speed" || !(op.set.speed! > 0)) return { why: `the composition's sequences take a speed, not ${only.join(", ") || "that"}, yet` }
+ if (only.length === 1 && only[0] === "curve") {
+ // the clip as the curve leaves it: the source it shows and how long that now takes
+ const after = apply(t, op)
+ if (!after.ok) return { why: after.why }
+ const c = find(after.timeline, op.id)?.clip
+ if (!c) return { why: "that isn't one of the composition's sequences" }
+ const two = (v: number) => Math.round(v * 1000) / 1000
+ return each([op.id], (r) => ({ op: "curve", i: r.i, curve: c.curve ? c.curve.map((p): [number, number] => [two(p.at), two(p.speed)]) : null, source: Math.round(c.shows ?? c.length), frames: c.length }))
+ }
+ if (only.length !== 1 || only[0] !== "speed" || !(op.set.speed! > 0)) return { why: `the composition's sequences take a speed or a speed curve, not ${only.join(", ") || "that"}, yet` }
return each([op.id], (r) => ({ op: "speed", i: r.i, speed: Math.round(op.set.speed! * 1000) / 1000 }))
}
case "key":
diff --git a/sdk/timeline/test/read.test.ts b/sdk/timeline/test/read.test.ts
index e3832102..00803d99 100644
--- a/sdk/timeline/test/read.test.ts
+++ b/sdk/timeline/test/read.test.ts
@@ -38,7 +38,15 @@ describe("TL0c: a timeline is read from a composition", () => {
expect(seqEdits(t, { op: "remove", ids: ["seq-0", "seq-3"] })).toEqual([{ op: "delete", i: 3 }, { op: "delete", i: 0 }])
// a speed is the footage's rate; another field of a clip isn't a sequence's to take
expect(seqEdits(t, { op: "set", id: "seq-0", set: { speed: 2 } })).toEqual([{ op: "speed", i: 0, speed: 2 }])
- expect(seqEdits(t, { op: "set", id: "seq-0", set: { volume: 0.5 } })).toEqual({ why: "the composition's sequences take a speed, not volume, yet" })
+ expect(seqEdits(t, { op: "set", id: "seq-0", set: { volume: 0.5 } })).toEqual({ why: "the composition's sequences take a speed or a speed curve, not volume, yet" })
+ // a speed curve: the points, the source the sequence shows, and how long the curve takes over it
+ const len = t.tracks[0].clips[0].length
+ expect(seqEdits(t, { op: "set", id: "seq-0", set: { curve: [{ at: 0, speed: 2 }, { at: 1, speed: 2 }] } })).toEqual([{ op: "curve", i: 0, curve: [[0, 2], [1, 2]], source: len, frames: Math.round(len / 2) }])
+ const curved = fromSequences([{ ...rows[0], curve: [[0, 1], [1, 3]], shows: 120 }], 30).tracks[0].clips[0]
+ expect([curved.curve, curved.shows]).toEqual([[{ at: 0, speed: 1 }, { at: 1, speed: 3 }], 120])
+ // taken off again: the source it showed at 1x
+ const off = fromSequences([{ ...rows[0], from: 0, to: 60, curve: [[0, 2], [1, 2]], shows: 120 }], 30)
+ expect(seqEdits(off, { op: "set", id: "seq-0", set: { curve: null } })).toEqual([{ op: "curve", i: 0, curve: null, source: 120, frames: 120 }])
expect(seqEdits(t, { op: "duplicate", ids: ["seq-0"] })).toEqual({ why: 'the composition\'s sequences don\'t take "duplicate" yet' })
expect(fromSequences([{ ...rows[0], speed: 2 }], 30).tracks[0].clips[0].speed).toBe(2)
})
diff --git a/sdk/video/package.json b/sdk/video/package.json
index ae43ab46..cc3cc48d 100644
--- a/sdk/video/package.json
+++ b/sdk/video/package.json
@@ -12,6 +12,7 @@
"./timeline": "./src/timeline.tsx",
"./registry": "./src/registry.tsx",
"./nudge": "./src/nudge.tsx",
+ "./speed": "./src/speed.ts",
"./transition": "./src/transition.tsx",
"./words": "./src/words.tsx",
"./region": "./src/region.tsx",
diff --git a/sdk/video/src/index.ts b/sdk/video/src/index.ts
index a158ca6c..5e8f9d69 100644
--- a/sdk/video/src/index.ts
+++ b/sdk/video/src/index.ts
@@ -3,6 +3,7 @@ export * from "./media";
export * from "./timeline";
export * from "./registry";
export * from "./nudge";
+export * from "./speed";
export * from "./transition";
export * from "./words";
export * from "./region";
diff --git a/sdk/video/src/media.tsx b/sdk/video/src/media.tsx
index dc84a5c3..5557949a 100644
--- a/sdk/video/src/media.tsx
+++ b/sdk/video/src/media.tsx
@@ -5,6 +5,7 @@ import { createContext, useContext, type CSSProperties, type ImgHTMLAttributes }
import { isGeneratedAsset, type GeneratedAsset } from "@raea/asset/assets";
import { useClockState, useLocalTime } from "@raea/app/clock";
import { jsx } from "react/jsx-runtime";
+import { SPEEDS, speedLength, speedPoints, speedSource, type SpeedPoint } from "./speed";
export type VolumeProp = number | ((mediaFrame: number) => number);
@@ -32,6 +33,10 @@ export interface MediaProps {
fadeOut?: number;
/** how fast it plays (1): 2 is double speed */
playbackRate?: number;
+ /** ours: its speed as a curve over its source, [place, speed] points: the place from 0 (startFrom) to 1 (endAt, which
+ * it needs), the speed from 0.1 to 10 and changing in a straight line between two points. Wins over playbackRate;
+ * its Sequence is as long as the curve takes (`speedLength`) */
+ speedCurve?: SpeedPoint[];
/** play no sound */
muted?: boolean;
/** start again from `startFrom` when it reaches `endAt` */
@@ -64,6 +69,10 @@ interface MediaTiming {
sourceFrame: number;
ended: boolean;
volume: number;
+ /** how fast the source is passing at this frame: playbackRate, or the curve's speed here */
+ rate: number;
+ /** how many frames it plays from its start to endAt (Infinity with no endAt) */
+ length: number;
}
function pick(owner: string, a: number | undefined, aName: string, b: number | undefined, bName: string) {
@@ -89,7 +98,24 @@ function timing(owner: string, props: MediaProps, frame: number, src: string): M
let sourceFrame = startFrom + Math.max(0, frame) * rate;
let ended = false;
- if (endAt !== undefined && sourceFrame >= endAt) {
+ let now = rate;
+ let length = endAt === undefined ? Infinity : (endAt - startFrom) / rate;
+ if (props.speedCurve !== undefined) {
+ if (endAt === undefined) throw new Error(`${owner} ${src}: speedCurve runs from startFrom to endAt, so it needs endAt`);
+ const ps = speedPoints(`${owner} ${src}`, props.speedCurve);
+ const span = endAt - startFrom;
+ length = speedLength(ps, span);
+ let f = Math.max(0, frame);
+ if (f >= length) {
+ if (props.loop) f %= length;
+ else ended = true;
+ }
+ // endAt is exclusive: hold the last frame before it
+ const at = ended ? Math.max(0, span - 1) : speedSource(ps, span, f);
+ sourceFrame = startFrom + at;
+ // the source this frame passes: what the sound plays at, so the next frame's source is where it has got to
+ now = ended ? rate : Math.max(SPEEDS[0], speedSource(ps, span, f + 1) - at);
+ } else if (endAt !== undefined && sourceFrame >= endAt) {
if (props.loop) {
const span = endAt - startFrom;
sourceFrame = startFrom + ((sourceFrame - startFrom) % span);
@@ -118,9 +144,11 @@ function timing(owner: string, props: MediaProps, frame: number, src: string): M
TIMING.sourceFrame = sourceFrame;
TIMING.ended = ended;
TIMING.volume = volume;
+ TIMING.rate = now;
+ TIMING.length = length;
return TIMING;
}
-const TIMING: MediaTiming = { sourceFrame: 0, ended: false, volume: 1 };
+const TIMING: MediaTiming = { sourceFrame: 0, ended: false, volume: 1, rate: 1, length: Infinity };
/** A fade length in seconds, checked; the renderer applies it at the audio's own rate, so it can be under a frame. */
function fadeSeconds(owner: string, props: MediaProps, name: "fadeIn" | "fadeOut", src: string): number {
@@ -150,9 +178,11 @@ function useMediaAttrs(owner: string, props: MediaProps, src = props.src as stri
const { frame, origin } = useLocalTime(owner);
if (typeof src !== "string" || src === "") throw new Error(`${owner}: src is required`);
const t = timing(owner, props, frame, src);
+ // (read now: `t` is one object every media element shares)
+ const rate = t.rate;
// where it stops: its Sequence's (or Loop pass's) end, or endAt reached (a loop never reaches it)
const endAt = props.loop ? undefined : (props.endAt ?? props.trimAfter);
- const own = endAt === undefined ? Infinity : origin + Math.ceil((endAt - (props.startFrom ?? props.trimBefore ?? 0)) / (props.playbackRate ?? 1));
+ const own = endAt === undefined ? Infinity : origin + Math.ceil(t.length);
const fadeOut = fadeSeconds(owner, props, "fadeOut", src);
const end = Math.min(useContext(MediaEndContext), own);
const volume = fadedOut(t.volume, fadeOut, fps, origin + frame, end);
@@ -164,7 +194,7 @@ function useMediaAttrs(owner: string, props: MediaProps, src = props.src as stri
"data-fade-in": fadeSeconds(owner, props, "fadeIn", src),
// faded here into its end: the stop at the end is the mixer's edge. With no end, the mixer fades it once it's gone
"data-fade-out": end === Infinity ? fadeOut : 0,
- "data-playback-rate": props.playbackRate ?? 1,
+ "data-playback-rate": rate,
"data-start-from": props.startFrom ?? props.trimBefore ?? 0,
"data-end-at": props.endAt ?? props.trimAfter,
"data-loop": props.loop ? "true" : undefined,
diff --git a/sdk/video/src/speed.ts b/sdk/video/src/speed.ts
new file mode 100644
index 00000000..9ec3a159
--- /dev/null
+++ b/sdk/video/src/speed.ts
@@ -0,0 +1,48 @@
+// A clip's speed as a curve over its source (docs/timeline.feature TL6b): [place, speed] points, the place from 0
+// (its startFrom) to 1 (its endAt), the speed changing in a straight line over the source between two of them. So
+// the frames a stretch of source takes, and the source frame at a frame, both have closed forms.
+export type SpeedPoint = [place: number, speed: number];
+
+/** The slowest and fastest a curve's point can be. */
+export const SPEEDS = [0.1, 10] as const;
+
+/** The points checked and in order, one at each end. */
+export function speedPoints(owner: string, curve: SpeedPoint[]): SpeedPoint[] {
+ if (!Array.isArray(curve) || !curve.length) throw new RangeError(`${owner}: speedCurve needs at least one [place, speed] point`);
+ for (const p of curve) {
+ if (!Array.isArray(p) || !(p[0] >= 0 && p[0] <= 1)) throw new RangeError(`${owner}: a speedCurve point's place runs from 0 to 1, got ${p?.[0]}`);
+ if (!(p[1] >= SPEEDS[0] && p[1] <= SPEEDS[1])) throw new RangeError(`${owner}: a speedCurve point's speed runs from ${SPEEDS[0]} to ${SPEEDS[1]}, got ${p[1]}`);
+ }
+ const ps = [...curve].sort((a, b) => a[0] - b[0]);
+ if (ps[0][0] > 0) ps.unshift([0, ps[0][1]]);
+ if (ps[ps.length - 1][0] < 1) ps.push([1, ps[ps.length - 1][1]]);
+ return ps;
+}
+
+// the frames a stretch of `len` source frames takes while the speed goes from `a` to `b` across it
+const stretch = (len: number, a: number, b: number) => (Math.abs(b - a) < 1e-9 ? len / a : (len * Math.log(b / a)) / (b - a));
+
+/** How many frames `span` source frames take under the curve (points from speedPoints). */
+export function speedLength(ps: SpeedPoint[], span: number): number {
+ let n = 0;
+ for (let i = 0; i + 1 < ps.length; i++) n += stretch((ps[i + 1][0] - ps[i][0]) * span, ps[i][1], ps[i + 1][1]);
+ return n;
+}
+
+/** The source frame, counted from the curve's start, showing `frame` frames in; `span` once the curve has run out. */
+export function speedSource(ps: SpeedPoint[], span: number, frame: number): number {
+ let left = Math.max(0, frame);
+ for (let i = 0; i + 1 < ps.length; i++) {
+ const len = (ps[i + 1][0] - ps[i][0]) * span;
+ const a = ps[i][1], b = ps[i + 1][1];
+ const all = stretch(len, a, b);
+ if (left > all) {
+ left -= all;
+ continue;
+ }
+ // the speed over this stretch is a + k s (s source frames into it), so s frames in take ln((a + k s) / a) / k
+ const k = len > 0 ? (b - a) / len : 0;
+ return ps[i][0] * span + Math.min(len, Math.abs(k) < 1e-9 ? left * a : (a * Math.expm1(k * left)) / k);
+ }
+ return span;
+}
diff --git a/systems/mix/src/nodes/mod.rs b/systems/mix/src/nodes/mod.rs
index d287620a..12f9763d 100644
--- a/systems/mix/src/nodes/mod.rs
+++ b/systems/mix/src/nodes/mod.rs
@@ -204,6 +204,11 @@ impl AudioNodeProcessor for VoicesProc {
v.ramp = (ramp, ramp);
}
}
+ Ev::Rate { id, rate } => {
+ if let Some(Src::Pcm { pcm, step, .. }) = self.voices.iter_mut().find(|v| v.id == id && v.env.stopping.is_none()).map(|v| &mut v.src) {
+ *step = pcm.rate / self.rate * rate;
+ }
+ }
Ev::Stop { id, fade } => {
if let Some(v) = self.voices.iter_mut().find(|v| v.id == id && v.env.stopping.is_none()).map(|v| &mut v.env) {
v.stopping = Some((fade.max(1), fade.max(1)));
diff --git a/systems/mix/src/offline.rs b/systems/mix/src/offline.rs
index eaec214e..469f52ff 100644
--- a/systems/mix/src/offline.rs
+++ b/systems/mix/src/offline.rs
@@ -355,6 +355,40 @@ mod tests {
assert_eq!(worst, 0.0, "the Tone play differs from its bounce by up to {worst}");
}
+ /// A sound under a speed curve (sdk/video speedCurve): each frame says where its source is and the rate it passes
+ /// at, the next frame's place being where that rate took it. It plays on as one voice, its pitch rising with the
+ /// rate, with no dip where a frame's rate changes.
+ #[test]
+ fn a_sound_whose_rate_changes_each_frame_plays_on_without_a_break() {
+ let dir = std::env::temp_dir().join(format!("raea-mixer-test-rate-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let a = tone(&dir, "a.wav", 440.0, 8.0);
+ let fps = 30.0;
+ let mut at = 0.0;
+ let fr: Vec<Cue> = (0..90)
+ .map(|f| {
+ // 1x rising to 2x over three seconds
+ let rate = 1.0 + f as f64 / 90.0;
+ let mut c = Cue::default();
+ c.sounds.push(Sound { key: "curve".into(), file: a.as_path().into(), at, volume: 1.0, rate, fade_in: 0.0, fade_out: 0.0, bus: None });
+ at += rate / fps;
+ c
+ })
+ .collect();
+ let out = bounce_raw(&fr, fps).unwrap();
+ let ch = &out.channels[0];
+ let crossings = |from: usize, to: usize| ch[from..to].windows(2).filter(|w| w[0] <= 0.0 && w[1] > 0.0).count() as f64;
+ let half = RATE as usize / 2;
+ // the first half second is about 1.08x of 440 Hz, the last (frames 75 to 90) about 1.92x
+ let (first, last) = (crossings(0, half), crossings(5 * half, 6 * half));
+ assert!((first / 220.0 - 1.083).abs() < 0.03, "first half second: {first} cycles");
+ assert!((last / 220.0 - 1.917).abs() < 0.03, "last half second: {last} cycles");
+ // no dip: every 5 ms of it (after the fade in, before the end) reaches the tone's level
+ let win = RATE as usize / 200;
+ let low = (2..ch.len() / win - 4).map(|k| ch[k * win..(k + 1) * win].iter().fold(0f32, |m, v| m.max(v.abs()))).fold(f32::MAX, f32::min);
+ assert!(low > 0.45, "it dips to {low}");
+ }
+
#[test]
fn a_raw_bounce_mastered_is_the_mastered_bounce() {
let dir = std::env::temp_dir().join(format!("raea-mixer-test-raw-{}", std::process::id()));
diff --git a/systems/mix/src/score.rs b/systems/mix/src/score.rs
index 3b05f5b3..2e2dc944 100644
--- a/systems/mix/src/score.rs
+++ b/systems/mix/src/score.rs
@@ -21,6 +21,8 @@ pub enum Ev {
Start { id: u64, pcm: Arc<Pcm>, at: f64, rate: f64, gain: f32, fade_in: u32, port: usize },
/// its gain ramps linearly to `gain` over `ramp` samples
Gain { id: u64, gain: f32, ramp: u32 },
+ /// it reads on from where it is, `rate` times as fast (a speed curve's next frame: no new voice, no fade)
+ Rate { id: u64, rate: f64 },
/// it fades out over `fade` samples and goes
Stop { id: u64, fade: u32 },
/// a Tone instrument's note on (attack, or attack-release over `dur` samples), out of its port
@@ -120,7 +122,12 @@ impl Score {
let (s, pcm): (&Sound, _) = sound(sp.2);
if let Some(r) = self.runs.get_mut(k) {
let moved = r.at + r.rate * (f - r.f) as f64 / self.fps;
- if f > r.f && (s.at - moved).abs() < 1e-6 && (s.rate - r.rate).abs() < 1e-9 {
+ // where the last frame's rate took it: the same sound going on, at a new rate under a speed curve
+ if f > r.f && (s.at - moved).abs() < 1e-6 {
+ if (s.rate - r.rate).abs() >= 1e-9 {
+ out.push((t, Ev::Rate { id: r.id, rate: s.rate }));
+ r.rate = s.rate;
+ }
if (s.volume - r.volume).abs() > 1e-9 {
out.push((t, Ev::Gain { id: r.id, gain: s.volume, ramp }));
}