Skip to content

Open source CapCut alternative.

TypeScript

feat(site): a clip plays backward [rebuild]

David Lef2887de6f973
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.md
index d7b9380f..a72556be 100644
--- a/docs/guides/cut/README.md
+++ b/docs/guides/cut/README.md
@@ -44,7 +44,7 @@ The client probes the engine's health endpoint (dedicated port first, dev server
**A handover is on the picture or on the sound.** A transition is a blend at the cut rather than an overlap: the clips still abut, the layout never moves, and the incoming clip starts exactly at the cut. Most styles blend the picture across the outgoing clip's last seconds. The cross dissolve hands over on the sound instead — the picture cuts while the two clips ramp past each other, half the handover either side of it. Its bar sits across the cut for that reason, where every other bar ends on the boundary it plays. The two windows sit on separate fields, so everything that draws the picture reads a plain cut and only the mix ramps: the preview, the in-tab export, and the ffmpeg graph the engine and the worker build all follow from that one split. A sound handover needs a second clip's sound to cross into, so a bar of it parked on a clip's open head or tail plays nothing.
-**A clip's rate is a curve over its footage.** A clip plays at one speed, or at a speed that changes through it: nodes pinned to moments in the source, each with a rate, joined by a smooth curve that holds its shape through trims and splits because the nodes belong to the footage. One map sits under it — timeline seconds to source seconds and back — and everything that reads a clip reads that map: the preview's decoder and its pitch-held sound, the in-tab export, the filmstrip on the bar, the beat dots, the assistant's cue arithmetic, and the ffmpeg graph the engine and the cloud worker build. The picture side of that graph is the map itself written as a timestamp expression; the sound side is baked first, since ffmpeg's tempo filter only takes a constant, so all three renderers stretch the sound with the same code. The curve is edited in a strip over the timeline — the footage behind the graph, the beats as ticks a node snaps to, presets for the usual ramps — and the assistant lays one from a description with the same tool.
+**A clip's rate is a curve over its footage.** A clip plays at one speed, or at a speed that changes through it: nodes pinned to moments in the source, each with a rate, joined by a smooth curve that holds its shape through trims and splits because the nodes belong to the footage. One map sits under it — timeline seconds to source seconds and back — and everything that reads a clip reads that map: the preview's decoder and its pitch-held sound, the in-tab export, the filmstrip on the bar, the beat dots, the assistant's cue arithmetic, and the ffmpeg graph the engine and the cloud worker build. The picture side of that graph is the map itself written as a timestamp expression; the sound side is baked first, since ffmpeg's tempo filter only takes a constant, so all three renderers stretch the sound with the same code. The curve is edited in a strip over the timeline — the footage behind the graph, the beats as ticks a node snaps to, presets for the usual ramps — and the assistant lays one from a description with the same tool. A clip can also play backward: the same map read from its far end, so the footprint, the curve and every reader above hold as they are. The preview serves it off the decoder's backward walk, the sound is the span turned before it is stretched, and the engine and the worker bake the span into a turned copy in bounded chunks ahead of the graph and render the clip forward off that.
**A crossing needs handle, and holds its loudness.** Clips never overlap, so for the length of a cross dissolve each one plays into the other's time out of its handle — the media its trim left behind, the outgoing clip past its out point and the incoming clip before its in point. That is what makes both sides really audible over a cut their pictures hard-join, and it is why the ramps are equal-power (sine and cosine) rather than straight lines: two signals meeting at half level sum to the loudness they each had, so the mix never dips through the join. A clip trimmed to the end of its source has no handle to reach into; its side of the crossing stops at the cut, and the handover reads as a dip instead of a crossing. Every renderer works from the same two numbers on a span — how far the crossing runs, and how far each side reaches — so the preview, the browser fold and the ffmpeg graph land on one sound. It opens at 0.3 seconds, shorter than a picture blend's half second: that covers the jump in room tone at a cut while staying under the length where the ear starts hearing two voices, and it asks less of the trim each clip has left. It is picked where the other work on the sound is picked — the Effects tab's Sound family — while the styles that blend the picture are picked from the Transitions tab. A bar can also be hidden, like anything else on the timeline: it grays out and plays nothing while keeping the cut it sits on, so the joint runs hard and the blend is one click away again.
diff --git a/site/packages/effects-kit/src/retime.test.ts b/site/packages/effects-kit/src/retime.test.ts
index b7aaa0d6..5f68da2a 100644
--- a/site/packages/effects-kit/src/retime.test.ts
+++ b/site/packages/effects-kit/src/retime.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import {
flatSpeedCurve,
+ mirrorRetimable,
retimeOf,
speedCurveOf,
speedCurvePreset,
@@ -23,6 +24,59 @@ describe("retimeOf", () => {
]);
});
+ test("a reversed span mirrors the forward map and keeps its footprint", () => {
+ const f = retimeOf({ in: 2, out: 8, speed: 1.5 });
+ const r = retimeOf({ in: 2, out: 8, speed: 1.5, reverse: true });
+ expect(r.reverse).toBe(true);
+ expect(r.len).toBe(f.len);
+ expect(r.rate).toBe(f.rate);
+ expect(r.srcAt(0)).toBe(8);
+ expect(r.srcAt(r.len)).toBe(2);
+ expect(r.srcAt(1)).toBe(6.5);
+ expect(r.tAt(6.5)).toBe(1);
+ expect(r.knots).toEqual([
+ [0, 4],
+ [6, 0],
+ ]);
+ const curve: SpeedNode[] = [
+ [1, 0.25],
+ [3, 8],
+ [5, 1],
+ ];
+ const cf = retimeOf({ in: 1, out: 5, speedCurve: curve });
+ const cr = retimeOf({ in: 1, out: 5, speedCurve: curve, reverse: true });
+ expect(cr.len).toBe(cf.len);
+ for (let t = 0; t <= cf.len; t += cf.len / 53) {
+ expect(cr.srcAt(t)).toBeCloseTo(cf.srcAt(cf.len - t), 9);
+ expect(cr.rateAt(t)).toBeCloseTo(cf.rateAt(cf.len - t), 9);
+ expect(cr.tAt(cr.srcAt(t))).toBeCloseTo(t, 3);
+ }
+ let prev = Infinity;
+ for (const [, t] of cr.knots) {
+ expect(t).toBeLessThanOrEqual(prev);
+ prev = t;
+ }
+ });
+
+ test("a reversed span over turned media is the forward span over the copy", () => {
+ const curve: SpeedNode[] = [
+ [1, 0.25],
+ [3, 8],
+ [5, 1],
+ ];
+ const rev = retimeOf({ in: 1, out: 5, speedCurve: curve, reverse: true });
+ const turned = mirrorRetimable({ in: 1, out: 5, speedCurve: curve, reverse: true }, 6);
+ expect(turned.in).toBe(1);
+ expect(turned.out).toBe(5);
+ expect(turned.reverse).toBeUndefined();
+ const fwd = retimeOf(turned);
+ expect(fwd.reverse).toBe(false);
+ expect(fwd.len).toBeCloseTo(rev.len, 9);
+ for (let t = 0; t <= rev.len; t += rev.len / 41) {
+ expect(6 - fwd.srcAt(t)).toBeCloseTo(rev.srcAt(t), 6);
+ }
+ });
+
test("a flat curve equals the uniform map", () => {
const u = retimeOf({ in: 1, out: 7, speed: 2 });
const c = retimeOf({ in: 1, out: 7, speedCurve: flatSpeedCurve({ in: 1, out: 7, speed: 2 }) });
diff --git a/site/packages/effects-kit/src/retime.ts b/site/packages/effects-kit/src/retime.ts
index 5ff1ff36..0b81bdd2 100644
--- a/site/packages/effects-kit/src/retime.ts
+++ b/site/packages/effects-kit/src/retime.ts
@@ -26,6 +26,10 @@ export interface Retimable {
out: number;
speed?: number;
speedCurve?: SpeedNode[];
+ /** The span plays backward: the head of the clip shows `out`, the tail
+ * shows `in`. The rate (one number or a curve) still describes the footage
+ * in source seconds, so the footprint is the same either way. */
+ reverse?: boolean;
}
export interface Retime {
@@ -37,9 +41,11 @@ export interface Retime {
uniform: boolean;
/** The uniform rate, or the span's average rate under a curve. */
rate: number;
+ /** Source seconds fall as timeline seconds rise. */
+ reverse: boolean;
/** Timeline offset from the span's head → absolute source second. Linear
* past either end at the edge rate, so a handle reaching outside the span
- * maps like the footage beside it. */
+ * maps like the footage beside it. Falls with `tLocal` on a reversed span. */
srcAt(tLocal: number): number;
/** Absolute source second → timeline offset from the span's head. */
tAt(src: number): number;
@@ -48,8 +54,10 @@ export interface Retime {
/** Rate at a source second. */
rateAtSrc(src: number): number;
/** The map as a reduced polyline of `[source seconds past in, timeline
- * seconds past the head]`, first knot `[0, 0]`, last `[out − in, len]`.
- * Renderers that cannot call a function (an ffmpeg expression) read this. */
+ * seconds past the head]`, ascending in source, first knot `[0, 0]`, last
+ * `[out − in, len]`. On a reversed span the timeline column runs the other
+ * way: first `[0, len]`, last `[out − in, 0]`. Renderers that cannot call
+ * a function (an ffmpeg expression) read this. */
knots: [number, number][];
/** Fingerprint of everything the map depends on. */
key: string;
@@ -118,6 +126,7 @@ function uniformRetime(inS: number, outS: number, rate: number, key: string): Re
len,
uniform: true,
rate,
+ reverse: false,
srcAt: (t) => inS + t * rate,
tAt: (s) => (s - inS) / rate,
rateAt: () => rate,
@@ -214,6 +223,7 @@ function curvedRetime(inS: number, outS: number, nodes: SpeedNode[], key: string
len,
uniform: false,
rate: len > 0 ? span / len : rateIn,
+ reverse: false,
srcAt,
tAt,
rateAt: (t) => rate(srcAt(t)),
@@ -223,17 +233,41 @@ function curvedRetime(inS: number, outS: number, nodes: SpeedNode[], key: string
};
}
+/** The forward map turned around: the head of the span plays `out`, the tail
+ * plays `in`, and every timeline offset reads the forward map at `len − t`.
+ * The footprint, the average rate and the rate at each source second are the
+ * forward span's own. */
+function reversedRetime(f: Retime, key: string): Retime {
+ const len = f.len;
+ return {
+ in: f.in,
+ out: f.out,
+ len,
+ uniform: f.uniform,
+ rate: f.rate,
+ reverse: true,
+ srcAt: (t) => f.srcAt(len - t),
+ tAt: (s) => len - f.tAt(s),
+ rateAt: (t) => f.rateAt(len - t),
+ rateAtSrc: f.rateAtSrc,
+ knots: f.knots.map(([x, y]): [number, number] => [x, len - y]),
+ key,
+ };
+}
+
/** The retime of a clip's span, memoized on everything it depends on. */
export function retimeOf(c: Retimable): Retime {
const nodes = speedCurveOf(c);
- const key = nodes
+ const fwdKey = nodes
? `${c.in.toFixed(4)}|${c.out.toFixed(4)}|${nodes.map((nd) => `${nd[0].toFixed(4)}:${nd[1].toFixed(4)}`).join(",")}`
: `${c.in}|${c.out}|u${uniformRate(c)}`;
+ const key = c.reverse ? `${fwdKey}|r` : fwdKey;
const hit = memo.get(key);
if (hit) return hit;
- const built = nodes
- ? curvedRetime(c.in, c.out, nodes, key)
- : uniformRetime(c.in, c.out, uniformRate(c), key);
+ const forward = nodes
+ ? curvedRetime(c.in, c.out, nodes, fwdKey)
+ : uniformRetime(c.in, c.out, uniformRate(c), fwdKey);
+ const built = c.reverse ? reversedRetime(forward, key) : forward;
memo.set(key, built);
// Three Float64 tables per curved entry, plus the knots it kept.
const bytes = nodes ? (built.knots.length + 1) * 16 + sampleCount(c.out - c.in) * 24 : 128;
@@ -252,6 +286,38 @@ export function retimeOf(c: Retimable): Retime {
/** Timeline seconds a clip occupies. */
export const retimeLen = (c: Retimable) => retimeOf(c).len;
+/** The source second at the head of a span: `in`, or `out` when it plays
+ * backward. */
+export const headSrc = (c: Pick<Retimable, "in" | "out" | "reverse">) => (c.reverse ? c.out : c.in);
+/** The source second at the tail of a span: `out`, or `in` when it plays
+ * backward. */
+export const tailSrc = (c: Pick<Retimable, "in" | "out" | "reverse">) => (c.reverse ? c.in : c.out);
+
+/** The source seconds a timeline window `[tFrom, tTo]` of the map reads,
+ * low end first whichever way the map runs. */
+export function srcSpan(rt: Retime, tFrom: number, tTo: number): { lo: number; hi: number } {
+ const a = rt.srcAt(tFrom);
+ const b = rt.srcAt(tTo);
+ return a <= b ? { lo: a, hi: b } : { lo: b, hi: a };
+}
+
+/**
+ * The same span over media that has been turned around: source second `s`
+ * of the original sits at `pivot − s` in the turned copy. A reversed clip
+ * over the original is a forward clip over the copy, with its curve's nodes
+ * carried to the moments they still describe.
+ */
+export function mirrorRetimable<T extends Retimable>(c: T, pivot: number): T {
+ const nodes = speedCurveOf(c);
+ return {
+ ...c,
+ in: pivot - c.out,
+ out: pivot - c.in,
+ speedCurve: nodes ? nodes.map(([at, rate]): SpeedNode => [pivot - at, rate]).reverse() : undefined,
+ reverse: undefined,
+ };
+}
+
/** A flat curve at the clip's current rate, one node on each edge of the
* span — what a clip starts from when it enters curve editing. */
export function flatSpeedCurve(c: Retimable): SpeedNode[] {
diff --git a/site/src/cut/components/Inspector.tools.ts b/site/src/cut/components/Inspector.tools.ts
index 239bec10..332ea835 100644
--- a/site/src/cut/components/Inspector.tools.ts
+++ b/site/src/cut/components/Inspector.tools.ts
@@ -172,7 +172,7 @@ export const INSPECTOR_TOOLS = [
{
name: "update_audio",
description:
- "Update a soundtrack clip: volume (0..3), fadeIn/fadeOut seconds, start position, in/out trim, speed, hidden, or duck. `duck` is voiceover ducking — while this clip plays, ALL other audio (video-clip sound and other music) drops to that gain (0..1); pass 1 to clear ducking. Use it to make a voiceover sit over quieter music.",
+ "Update a soundtrack clip: volume (0..3), fadeIn/fadeOut seconds, start position, in/out trim, speed, reverse, hidden, or duck. `duck` is voiceover ducking — while this clip plays, ALL other audio (video-clip sound and other music) drops to that gain (0..1); pass 1 to clear ducking. Use it to make a voiceover sit over quieter music.",
inputSchema: obj({
id: str("Soundtrack clip id"),
volume: num("0..3 (1 = unchanged, above 1 boosts)"),
@@ -182,6 +182,7 @@ export const INSPECTOR_TOOLS = [
in: num("Source in s"),
out: num("Source out s"),
speed: num("Playback rate (1 = normal, no upper limit)"),
+ reverse: bool("Play the sound backward; false plays it forward again"),
duck: num("Duck other audio to this gain while this clip plays, 0..1 (1 clears ducking)"),
hidden: bool("Silence the clip without removing it (grayed on the timeline)"),
}, ["id"]),
@@ -275,8 +276,8 @@ export const INSPECTOR_TOOLS = [
{
name: "set_speed",
description:
- "Set a video clip's playback speed, one rate across the whole clip. Faster shortens the clip on the timeline; slower stretches it. Later clips, titles, captions, and soundtrack shift to stay in sync. A clip carrying a speed curve loses it: the rate becomes uniform again (set_speed_curve is the tool for a rate that changes through the footage).",
- inputSchema: obj({ clipId: str("Video clip id"), speed: num("Playback rate (1 = normal, no upper limit)") }, ["clipId", "speed"]),
+ "Set a video clip's playback speed, one rate across the whole clip, and/or play it backward. Faster shortens the clip on the timeline; slower stretches it. Later clips, titles, captions, and soundtrack shift to stay in sync. A clip carrying a speed curve loses it when speed is passed: the rate becomes uniform again (set_speed_curve is the tool for a rate that changes through the footage). `reverse: true` plays the clip's trim backward, picture and sound, at its rate — the clip keeps its length and its curve, and its head now shows source `out`; `reverse: false` turns it forward again.",
+ inputSchema: obj({ clipId: str("Video clip id"), speed: num("Playback rate (1 = normal, no upper limit)"), reverse: bool("Play the footage backward (true) or forward (false)") }, ["clipId"]),
},
{
name: "set_speed_curve",
diff --git a/site/src/cut/components/Inspector.tsx b/site/src/cut/components/Inspector.tsx
index f7cf48d4..e600853f 100644
--- a/site/src/cut/components/Inspector.tsx
+++ b/site/src/cut/components/Inspector.tsx
@@ -1147,6 +1147,12 @@ function ClipPanel({ clip }: { clip: VideoClip }) {
</span>
)}
</Row>
+ <Row label="Reverse">
+ <Switch
+ checked={!!clip.reverse}
+ onCheckedChange={(v) => useEditor.getState().setClipReverse(clip.id, v)}
+ />
+ </Row>
{/* Picture */}
<div className="my-1.5 h-px bg-border" />
@@ -1557,6 +1563,12 @@ function AudioPanel({ clip }: { clip: AudioClip }) {
onClick={() => commitAudio({ speed: undefined, speedCurve: undefined })}
/>
</Row>
+ <Row label="Reverse">
+ <Switch
+ checked={!!clip.reverse}
+ onCheckedChange={(v) => commitAudio({ reverse: v || undefined })}
+ />
+ </Row>
<Row label="Volume">
<ValueSlider
label="Volume"
diff --git a/site/src/cut/components/SpeedCurveStrip.tsx b/site/src/cut/components/SpeedCurveStrip.tsx
index 0b3de976..01b81477 100644
--- a/site/src/cut/components/SpeedCurveStrip.tsx
+++ b/site/src/cut/components/SpeedCurveStrip.tsx
@@ -82,7 +82,10 @@ function Strip({ clip }: { clip: VideoClip }) {
() => draft ?? speedCurveOf(clip) ?? flatSpeedCurve(clip),
[draft, clip]
);
- const rt = useMemo(() => retimeOf({ in: clip.in, out: clip.out, speedCurve: nodes }), [clip.in, clip.out, nodes]);
+ const rt = useMemo(
+ () => retimeOf({ in: clip.in, out: clip.out, speedCurve: nodes, reverse: clip.reverse }),
+ [clip.in, clip.out, nodes, clip.reverse]
+ );
const boxRef = useRef<HTMLDivElement | null>(null);
const [width, setWidth] = useState(0);
@@ -165,7 +168,7 @@ function Strip({ clip }: { clip: VideoClip }) {
useEditor.getState().setClipSpeedCurve(clip.id, next);
};
const seekToSrc = (src: number, list: SpeedNode[]) => {
- const map = retimeOf({ in: clip.in, out: clip.out, speedCurve: list });
+ const map = retimeOf({ in: clip.in, out: clip.out, speedCurve: list, reverse: clip.reverse });
useEditor.getState().seek(clip.start + map.tAt(src));
};
diff --git a/site/src/cut/components/TemplateCard.tsx b/site/src/cut/components/TemplateCard.tsx
index da0cb82a..83ec42fe 100644
--- a/site/src/cut/components/TemplateCard.tsx
+++ b/site/src/cut/components/TemplateCard.tsx
@@ -105,7 +105,7 @@ export function TemplateCard({
// The contents, one row per item, in save order: clips and stills, sounds,
// titles, then a caption count.
- const speedLen = (x: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[] }) =>
+ const speedLen = (x: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean }) =>
retimeOf(x).len;
const parts: {
icon: typeof Film;
diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsx
index 38351486..7818d77a 100644
--- a/site/src/cut/components/Timeline.tsx
+++ b/site/src/cut/components/Timeline.tsx
@@ -58,7 +58,7 @@ import { useBrushUi } from "@/cut/lib/removal/brushUi";
import { useMatteBakes } from "@/cut/lib/removal/bakeJobs";
import { laneHidden, subtitleLaneCount } from "@/cut/lib/subtitles";
import { formatTime, formatTimecode } from "@/cut/lib/time";
-import { EFFECT_LABELS, hasSpeedCurve, retimeOf, SPEED_CURVE_MAX, SPEED_CURVE_MIN, type EffectId, type Retime, type SpeedNode } from "@donkeycut/effects-kit";
+import { EFFECT_LABELS, hasSpeedCurve, headSrc, retimeOf, SPEED_CURVE_MAX, SPEED_CURVE_MIN, tailSrc, type EffectId, type Retime, type SpeedNode } from "@donkeycut/effects-kit";
import { assetIsSilent, emptySubtitles, IMAGE_CLIP_SECONDS, isAudioTransition, SHAPE_LABELS, TRANSITION_MAX, TRANSITION_STYLE_LABELS, transitionBarStart, transitionDefaultSeconds, type ShapeKind } from "@/cut/lib/types";
import type { AudioClip, ClipSpan, ColorGrade, MediaAsset, Overlay, Selection, StickerOverlay, SubtitleCue, TimelineTransition, TransitionBoundaryKind, TransitionStyle, VideoClip } from "@/cut/lib/types";
import { isLottieAsset } from "@/cut/lib/lottieAssets";
@@ -3807,8 +3807,9 @@ function ClipView({
// The box is drawn a gutter narrower than the footprint, so everything laid
// out inside it — the strip, the dots — measures against this, not `w`.
const barW = Math.max(10, w - CLIP_GAP);
- const filmIn = clip.in;
- const filmOut = clip.out;
+ // The source seconds at the box's edges: a reversed clip opens on `out`.
+ const filmIn = headSrc(clip);
+ const filmOut = tailSrc(clip);
const startFrame = useEdgeFrame(asset, filmIn, `${clip.id}:in`);
const endFrame = useEdgeFrame(asset, filmOut, `${clip.id}:out`);
@@ -3922,7 +3923,7 @@ function ClipView({
)}
style={{ height: WAVE_H }}
>
- <WaveformCanvas asset={asset} from={filmIn} to={filmOut} w={barW} h={WAVE_H - 4} map={rt.uniform ? undefined : (px) => rt.srcAt(px / pps)} className="inset-x-0 inset-y-0.5" />
+ <WaveformCanvas asset={asset} from={clip.in} to={clip.out} w={barW} h={WAVE_H - 4} map={rt.uniform && !rt.reverse ? undefined : (px) => rt.srcAt(px / pps)} className="inset-x-0 inset-y-0.5" />
</div>
)}
{selected && (
@@ -4014,7 +4015,7 @@ function ClipView({
{/* Drawn wherever the source has a grid: on the band when there is one,
along the bar's bottom edge when the clip plays silent. Every edge
snaps to them either way. */}
- <BeatDots asset={asset} from={filmIn} to={filmOut} retime={rt} pps={pps} w={barW} />
+ <BeatDots asset={asset} lo={clip.in} hi={clip.out} retime={rt} pps={pps} w={barW} />
<span
className={cn(trimFor(barW), "tl-trim-l left-0")}
onPointerDown={(e) => startLaneTrim(e, lane, clip.id, "l", ui)}
@@ -5085,7 +5086,7 @@ function writeBeats(assetId: string, edit: (beats: number[]) => number[]) {
function addBeatAt(
e: React.PointerEvent<HTMLElement>,
asset: MediaAsset,
- clip: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[] },
+ clip: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean },
pps: number
) {
e.preventDefault();
@@ -5166,15 +5167,18 @@ function BeatDot({
* source window `from..to`. */
function BeatDots({
asset,
- from,
- to,
+ lo,
+ hi,
retime,
pps,
w,
}: {
asset: MediaAsset;
- from: number;
- to: number;
+ /** The stretch of source the clip holds, low second first. A clip that
+ * plays backward holds the same stretch and shows it in the other order,
+ * so the window it is picked out of reads the same way either way. */
+ lo: number;
+ hi: number;
retime: Retime;
pps: number;
w: number;
@@ -5184,7 +5188,7 @@ function BeatDots({
return (
<>
{beats
- .filter((b) => b >= from && b <= to)
+ .filter((b) => b >= lo && b <= hi)
.map((b) => (
<BeatDot
key={b}
@@ -5293,9 +5297,9 @@ function AudioView({
className="pointer-events-none absolute inset-0"
style={{ clipPath: fadeClipPath(fadeInPx, fadeOutPx, barW) }}
>
- <WaveformCanvas asset={asset} from={clip.in} to={clip.out} w={barW} h={AUDIO_H - 8} map={rt.uniform ? undefined : (px) => rt.srcAt(px / pps)} className="inset-x-0 inset-y-1" />
+ <WaveformCanvas asset={asset} from={clip.in} to={clip.out} w={barW} h={AUDIO_H - 8} map={rt.uniform && !rt.reverse ? undefined : (px) => rt.srcAt(px / pps)} className="inset-x-0 inset-y-1" />
</div>
- <BeatDots asset={asset} from={clip.in} to={clip.out} retime={rt} pps={pps} w={barW} />
+ <BeatDots asset={asset} lo={clip.in} hi={clip.out} retime={rt} pps={pps} w={barW} />
<FadeEnvelope inPx={fadeInPx} outPx={fadeOutPx} barW={barW} />
<FadeGrip clip={clip} side="in" pps={pps} barW={barW} fade={fadeIn} live={liveFade?.side === "in"} onLive={setLiveFade} />
<FadeGrip clip={clip} side="out" pps={pps} barW={barW} fade={fadeOut} live={liveFade?.side === "out"} onLive={setLiveFade} />
diff --git a/site/src/cut/hooks/usePlayback.ts b/site/src/cut/hooks/usePlayback.ts
index cbbacbc0..37d7df5b 100644
--- a/site/src/cut/hooks/usePlayback.ts
+++ b/site/src/cut/hooks/usePlayback.ts
@@ -8,7 +8,7 @@ import {
projectDuration,
useEditor,
} from "@/cut/lib/store";
-import { matteLumaToAlpha, retimeOf } from "@donkeycut/effects-kit";
+import { headSrc, matteLumaToAlpha, retimeOf, srcSpan } from "@donkeycut/effects-kit";
import { playheadAt, previewAt, setPlayhead, subscribePlayhead } from "@/cut/lib/playhead";
import { assetIsSilent, clipCovers, projectFadeSeconds, rectOf } from "@/cut/lib/types";
import type { ClipSpan, MediaAsset, VideoClip } from "@/cut/lib/types";
@@ -110,7 +110,15 @@ const PLAY_SETTLE_MS = 6_000;
/** The decode identity of a clip — see `mappingKey`. */
const keyOf = (clip: VideoClip, asset: MediaAsset) =>
- mappingKey(asset.id, retimeOf(clip), clip.in, clip.start);
+ mappingKey(asset.id, retimeOf(clip), clip.start);
+
+/**
+ * Which way a clip's source is read at this moment: playing, a reversed clip
+ * reads down its source; paused, the reader's own direction along the
+ * timeline turns around on a reversed clip.
+ */
+const readsDown = (clip: VideoClip, playing: boolean, backward: boolean) =>
+ playing ? !!clip.reverse : backward !== !!clip.reverse;
let engineSerial = 0;
@@ -139,14 +147,19 @@ const voiceSpan = (sp: ClipSpan) => {
// beside them, so the voice's span widens through the clip's own map and
// its retime is rebuilt over the wider span.
const rt = retimeOf(sp.clip);
- const wIn = rt.srcAt(-sp.soundBack);
- const wOut = rt.srcAt(rt.len + sp.soundAhead);
+ const { lo, hi } = srcSpan(rt, -sp.soundBack, rt.len + sp.soundAhead);
return {
url: sp.asset.url,
start: sp.start - sp.soundBack,
- in: wIn,
- out: wOut,
- retime: retimeOf({ in: wIn, out: wOut, speed: sp.clip.speed, speedCurve: sp.clip.speedCurve }),
+ in: lo,
+ out: hi,
+ retime: retimeOf({
+ in: lo,
+ out: hi,
+ speed: sp.clip.speed,
+ speedCurve: sp.clip.speedCurve,
+ reverse: sp.clip.reverse,
+ }),
sound: sp.clip.sound,
};
};
@@ -381,12 +394,17 @@ class Engine {
// alpha read below is a per-frame pixel pass; capping the matte's decode
// keeps that pass off the frame budget.
const src = this.pool.get(
- mappingKey(asset.id, retimeOf(clip), m.in, clip.start),
+ mappingKey(asset.id, retimeOf(clip), clip.start, m.in),
asset,
Math.min(this.decodeHeight(), 480)
);
this.used.add(src);
- src.want(mt, this.renderPlaying, false, retimeOf(clip).rateAt(at - clip.start));
+ src.want(
+ mt,
+ this.renderPlaying,
+ readsDown(clip, this.renderPlaying, this.readBackward),
+ retimeOf(clip).rateAt(at - clip.start)
+ );
const frame = src.frameAt(mt, 0, dur);
if (!frame) return null;
const held = this.matteAlpha.get(clip.id);
@@ -428,7 +446,12 @@ class Engine {
const src = this.pool.get(keyOf(span.clip, span.asset), span.asset, this.decodeHeight());
this.used.add(src);
const st = sourceTimeOf(span.clip, t);
- src.want(st, playing, this.readBackward, retimeOf(span.clip).rateAt(t - span.start));
+ src.want(
+ st,
+ playing,
+ readsDown(span.clip, playing, this.readBackward),
+ retimeOf(span.clip).rateAt(t - span.start)
+ );
// A failed source that already decoded frames keeps showing the nearest
// one it holds — a transient blip (a network drop, a signed URL mid
// re-mint) reads as a held frame, and only a source with nothing at all
@@ -476,8 +499,12 @@ class Engine {
const src = this.pool.get(keyOf(sp.clip, sp.asset), sp.asset, this.decodeHeight());
if (this.used.has(src)) continue;
this.used.add(src);
- const tail = Math.max(sp.clip.in, sourceTimeOf(sp.clip, end) - 0.001);
- src.want(tail, false, true);
+ // A reversed clip's tail is its source's `in`, and backing into it
+ // reads up the source from there.
+ const tail = sp.clip.reverse
+ ? sp.clip.in
+ : Math.max(sp.clip.in, sourceTimeOf(sp.clip, end) - 0.001);
+ src.want(tail, false, !sp.clip.reverse);
}
}
}
@@ -502,7 +529,7 @@ class Engine {
// reached gets a walk, and the ones behind it get the single frame that
// lets a cut land on something.
const imminent = sp.start - t <= WARM_STREAM_S;
- src.want(sp.clip.in, playing || imminent);
+ src.want(headSrc(sp.clip), playing || imminent, !!sp.clip.reverse);
}
}
}
diff --git a/site/src/cut/lib/aiContext.ts b/site/src/cut/lib/aiContext.ts
index ff3f3ea4..77060b83 100644
--- a/site/src/cut/lib/aiContext.ts
+++ b/site/src/cut/lib/aiContext.ts
@@ -455,17 +455,19 @@ export function buildAiContext(opts?: { fullCues?: boolean; chatId?: string | nu
/** A clip's rate as the model reads it: one number, or the average plus the
* curve's nodes as [sourceSeconds, rate] when the rate changes through the
* footage. */
-function describeRate(c: { speed?: number; speedCurve?: SpeedNode[]; in: number; out: number }) {
+function describeRate(c: { speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean; in: number; out: number }) {
const nodes = speedCurveOf(c);
- if (!nodes) return { speed: r(c.speed ?? 1) };
+ const reverse = c.reverse ? { reverse: true } : {};
+ if (!nodes) return { speed: r(c.speed ?? 1), ...reverse };
return {
speed: r(retimeOf(c).rate),
speedCurve: nodes.map(([at, rate]) => [r(at), r(rate)]),
+ ...reverse,
};
}
function describeAudio(
- a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number; speed?: number; speedCurve?: SpeedNode[]; sound?: ClipSound; duck?: number; lane?: number; hidden?: boolean },
+ a: { assetId: string; start: number; in: number; out: number; volume: number; fadeIn?: number; fadeOut?: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean; sound?: ClipSound; duck?: number; lane?: number; hidden?: boolean },
assets: Map<string, { name: string }>
) {
const rt = retimeOf(a);
@@ -480,7 +482,7 @@ function describeAudio(
fadeIn: r(a.fadeIn ?? 0),
fadeOut: r(a.fadeOut ?? 0),
...(a.sound ? { sound: a.sound } : {}),
- ...(speed !== 1 || a.speedCurve ? describeRate(a) : {}),
+ ...(speed !== 1 || a.speedCurve || a.reverse ? describeRate(a) : {}),
...(a.lane ? { lane: a.lane } : {}),
...(a.hidden ? { hidden: true } : {}),
// A voiceover: while it plays, other audio ducks to this gain.
@@ -512,7 +514,7 @@ function describeOverlayClip(c: VideoClip, assets: Map<string, { name: string }>
: {}),
...(c.rotation ? { rotation: c.rotation } : {}),
...((c.opacity ?? 1) < 1 ? { opacity: r(c.opacity ?? 1) } : {}),
- ...(retimeOf(c).rate !== 1 || c.speedCurve ? describeRate(c) : {}),
+ ...(retimeOf(c).rate !== 1 || c.speedCurve || c.reverse ? describeRate(c) : {}),
...(c.grade ? { colorGrade: c.grade } : {}),
...(c.mask ? { mask: c.mask } : {}),
...(c.boxStyle ? { boxStyle: c.boxStyle } : {}),
diff --git a/site/src/cut/lib/aiTools.ts b/site/src/cut/lib/aiTools.ts
index 51c37a21..2aa71478 100644
--- a/site/src/cut/lib/aiTools.ts
+++ b/site/src/cut/lib/aiTools.ts
@@ -932,14 +932,19 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
in: round2(clip.in),
out: round2(clip.out),
speed: round2(speed),
+ ...(clip.reverse ? { reverse: true } : {}),
...(speedCurveOf(clip)
? {
speedCurve: speedCurveOf(clip)!.map(([at, rate]) => [round2(at), round2(rate)]),
- note: `this clip has a speed curve (average ${round2(speed)}×): source_t maps to the timeline through the curve, with the clip occupying [${round2(clip.start)}, ${round2(clip.start + retimeOf(clip).len)}]; work in source seconds here`,
+ note: `this clip has a speed curve (average ${round2(speed)}×${clip.reverse ? ", played backward" : ""}): source_t maps to the timeline through the curve, with the clip occupying [${round2(clip.start)}, ${round2(clip.start + retimeOf(clip).len)}]; work in source seconds here`,
}
- : {
- note: `timeline_t = ${round2(clip.start)} + (source_t - ${round2(clip.in)}) / ${round2(speed)}, for source_t in [${round2(clip.in)}, ${round2(clip.out)}]`,
- }),
+ : clip.reverse
+ ? {
+ note: `this clip plays backward: timeline_t = ${round2(clip.start)} + (${round2(clip.out)} - source_t) / ${round2(speed)}, for source_t in [${round2(clip.in)}, ${round2(clip.out)}]`,
+ }
+ : {
+ note: `timeline_t = ${round2(clip.start)} + (source_t - ${round2(clip.in)}) / ${round2(speed)}, for source_t in [${round2(clip.in)}, ${round2(clip.out)}]`,
+ }),
},
}
: {}),
@@ -1007,7 +1012,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
// Pre-map each silence's overlap with the clip's trimmed range onto the
// timeline so the model cuts on ready numbers.
const toTimeline = (t: number) =>
- round2(clip!.start + (clamp(t, clip!.in, clip!.out) - clip!.in) / speed);
+ round2(clip!.start + retimeOf(clip!).tAt(clamp(t, clip!.in, clip!.out)));
return {
silences: silences.map((x) => ({
start: round2(x.start),
@@ -1051,7 +1056,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
throw new ToolError(e instanceof Error ? e.message : "Could not read the audio.");
});
const beats = grid.beats.filter((b) => b >= from && (to === undefined || b <= to));
- const toTimeline = (t: number) => round2(clip!.start + (t - clip!.in) / speed);
+ const toTimeline = (t: number) => round2(clip!.start + retimeOf(clip!).tAt(t));
return {
bpm: grid.bpm,
beats: beats.map(round2),
@@ -2079,6 +2084,7 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
if (isNum(input.speed))
patch.speed =
Math.abs(input.speed - 1) < 1e-4 ? undefined : Math.max(SPEED_FLOOR, input.speed);
+ if (typeof input.reverse === "boolean") patch.reverse = input.reverse || undefined;
// duck >= 1 clears ducking (undefined); below 1 sets the gain.
if (isNum(input.duck)) patch.duck = input.duck >= 1 ? undefined : clamp(input.duck, 0, 1);
if (typeof input.hidden === "boolean") patch.hidden = input.hidden || undefined;
@@ -3554,13 +3560,17 @@ const toolRuns: Record<BrowserToolName, ToolRun> = {
set_speed: (s, input) => {
const clip = requireItem(s.clips, input.clipId, "video clip");
- if (!isNum(input.speed)) throw new ToolError("speed is required (e.g. 1.5).");
+ const reverse = typeof input.reverse === "boolean" ? input.reverse : undefined;
+ if (!isNum(input.speed) && reverse === undefined)
+ throw new ToolError("speed (e.g. 1.5) or reverse is required.");
const before = clipLen(clip);
- s.setClipSpeed(clip.id, input.speed);
+ if (isNum(input.speed)) s.setClipSpeed(clip.id, input.speed);
+ if (reverse !== undefined) s.setClipReverse(clip.id, reverse);
const next = useEditor.getState().clips.find((c) => c.id === clip.id)!;
return {
id: next.id,
speed: next.speed ?? 1,
+ ...(next.reverse ? { reverse: true } : {}),
lenBefore: round2(before),
lenAfter: round2(clipLen(next)),
...tracksAfter(),
@@ -4082,7 +4092,7 @@ function resolveWatchTarget(
input: Record<string, unknown>
): {
asset: MediaAsset;
- clip: { id: string; start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[] } | null;
+ clip: { id: string; start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean } | null;
} {
if (input.clip_id !== undefined && input.clip_id !== null) {
const id = String(input.clip_id);
@@ -4109,7 +4119,7 @@ function resolveWatchRange(
): {
projectId: string;
asset: MediaAsset;
- clip: { id: string; start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[] } | null;
+ clip: { id: string; start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean } | null;
speed: number;
from: number;
to: number | undefined;
diff --git a/site/src/cut/lib/audioMix.ts b/site/src/cut/lib/audioMix.ts
index 95d68a5e..9dd9ec67 100644
--- a/site/src/cut/lib/audioMix.ts
+++ b/site/src/cut/lib/audioMix.ts
@@ -23,11 +23,12 @@ import {
buildAudioFx,
retimeOf,
soundRecipe,
+ srcSpan,
type ClipSound,
type SpeedNode,
} from "@donkeycut/effects-kit";
import { decodeAudioSpan } from "./mediaRead";
-import { timeStretch } from "./timeStretch";
+import { fitSpan, retimeFits } from "./retimeFit";
/** One track-0 clip's audio in the sequential fold. A spacer (no file) only
* shapes time. */
@@ -38,6 +39,7 @@ export interface MixClip {
muted: boolean;
speed?: number;
speedCurve?: SpeedNode[];
+ reverse?: boolean;
/** Gain on the clip's own audio; absent = 1. */
volume?: number;
/** The clip's own treatment, run on its sound before the fades. */
@@ -66,6 +68,7 @@ export interface MixItem {
volume: number;
speed?: number;
speedCurve?: SpeedNode[];
+ reverse?: boolean;
/** Half the cross dissolve at this item's head and tail, with the handle
* each side reaches into — an upper-track cut crosses the same way track
* 0's does. */
@@ -158,22 +161,28 @@ export function foldClips(clips: MixClip[]) {
/** How far each side of a clip reaches into its handle for a crossing, capped
* by the ramp that crossing actually got. */
-const handles = (g: { clip: MixClip; crossIn: number; crossOut: number }) => ({
- // Never past the head of the source: a handle is what the trim left behind.
- back: Math.min(g.clip.soundBack ?? 0, g.crossIn, Math.max(0, -retimeOf(g.clip).tAt(0))),
- ahead: Math.min(g.clip.soundAhead ?? 0, g.crossOut),
-});
+const handles = (g: { clip: MixClip; crossIn: number; crossOut: number }) => {
+ const rt = retimeOf(g.clip);
+ return {
+ // Never past the head of the source: a handle is what the trim left
+ // behind. A reversed clip's head reaches toward the source's end, and
+ // `soundBack` already stops at it.
+ back: Math.min(g.clip.soundBack ?? 0, g.crossIn, rt.reverse ? Infinity : Math.max(0, -rt.tAt(0))),
+ ahead: Math.min(g.clip.soundAhead ?? 0, g.crossOut),
+ };
+};
-/** The source span an entry decodes: its own trim, widened by the handle each
- * crossing at its edges reaches into. Timeline seconds go through the entry's
- * own map on the way into the source. */
+/** The source span an entry decodes, low end first: its own trim, widened by
+ * the handle each crossing at its edges reaches into. Timeline seconds go
+ * through the entry's own map on the way into the source. */
const crossSpan = (
- c: { file: string; in: number; out: number; speed?: number; speedCurve?: SpeedNode[] },
+ c: { file: string; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean },
back = 0,
ahead = 0
) => {
const rt = retimeOf(c);
- return { file: c.file, in: rt.srcAt(-back), out: rt.srcAt(rt.len + ahead) };
+ const { lo, hi } = srcSpan(rt, -back, rt.len + ahead);
+ return { file: c.file, in: lo, out: hi };
};
/**
@@ -366,15 +375,16 @@ export async function renderMix(spec: MixSpec, opts: MixOptions): Promise<AudioB
* preview nor the engine's `atempo` does. So the buffer is stretched to the
* length it needs first, and then played at its own rate.
*/
- const stretched = new Map<string, AudioBuffer>();
+ const stretched = new Map<string, { buffer: AudioBuffer; shift: number }>();
const fitted = (
key: string,
buf: AudioBuffer,
- entry: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[] },
- from: number
- ): AudioBuffer => {
+ entry: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean },
+ from: number,
+ to: number
+ ): { buffer: AudioBuffer; shift: number } => {
const rt = retimeOf(entry);
- if (rt.uniform && rt.rate === 1) return buf;
+ if (!retimeFits(rt)) return { buffer: buf, shift: 0 };
// A span used by more than one clip at the same rate is stretched once.
const memo = `${key}@${rt.key}`;
const hit = stretched.get(memo);
@@ -382,26 +392,18 @@ export async function renderMix(spec: MixSpec, opts: MixOptions): Promise<AudioB
const channels = Array.from({ length: buf.numberOfChannels }, (_, c) =>
buf.getChannelData(c)
);
- // `from` is the source second the buffer starts at; the schedule follows
- // the clip's own map from there and lands exactly on its length.
- const fit = timeStretch(
- channels,
- buf.sampleRate,
- rt.uniform
- ? 1 / rt.rate
- : {
- factorAt: (sec) => 1 / rt.rateAtSrc(from + sec),
- outLength: Math.round((rt.tAt(from + buf.duration) - rt.tAt(from)) * buf.sampleRate),
- }
- );
+ // `from` is the source second the buffer starts at; the fit follows the
+ // clip's own map from there and lands exactly on its length.
+ const fit = fitSpan(channels, buf.sampleRate, rt, from, to);
const out = new AudioBuffer({
- length: Math.max(1, fit[0].length),
+ length: Math.max(1, fit.channels[0].length),
numberOfChannels: buf.numberOfChannels,
sampleRate: buf.sampleRate,
});
- fit.forEach((data, c) => out.getChannelData(c).set(data));
- stretched.set(memo, out);
- return out;
+ fit.channels.forEach((data, c) => out.getChannelData(c).set(data));
+ const fitted = { buffer: out, shift: fit.shift };
+ stretched.set(memo, fitted);
+ return fitted;
};
// Each buffer holds exactly the span its entry plays, already fitted to the
@@ -438,9 +440,10 @@ export async function renderMix(spec: MixSpec, opts: MixOptions): Promise<AudioB
const key = spanKey(g.span);
const buf = !c.muted && c.file ? buffers.get(key) : undefined;
if (!buf) continue; // muted, silent, or a gap spacer: only shapes time
- const from = g.at - g.back;
+ const fit = fitted(key, buf, c, Math.max(0, g.span.in), g.span.out);
+ const from = g.at - g.back + fit.shift;
const end = g.at + g.dur;
- play(fitted(key, buf, c, Math.max(0, g.span.in)), from, g.dur + g.back + g.ahead, ducked, c.sound, (gain) => {
+ play(fit.buffer, from, g.dur + g.back + g.ahead, ducked, c.sound, (gain) => {
const level = Math.max(0, c.volume ?? 1);
gain.gain.value = level;
// A crossing and a fade never share an edge — the cut carries one
@@ -471,7 +474,9 @@ export async function renderMix(spec: MixSpec, opts: MixOptions): Promise<AudioB
// A voiceover that ducks everything else is not itself ducked; it still
// lands on the bus, so the effect elements treat it with the rest.
const into = a.duck !== undefined && a.duck < 1 ? bus : ducked;
- play(fitted(key, buf, a, Math.max(0, crossSpan(a, back, ahead).in)), a.start - back, dur + back + ahead, into, a.sound, (gain) => {
+ const reach = crossSpan(a, back, ahead);
+ const fit = fitted(key, buf, a, Math.max(0, reach.in), reach.out);
+ play(fit.buffer, a.start - back + fit.shift, dur + back + ahead, into, a.sound, (gain) => {
const level = Math.max(0, a.volume);
gain.gain.value = level;
const fIn = Math.min(a.fadeIn ?? 0, dur);
diff --git a/site/src/cut/lib/cloudTranscribe.ts b/site/src/cut/lib/cloudTranscribe.ts
index e10abbe0..feb6e236 100644
--- a/site/src/cut/lib/cloudTranscribe.ts
+++ b/site/src/cut/lib/cloudTranscribe.ts
@@ -26,10 +26,11 @@ export interface CloudTranscribeSpec {
muted: boolean;
speed?: number;
speedCurve?: [number, number][];
+ reverse?: boolean;
/** Cross-dissolve overlap into the next clip, timeline seconds. */
transition?: number;
}[];
- audio: { file: string; in: number; out: number; start: number; volume: number; speed?: number; speedCurve?: [number, number][] }[];
+ audio: { file: string; in: number; out: number; start: number; volume: number; speed?: number; speedCurve?: [number, number][]; reverse?: boolean }[];
}
const RATE = 16000; // the wire format the hosted route expects
diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.ts
index 0e3bc922..993a91f4 100644
--- a/site/src/cut/lib/exportClient.ts
+++ b/site/src/cut/lib/exportClient.ts
@@ -611,6 +611,7 @@ export async function buildExportPayload(
frame: sp.clip.frame,
speed: clipSpeed(sp.clip),
speedCurve: sp.clip.speedCurve,
+ reverse: sp.clip.reverse,
transition: sp.transitionOut,
// A cross dissolve carries its own window: the picture cuts, so the
// server's blend must not see one. The handles are what the crossing
@@ -815,6 +816,7 @@ export async function buildExportPayload(
sound: c.sound,
speed: c.speed,
speedCurve: c.speedCurve,
+ reverse: c.reverse,
image: assetById.get(c.assetId)!.type === "image",
grade: normalizeGrade(c.grade),
look: c.look,
@@ -912,6 +914,7 @@ export async function buildExportPayload(
fadeOut: a.fadeOut ?? 0,
speed: a.speed,
speedCurve: a.speedCurve,
+ reverse: a.reverse,
sound: a.sound,
duck: a.duck,
}));
@@ -1425,13 +1428,16 @@ export function docFirstSeconds(doc: ExportDoc, seconds: number): ExportDoc {
// The trim that ends a clip at `seconds` goes back through the clip's own
// map, so a curved clip cuts at the source second really playing there.
const clampOut = <
- T extends { start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[] },
+ T extends { start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean },
>(
clip: T
): T => {
const rt = retimeOf(clip);
const room = seconds - clip.start;
- return rt.len <= room ? clip : { ...clip, out: rt.srcAt(room) };
+ if (rt.len <= room) return clip;
+ // The cut-off lands on the source second playing there: the tail of a
+ // reversed clip is its `in`.
+ return clip.reverse ? { ...clip, in: rt.srcAt(room) } : { ...clip, out: rt.srcAt(room) };
};
const starts = <T extends { start: number }>(item: T) => item.start < seconds;
return {
diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.ts
index af510a2f..f3c7dea0 100644
--- a/site/src/cut/lib/exportRender.ts
+++ b/site/src/cut/lib/exportRender.ts
@@ -31,7 +31,8 @@ import { audioFxSpans } from "./audioEffects";
import { renderMix, type MixClip, type MixItem, type MixSpec } from "./audioMix";
import { FrameCompositor, MISSING_FRAME, type Frame } from "./composite";
import { overlayPlan, trackZeroPlan } from "./framePlan";
-import { frameSink, openMedia, videoTrackOf } from "./mediaRead";
+import { frameSink, keyframeTimeAt, openMedia, videoTrackOf } from "./mediaRead";
+import type { InputVideoTrack, WrappedCanvas } from "mediabunny";
import { allowance, canvasBytes, holdMemory } from "./memoryBudget";
import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";
import { captionStyle, cueOverlay, cueWordFrames, laneCues, laneHidden, subtitleLaneCount, trackPos } from "./subtitles";
@@ -138,6 +139,24 @@ const READERS_TUNED = 12;
* frame's own readers are never candidates, so what a join or a stack of
* layers needs together is never taken away from the frame needing it. */
const READER_GRACE = 2;
+/**
+ * Canvas bytes a reader may hold for a clip read backward.
+ *
+ * A reversed clip asks for its frames in falling order, and a decoder only
+ * runs forward: each ask on its own would decode from the keyframe below it
+ * every time, most of a group of pictures per frame. So a step down decodes
+ * the window of frames ending at the ask in one pass and holds it, and the
+ * asks below are answered from it until it runs out. The window is as many
+ * frames as this buys at the source's size, so a 4K clip holds a few and a
+ * small one holds a dozen.
+ */
+const BACK_WINDOW_BYTES = 64 << 20;
+const BACK_WINDOW_MAX = 12;
+/** Canvases the reader's pools cycle, in frames: the forward pool plus the
+ * backward window and the two frames a fill needs around it. */
+export function readerPoolFrames(r: { backWindow: number }): number {
+ return READER_POOL + (r.backWindow > 0 ? r.backWindow + 2 : 0);
+}
/** A clip's source time at timeline time `t`. */
function sourceTimeAt(span: ClipSpan, t: number): number {
@@ -155,7 +174,15 @@ function sourceTimeAt(span: ClipSpan, t: number): number {
export class ClipReader {
private input: ReturnType<typeof openMedia> | null = null;
private sink: ClipSink | null = null;
+ private track: InputVideoTrack | null = null;
private still: Frame | null = null;
+ /** The source second last asked for; an ask below it is a step back. */
+ private lastAt = -Infinity;
+ /** The backward window: frames in rising order, on their own sink, and the
+ * frame length learned from them. */
+ private backSink: ClipSink | null = null;
+ private backFrames: WrappedCanvas[] = [];
+ private frameDt = 1 / 30;
private opened: Promise<ClipSink | null> | null = null;
/** Reads that failed in a row, each off a freshly rebuilt reader. Any
* successful read clears it. */
@@ -180,6 +207,16 @@ export class ClipReader {
return (this.asset.width ?? 1920) * (this.asset.height ?? 1080);
}
+ /** Frames the backward window holds once it is open, 0 while it is not. */
+ get backWindow(): number {
+ return this.backSink ? this.windowFrames : 0;
+ }
+
+ /** Frames a backward window holds at this source's size. */
+ private get windowFrames(): number {
+ return Math.max(2, Math.min(BACK_WINDOW_MAX, Math.floor(BACK_WINDOW_BYTES / canvasBytes(this.sourcePixels))));
+ }
+
constructor(
private asset: MediaAsset,
/** Resolved on open, and again on a re-open, so a link re-minted while the
@@ -211,6 +248,7 @@ export class ClipReader {
return null;
}
this.input = input;
+ this.track = track;
// A small pool keeps the render's canvas allocation flat over thousands
// of frames.
this.sink = frameSink(track, undefined, {
@@ -228,9 +266,11 @@ export class ClipReader {
let sink = await this.open();
if (this.still) return this.still;
if (!sink) return MISSING_FRAME;
+ const stepBack = at < this.lastAt - 1e-6;
+ this.lastAt = at;
for (;;) {
try {
- const wrapped = await sink.getCanvas(Math.max(0, at));
+ const wrapped = (stepBack && (await this.backFrame(at))) || (await sink.getCanvas(Math.max(0, at)));
this.failStreak = 0;
if (!wrapped) return MISSING_FRAME;
return {
@@ -253,6 +293,8 @@ export class ClipReader {
this.input?.dispose();
this.input = null;
this.sink = null;
+ this.track = null;
+ this.dropBack();
this.opened = null;
const reopened = await this.open();
if (!reopened) throw err;
@@ -261,10 +303,57 @@ export class ClipReader {
}
}
+ /**
+ * The frame covering `at` for a reader stepping down its source, out of
+ * the backward window — filled first when the window has run out: the
+ * frames from the keyframe below `at` (or as many as the window holds)
+ * up to `at`, decoded in one pass on the window's own sink. Null when the
+ * source has no frame there, and the ordinary read answers.
+ */
+ private async backFrame(at: number): Promise<WrappedCanvas | null> {
+ const covering = (f: WrappedCanvas) =>
+ f.timestamp <= at + 1e-4 && at < f.timestamp + Math.max(f.duration, 1e-4) + 1e-4;
+ const held = this.backFrames.find(covering);
+ if (held) return held;
+ if (!this.track) return null;
+ const kt = await keyframeTimeAt(this.track, Math.max(0, at));
+ if (kt === null) return null;
+ const window = this.windowFrames;
+ this.backSink ??= frameSink(this.track, undefined, {
+ poolSize: window + 2,
+ ...(this.software ? { software: true } : {}),
+ });
+ const start = Math.max(kt, at - (window - 1) * this.frameDt, 0);
+ const frames: WrappedCanvas[] = [];
+ const stream = this.backSink.canvases(start);
+ try {
+ for (;;) {
+ const { value, done } = await stream.next();
+ if (done || !value) break;
+ if (value.duration > 0) this.frameDt = value.duration;
+ if (value.timestamp > at + 1e-4) break;
+ frames.push(value);
+ if (frames.length > window) frames.shift();
+ if (value.timestamp + value.duration > at + 1e-4) break;
+ }
+ } finally {
+ void stream.return(undefined).catch(() => {});
+ }
+ this.backFrames = frames;
+ return frames.find(covering) ?? frames[frames.length - 1] ?? null;
+ }
+
+ private dropBack(): void {
+ this.backFrames = [];
+ this.backSink = null;
+ }
+
dispose() {
this.input?.dispose();
this.input = null;
this.sink = null;
+ this.track = null;
+ this.dropBack();
if (this.still?.kind === "ready") (this.still.image as ImageBitmap).close?.();
this.still = null;
}
@@ -536,6 +625,7 @@ export function mixSpecFor(doc: ExportDoc, resolve: (asset: MediaAsset) => strin
volume: sp.clip.volume ?? 1,
speed: sp.clip.speed,
speedCurve: sp.clip.speedCurve,
+ reverse: sp.clip.reverse,
sound: sp.clip.sound,
muted: sp.clip.muted || assetIsSilent(sp.asset),
fadeIn: ramps[i].head,
@@ -558,6 +648,7 @@ export function mixSpecFor(doc: ExportDoc, resolve: (asset: MediaAsset) => strin
volume: a.volume,
speed: a.speed,
speedCurve: a.speedCurve,
+ reverse: a.reverse,
fadeIn: a.fadeIn,
fadeOut: a.fadeOut,
sound: a.sound,
@@ -578,6 +669,7 @@ export function mixSpecFor(doc: ExportDoc, resolve: (asset: MediaAsset) => strin
muted: sp.clip.muted || !!sp.clip.hidden || assetIsSilent(sp.asset),
speed: sp.clip.speed,
speedCurve: sp.clip.speedCurve,
+ reverse: sp.clip.reverse,
volume: sp.clip.volume,
sound: sp.clip.sound,
transition: sp.transitionOut,
@@ -859,7 +951,7 @@ export class FramePainter {
* beside the preview's own pictures in the memory report. */
private readonly releaseMemory = holdMemory("exportReaders", () => {
let n = 0;
- for (const r of this.readers.values()) n += canvasBytes(READER_POOL * r.sourcePixels);
+ for (const r of this.readers.values()) n += canvasBytes(readerPoolFrames(r) * r.sourcePixels);
return n;
});
/** Frames drawn, which is the clock the readers' eviction order runs on. */
@@ -981,7 +1073,7 @@ export class FramePainter {
* grace, cannot.
*/
private evictReaders(): void {
- const cost = (r: ClipReader) => canvasBytes(READER_POOL * r.sourcePixels);
+ const cost = (r: ClipReader) => canvasBytes(readerPoolFrames(r) * r.sourcePixels);
const cap = allowance(
"exportReaders",
READERS_TUNED * canvasBytes(READER_POOL * 1920 * 1080)
diff --git a/site/src/cut/lib/filmstrip.test.ts b/site/src/cut/lib/filmstrip.test.ts
index 241a32eb..0eae863e 100644
--- a/site/src/cut/lib/filmstrip.test.ts
+++ b/site/src/cut/lib/filmstrip.test.ts
@@ -351,3 +351,29 @@ describe("a curved clip's strips agree", () => {
}
});
});
+
+describe("a reversed clip's strip", () => {
+ const clip = { in: 0, out: DURATION, speed: 1, reverse: true };
+ const retime = retimeOf(clip);
+ const tiles = planFilmstrip({
+ thumbs,
+ thumbStep: THUMB_STEP,
+ duration: DURATION,
+ aspect: 16 / 9,
+ filmIn: clip.out,
+ w: 1400,
+ pps: 1400 / retime.len,
+ speed: retime.rate,
+ retime,
+ tileH: 60,
+ minTileW: 26,
+ });
+
+ test("walks the footage backward across the box", () => {
+ expect(tiles.length).toBeGreaterThan(2);
+ for (let i = 1; i < tiles.length; i++) expect(tiles[i].srcT).toBeLessThan(tiles[i - 1].srcT);
+ expect(tiles[0].srcT).toBeGreaterThan(DURATION - 2);
+ expect(tiles[tiles.length - 1].srcT).toBeLessThan(2);
+ for (const t of tiles) expect(t.wantT).toBeGreaterThanOrEqual(0);
+ });
+});
diff --git a/site/src/cut/lib/filmstrip.ts b/site/src/cut/lib/filmstrip.ts
index 137467f7..f87db392 100644
--- a/site/src/cut/lib/filmstrip.ts
+++ b/site/src/cut/lib/filmstrip.ts
@@ -36,7 +36,7 @@
* grid: a scroll keeps a tile's capture where it was, a zoom re-aims it.
*/
-import type { Retime } from "@donkeycut/effects-kit";
+import { srcSpan, type Retime } from "@donkeycut/effects-kit";
export type FilmTile = {
/** The tile's place on the source grid at this zoom, stable across
@@ -111,9 +111,9 @@ export function pickThumbTimes(
});
}
-/** Tiles on the timeline grid for a clip whose rate changes: `imgW` pixels
- * each, the last one ending at the clip's edge, each showing the source
- * second playing at its middle. */
+/** Tiles on the timeline grid for a clip whose rate changes, or that plays
+ * backward: `imgW` pixels each, the last one ending at the clip's edge, each
+ * showing the source second playing at its middle. */
function planCurvedStrip(
p: Omit<Parameters<typeof planFilmstrip>[0], "retime"> & { retime: Retime },
imgW: number
@@ -129,8 +129,9 @@ function planCurvedStrip(
if (width <= 0) break;
const tMid = (left + width / 2) / p.pps;
const mid = Math.max(0, Math.min(p.duration, rt.srcAt(tMid)));
- const a = Math.max(0, rt.srcAt(left / p.pps));
- const b = Math.min(p.duration, rt.srcAt((left + width) / p.pps));
+ const edge = srcSpan(rt, left / p.pps, (left + width) / p.pps);
+ const a = Math.max(0, edge.lo);
+ const b = Math.min(p.duration, edge.hi);
const idx = Math.min(p.thumbs.length - 1, Math.max(0, Math.floor(mid / p.thumbStep)));
let src = p.thumbs[idx];
let exact = false;
@@ -162,9 +163,10 @@ export function planFilmstrip(p: {
/** Source seconds per timeline second across the strip (the clip's rate,
* or its average rate under a curve). */
speed: number;
- /** The clip's map, when its rate changes through the footage. The strip
- * then lays tiles on the timeline grid — a held moment takes the width it
- * plays for — with each tile picturing the source second at its middle. */
+ /** The clip's map, when its rate changes through the footage or it plays
+ * backward. The strip then lays tiles on the timeline grid — a held moment
+ * takes the width it plays for — with each tile picturing the source second
+ * at its middle. */
retime?: Retime;
tileH: number;
minTileW: number;
@@ -184,7 +186,8 @@ export function planFilmstrip(p: {
const span = p.view ? Math.min(p.w, p.view.hi - p.view.lo) : p.w;
const cells = Math.max(1, Math.ceil(span / natural));
const imgW = natural * Math.ceil(cells / FILM_TILE_CAP);
- if (p.retime && !p.retime.uniform) return planCurvedStrip({ ...p, retime: p.retime }, imgW);
+ if (p.retime && (!p.retime.uniform || p.retime.reverse))
+ return planCurvedStrip({ ...p, retime: p.retime }, imgW);
const stepT = (imgW / p.pps) * p.speed;
const filmOut = p.filmIn + (p.w / p.pps) * p.speed;
// The window, in source time, clamped to the clip.
diff --git a/site/src/cut/lib/framePlan.ts b/site/src/cut/lib/framePlan.ts
index 77a231ac..322cc7f6 100644
--- a/site/src/cut/lib/framePlan.ts
+++ b/site/src/cut/lib/framePlan.ts
@@ -1,6 +1,6 @@
"use client";
-import { retimeOf } from "@donkeycut/effects-kit";
+import { headSrc, retimeOf } from "@donkeycut/effects-kit";
/**
* What the cut looks like at one instant, worked out from the document alone.
@@ -384,9 +384,9 @@ export function trackZeroPlan(master: ClipSpan, spans: ClipSpan[], t: number): T
let backdrop: TrackZeroPlan["backdrop"] = null;
if (!incoming) {
if (abutPrev && animLive(master.clip.animIn, "in", rel, master.len)) {
- backdrop = { span: prev, at: prev.clip.out - 0.05 };
+ backdrop = { span: prev, at: prev.clip.reverse ? prev.clip.in + 0.05 : prev.clip.out - 0.05 };
} else if (abutNext && animLive(master.clip.animOut, "out", rel, master.len)) {
- backdrop = { span: next, at: next.clip.in };
+ backdrop = { span: next, at: headSrc(next.clip) };
}
}
diff --git a/site/src/cut/lib/frameSource.test.ts b/site/src/cut/lib/frameSource.test.ts
index 9c33ee29..fec64fe6 100644
--- a/site/src/cut/lib/frameSource.test.ts
+++ b/site/src/cut/lib/frameSource.test.ts
@@ -244,31 +244,60 @@ describe("mappingKey", () => {
test("clips showing identical pictures share a decoder", () => {
// A plain split: same file, same speed, and the same source time at
// timeline zero. One decoder reads straight across the cut.
- const left = mappingKey("a", uniform(1, 0), 0, 0);
- const right = mappingKey("a", uniform(1, 4), 4, 4);
+ const left = mappingKey("a", uniform(1, 0), 0);
+ const right = mappingKey("a", uniform(1, 4), 4);
expect(left).toBe(right);
});
test("different trims of one file keep their own decoders", () => {
// Both live at timeline 4, showing different moments — a same-source
// dissolve has to blend two distinct frames.
- expect(mappingKey("a", uniform(1, 0), 0, 4)).not.toBe(mappingKey("a", uniform(1, 8), 8, 4));
+ expect(mappingKey("a", uniform(1, 0), 4)).not.toBe(mappingKey("a", uniform(1, 8), 4));
});
test("a speed change is a different mapping", () => {
- expect(mappingKey("a", uniform(1, 0), 0, 0)).not.toBe(mappingKey("a", uniform(2, 0), 0, 0));
+ expect(mappingKey("a", uniform(1, 0), 0)).not.toBe(mappingKey("a", uniform(2, 0), 0));
+ });
+
+ test("a reversed clip is its own mapping", () => {
+ const rev = (inPoint: number, start: number) =>
+ mappingKey("a", retimeOf({ in: inPoint, out: inPoint + 4, speed: 1, reverse: true }), start);
+ expect(rev(0, 0)).not.toBe(mappingKey("a", uniform(1, 0, 4), 0));
+ // Two reversed halves of one span read straight across their cut too:
+ // the right half shows the lower source seconds.
+ expect(rev(4, 0)).toBe(rev(0, 4));
+ expect(rev(0, 0)).not.toBe(rev(4, 0));
});
test("a speed curve is its own mapping, keyed on the curve and the start", () => {
const curved = (start: number) =>
- mappingKey("a", retimeOf({ in: 0, out: 10, speedCurve: [[0, 1], [10, 4]] }), 0, start);
+ mappingKey("a", retimeOf({ in: 0, out: 10, speedCurve: [[0, 1], [10, 4]] }), start);
expect(curved(0)).toBe(curved(0));
expect(curved(0)).not.toBe(curved(2));
- expect(curved(0)).not.toBe(mappingKey("a", uniform(1, 0), 0, 0));
+ expect(curved(0)).not.toBe(mappingKey("a", uniform(1, 0), 0));
});
test("different files never share", () => {
- expect(mappingKey("a", uniform(1, 0), 0, 0)).not.toBe(mappingKey("b", uniform(1, 0), 0, 0));
+ expect(mappingKey("a", uniform(1, 0), 0)).not.toBe(mappingKey("b", uniform(1, 0), 0));
+ });
+
+ test("a second file read at an offset keys on that offset", () => {
+ // Two clips over one removal matte, each holding the matte from a
+ // different second. They read different pictures and need their own
+ // decoders; without the offset they would share one and fight over it.
+ const matte = (offset: number) => mappingKey("m", uniform(1, 0), 0, offset);
+ expect(matte(0)).toBe(mappingKey("m", uniform(1, 0), 0));
+ expect(matte(2)).not.toBe(matte(5));
+ // A curve keys the same way.
+ const curve = retimeOf({ in: 0, out: 10, speedCurve: [[0, 1], [10, 4]] });
+ expect(mappingKey("m", curve, 0, 2)).not.toBe(mappingKey("m", curve, 0, 5));
+ expect(mappingKey("m", curve, 0, 0)).toBe(mappingKey("m", curve, 0));
+ });
+
+ test("an offset lands on the mapping it shifts to", () => {
+ // Reading the matte two seconds back from source second 8 is the same
+ // picture as reading it straight from source second 6.
+ expect(mappingKey("m", uniform(1, 8), 0, 2)).toBe(mappingKey("m", uniform(1, 6), 0));
});
});
diff --git a/site/src/cut/lib/frameSource.ts b/site/src/cut/lib/frameSource.ts
index e44e15f4..58d6d86a 100644
--- a/site/src/cut/lib/frameSource.ts
+++ b/site/src/cut/lib/frameSource.ts
@@ -857,6 +857,7 @@ export class ClipFrameSource {
* everything that source was ever asked for.
*/
want(t: number, playing: boolean, backward = false, rate = 1): void {
+ // `backward` while playing means the clip itself reads down its source.
if (this.closed || this.unreadable) return;
// The lookahead is source seconds tuned for a clip playing at 1×. A clip
// running faster eats the ring that much sooner, so the walk stays the
@@ -870,7 +871,7 @@ export class ClipFrameSource {
return;
}
void this.open();
- if (playing) {
+ if (playing && !backward) {
this.wanted = null;
this.lastAsk = null;
// Playback reads forward; the backward walk's frames are dead weight,
@@ -878,6 +879,9 @@ export class ClipFrameSource {
this.dropBack(true);
this.pumpStream(t, true);
} else {
+ // A play down the source — a reversed clip — is the backward walk run
+ // as a clock: every frame asks a step lower, and the walk keeps the
+ // window under each ask landed before it arrives.
const prev = this.lastAsk;
this.lastAsk = t;
const b = this.back;
@@ -1891,19 +1895,22 @@ export class FrameSourcePool {
/**
* The decode identity of a clip: the frames it shows are a function of its
- * file, its rate, and where its source time stands at timeline zero. Two clips
- * agreeing on all three show the same picture at every instant. A clip whose
- * rate changes through the footage is its own map: its curve and its start.
+ * file, its rate, which way it reads, and where its source time stands at
+ * timeline zero. Two clips agreeing on all four show the same picture at
+ * every instant. A clip whose rate changes through the footage is its own
+ * map: its curve and its start.
+ *
+ * `offset` shifts the source time a caller reads at, for a second file
+ * carried along by the clip's map — a removal matte, which the clip reads at
+ * `sourceTime − matte.in`. Two clips over one matte asset at different
+ * offsets read different seconds of it, so the offset is part of the
+ * identity; left out they would share a reader and fight over its position.
*/
-export function mappingKey(
- assetId: string,
- retime: Retime,
- inPoint: number,
- start: number
-): string {
+export function mappingKey(assetId: string, retime: Retime, start: number, offset = 0): string {
+ const shift = offset ? `|${offset.toFixed(3)}` : "";
if (retime.uniform) {
- const speed = retime.rate;
- return `${assetId}|${speed}|${(inPoint - start * speed).toFixed(3)}`;
+ const speed = retime.reverse ? -retime.rate : retime.rate;
+ return `${assetId}|${speed}|${(retime.srcAt(-start) - offset).toFixed(3)}`;
}
- return `${assetId}|${retime.key}|${inPoint.toFixed(3)}|${start.toFixed(3)}`;
+ return `${assetId}|${retime.key}|${start.toFixed(3)}${shift}`;
}
diff --git a/site/src/cut/lib/genvideo/editorBridge.ts b/site/src/cut/lib/genvideo/editorBridge.ts
index fba0c590..953ca217 100644
--- a/site/src/cut/lib/genvideo/editorBridge.ts
+++ b/site/src/cut/lib/genvideo/editorBridge.ts
@@ -38,7 +38,7 @@ export const GEN_FPS = 30;
const toSec = (frames: number) => frames / GEN_FPS;
/** Effective timeline footprint of a clip (seconds), through its rate. */
-function footprintSec(c: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[] }): number {
+function footprintSec(c: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean }): number {
return retimeOf(c).len;
}
diff --git a/site/src/cut/lib/laneTracks.ts b/site/src/cut/lib/laneTracks.ts
index c5e38c27..26078f10 100644
--- a/site/src/cut/lib/laneTracks.ts
+++ b/site/src/cut/lib/laneTracks.ts
@@ -1,6 +1,6 @@
"use client";
-import { retimeOf } from "@donkeycut/effects-kit";
+import { retimeOf, type Retimable, type SpeedNode } from "@donkeycut/effects-kit";
/**
* The lane-track coordinator: the one place for how items on the timeline's
@@ -101,7 +101,7 @@ interface LaneAdapter<T> {
* keeps walking the source back and the tail grows. Media kinds only. */
revealLeftPatch?(raw: T, start: number, reveal: number): Patch<T>;
/** Earliest timeline start the left edge can reveal to (media source floor). */
- leftFloor(raw: T): number;
+ leftFloor(s: S, raw: T): number;
/** Longest timeline footprint the item can grow to (media source bound). */
maxLen(s: S, raw: T): number;
/** Write a committed lane number (multi-lane kinds only). */
@@ -128,7 +128,7 @@ interface LaneAdapter<T> {
* the source maps its own window of them. */
function mediaBeatTimes(
s: S,
- c: { assetId: string; start: number; in: number; out: number; speed?: number }
+ c: { assetId: string; start: number; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean }
): number[] {
const beats = s.assets.find((a) => a.id === c.assetId)?.beats?.beats;
if (!beats?.length) return [];
@@ -138,11 +138,32 @@ function mediaBeatTimes(
return times;
}
+/** The trim a media item's head edge writes when it lands on timeline second
+ * `tHead`: the source edge playing there — `in`, or `out` on a reversed
+ * item. */
+const headTrim = <T extends Retimable>(c: T, tHead: number, start: number): Partial<T> => {
+ const src = retimeOf(c).srcAt(tHead - start);
+ return (c.reverse ? { out: src } : { in: src }) as Partial<T>;
+};
+/** The trim the tail edge writes when it lands on `tEnd`. */
+const tailTrim = <T extends Retimable>(c: T, tEnd: number, start: number): Partial<T> => {
+ const src = retimeOf(c).srcAt(tEnd - start);
+ return (c.reverse ? { in: src } : { out: src }) as Partial<T>;
+};
+/** The earliest timeline second an item's head can reach: where the source's
+ * own head sits — second 0, or the source's end on a reversed item. */
+const headFloor = (c: Retimable & { start: number }, duration: number | undefined) =>
+ Math.max(0, c.start + retimeOf(c).tAt(c.reverse ? (duration ?? c.out) : 0));
+/** The longest an item can run: its trim opened to the source's far end,
+ * which a reversed item reaches by opening `in` toward 0. */
+const mediaMaxLen = (c: Retimable, duration: number | undefined) =>
+ retimeOf(c.reverse ? { ...c, in: 0 } : { ...c, out: duration ?? c.out }).len;
+
function videoMaxLen(s: S, c: VideoClip): number {
const a = s.assets.find((x) => x.id === c.assetId);
// A still has no source length, so its clip can stretch to any duration.
if (a?.type === "image") return Infinity;
- return retimeOf({ ...c, out: a?.duration ?? c.out }).len;
+ return mediaMaxLen(c, a?.duration);
}
const clipAdapter: LaneAdapter<VideoClip> = {
@@ -156,17 +177,17 @@ const clipAdapter: LaneAdapter<VideoClip> = {
movePatch: (c, start) => ({ id: c.id, patch: { start } }),
trimLeftPatch: (c, newStart) => ({
id: c.id,
- patch: { start: newStart, in: retimeOf(c).srcAt(newStart - c.start) },
+ patch: { start: newStart, ...headTrim(c, newStart, c.start) },
}),
trimRightPatch: (c, newEnd) => ({
id: c.id,
- patch: { out: retimeOf(c).srcAt(newEnd - c.start) },
+ patch: tailTrim(c, newEnd, c.start),
}),
revealLeftPatch: (c, start, reveal) => ({
id: c.id,
- patch: { start, in: retimeOf(c).srcAt(reveal - c.start) },
+ patch: { start, ...headTrim(c, reveal, c.start) },
}),
- leftFloor: (c) => Math.max(0, c.start + retimeOf(c).tAt(0)),
+ leftFloor: (s, c) => headFloor(c, s.assets.find((x) => x.id === c.assetId)?.duration),
maxLen: videoMaxLen,
closesGap: true,
assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),
@@ -183,19 +204,18 @@ const audioAdapter: LaneAdapter<AudioClip> = {
movePatch: (a, start) => ({ id: a.id, patch: { start } }),
trimLeftPatch: (a, newStart) => ({
id: a.id,
- patch: { start: newStart, in: retimeOf(a).srcAt(newStart - a.start) },
+ patch: { start: newStart, ...headTrim(a, newStart, a.start) },
}),
trimRightPatch: (a, newEnd) => ({
id: a.id,
- patch: { out: retimeOf(a).srcAt(newEnd - a.start) },
+ patch: tailTrim(a, newEnd, a.start),
}),
revealLeftPatch: (a, start, reveal) => ({
id: a.id,
- patch: { start, in: retimeOf(a).srcAt(reveal - a.start) },
+ patch: { start, ...headTrim(a, reveal, a.start) },
}),
- leftFloor: (a) => Math.max(0, a.start + retimeOf(a).tAt(0)),
- maxLen: (s, a) =>
- retimeOf({ ...a, out: s.assets.find((x) => x.id === a.assetId)?.duration ?? a.out }).len,
+ leftFloor: (s, a) => headFloor(a, s.assets.find((x) => x.id === a.assetId)?.duration),
+ maxLen: (s, a) => mediaMaxLen(a, s.assets.find((x) => x.id === a.assetId)?.duration),
lanePatch: (a, lane) => ({ id: a.id, patch: { lane: lane > 0 ? lane : undefined } }),
assetOf: (s, a) => s.assets.find((x) => x.id === a.assetId),
beatTimes: mediaBeatTimes,
@@ -227,17 +247,17 @@ const overlayClipAdapter: LaneAdapter<VideoClip> = {
movePatch: (c, start) => ({ id: c.id, patch: { start } }),
trimLeftPatch: (c, newStart) => ({
id: c.id,
- patch: { start: newStart, in: retimeOf(c).srcAt(newStart - c.start) },
+ patch: { start: newStart, ...headTrim(c, newStart, c.start) },
}),
trimRightPatch: (c, newEnd) => ({
id: c.id,
- patch: { out: retimeOf(c).srcAt(newEnd - c.start) },
+ patch: tailTrim(c, newEnd, c.start),
}),
revealLeftPatch: (c, start, reveal) => ({
id: c.id,
- patch: { start, in: retimeOf(c).srcAt(reveal - c.start) },
+ patch: { start, ...headTrim(c, reveal, c.start) },
}),
- leftFloor: (c) => Math.max(0, c.start + retimeOf(c).tAt(0)),
+ leftFloor: (s, c) => headFloor(c, s.assets.find((x) => x.id === c.assetId)?.duration),
maxLen: videoMaxLen,
closesGap: true,
assetOf: (s, c) => s.assets.find((x) => x.id === c.assetId),
@@ -1231,7 +1251,7 @@ export function startLaneTrim(
.sort((a, b) => a.view.start - b.view.start);
const prevEnd = leaders.reduce((m, l) => Math.max(m, l.view.start + l.view.len), 0);
const runFloor = leaders.reduce((sum, l) => sum + l.view.len, 0);
- const srcFloor = ad.leftFloor(raw0);
+ const srcFloor = ad.leftFloor(s, raw0);
const floor = Math.max(runFloor, srcFloor);
const free = Math.max(prevEnd, srcFloor);
// With the edge pinned at the floor, a media item that still has source
diff --git a/site/src/cut/lib/maskVideo.ts b/site/src/cut/lib/maskVideo.ts
index e236cf4d..3aecf9da 100644
--- a/site/src/cut/lib/maskVideo.ts
+++ b/site/src/cut/lib/maskVideo.ts
@@ -40,7 +40,7 @@ const MASK_SHORT = 480;
/** Timeline second inside a span mapped to its source second. */
const sourceTimeAt = (sp: ClipSpan, t: number) =>
- Math.min(sp.clip.out, retimeOf(sp.clip).srcAt(Math.max(0, t - sp.start)));
+ Math.max(sp.clip.in, Math.min(sp.clip.out, retimeOf(sp.clip).srcAt(Math.max(0, t - sp.start))));
/** A clip whose picture trims by the person matte (either direction). */
const subjectClip = (c: { mask?: { kind: string } }) => c.mask?.kind === "subject";
diff --git a/site/src/cut/lib/overlayHosts.ts b/site/src/cut/lib/overlayHosts.ts
index 2382e718..c2a7c5a5 100644
--- a/site/src/cut/lib/overlayHosts.ts
+++ b/site/src/cut/lib/overlayHosts.ts
@@ -36,7 +36,8 @@ const spanChanged = (a: VideoClip, b: VideoClip) =>
a.in !== b.in ||
a.out !== b.out ||
a.speed !== b.speed ||
- a.speedCurve !== b.speedCurve;
+ a.speedCurve !== b.speedCurve ||
+ a.reverse !== b.reverse;
/** The element over the same source seconds of `host` that it covered of
* `was`. The curve maps linearly past either end, so an element leading into
@@ -47,6 +48,9 @@ function ride(o: Overlay, was: VideoClip, host: VideoClip): Overlay {
const to = retimeOf(host);
let start = host.start + to.tAt(from.srcAt(o.start - was.start));
let end = host.start + to.tAt(from.srcAt(o.end - was.start));
+ // A clip turned around plays those source seconds the other way, so the
+ // element's window lands mirrored.
+ if (end < start) [start, end] = [end, start];
if (end - start < MIN_LEN) end = start + MIN_LEN;
if (start < 0) {
end -= start;
diff --git a/site/src/cut/lib/previewMixer.ts b/site/src/cut/lib/previewMixer.ts
index 1cf4759f..853eb081 100644
--- a/site/src/cut/lib/previewMixer.ts
+++ b/site/src/cut/lib/previewMixer.ts
@@ -47,7 +47,7 @@ import type { WrappedAudioBuffer } from "mediabunny";
import { assembleAudio, decodeAudioSpan, openAudioWalk, type AudioWalk } from "./mediaRead";
import { allowance, holdMemory } from "./memoryBudget";
import { meterAudioLate, meterClockJump } from "./perfTrace";
-import { timeStretch, type StretchSchedule } from "./timeStretch";
+import { fitSpan, retimeFits } from "./retimeFit";
/** How much of a voice is pulled off its walk and scheduled at once, in source
* seconds. Long enough that a stretch of sound is one scheduling decision;
@@ -79,9 +79,18 @@ const WINDOW_STRETCHED_S = 4;
const STRETCH_CACHE_BYTES = 24 * WINDOW_STRETCHED_S * 48_000 * 2 * 4;
/** What a set of decoded windows costs: float samples, one per channel. */
-const decodedBytes = (held: Map<string, AudioBuffer>): number => {
+/** A window laid through a clip's map, with the source second its first
+ * sample really sits at — see `FittedSpan.head`. */
+interface FittedWindow {
+ buffer: AudioBuffer;
+ /** Seconds past where the window was asked for that its sound begins —
+ * see `FittedSpan.shift`. */
+ shift: number;
+}
+
+const decodedBytes = (held: Map<string, FittedWindow>): number => {
let n = 0;
- for (const b of held.values()) n += b.length * b.numberOfChannels * 4;
+ for (const { buffer: b } of held.values()) n += b.length * b.numberOfChannels * 4;
return n;
};
/** Schedule more of a voice once the playhead is this close to running out.
@@ -191,6 +200,17 @@ const READ_RECHECK_MS = 10_000;
* routinely runs a fraction short of the picture it came with. */
const END_SLACK_S = 0.25;
+/** Whether `source` sits at or past the end of the span the voice plays —
+ * `out` on a voice reading forward, `in` on one reading backward — within
+ * `slack` seconds. */
+const atSpanEnd = (live: { retime: Retime; in: number; out: number }, source: number, slack = 1e-3) =>
+ live.retime.reverse ? source <= live.in + slack : source >= live.out - slack;
+
+/** A source second as progress through the voice: it rises as the voice
+ * plays, whichever way the voice reads. */
+const progress = (live: { retime: Retime }, source: number) =>
+ live.retime.reverse ? -source : source;
+
/** One audio effect element the graph is carrying: its recipe's chain, and
* the pair of gains that cross the mix between treated and untreated. */
interface LiveFx {
@@ -236,7 +256,7 @@ export class PreviewMixer {
/** Timeline time, context time and wall time of the same instant. Everything
* scheduled is placed against this. */
private anchor: { timeline: number; ctx: number; wall: number } | null = null;
- private decoded = new Map<string, AudioBuffer>();
+ private decoded = new Map<string, FittedWindow>();
private readonly releaseMemory = holdMemory("mixerAudio", () => decodedBytes(this.decoded));
/** Whether the clock is running. */
@@ -455,7 +475,7 @@ export class PreviewMixer {
// parked playhead uses — so the release finds an open file already
// read where the first window starts.
const source = live.retime.srcAt(from - live.start);
- if (!live.filling && source < live.out - 1e-3) void this.prime(live, source);
+ if (!live.filling && !atSpanEnd(live, source)) void this.prime(live, source);
}
}
// Both clocks are pulled back to where the hold began, every frame of it:
@@ -676,7 +696,7 @@ export class PreviewMixer {
const source = live.retime.srcAt(from - live.start);
// Already reading, at the end of its source, or standing close enough
// that the play's first read is the one it was going to make anyway.
- if (live.filling || source >= live.out - 1e-3) continue;
+ if (live.filling || atSpanEnd(live, source)) continue;
if (live.walk && live.walk.position >= source && live.walk.position - source <= 1) continue;
void this.prime(live, source);
}
@@ -696,9 +716,15 @@ export class PreviewMixer {
live.filling = true;
live.fillAt = performance.now();
try {
- const walk = (live.walk ??= openAudioWalk(live.url, source, live.out));
- if (Math.abs(walk.position - source) > 0.02) walk.seek(source);
- await walk.next();
+ // A voice laid through its map has no walk: its first window is the
+ // primer, decoded now and held for the play that follows.
+ if (retimeFits(live.retime)) {
+ await this.stretchedWindow(live, source);
+ } else {
+ const walk = (live.walk ??= openAudioWalk(live.url, source, live.out));
+ if (Math.abs(walk.position - source) > 0.02) walk.seek(source);
+ await walk.next();
+ }
// The read answering is the source answering: a voice backed off by an
// outage is willing again the moment its file reads, so the play that
// follows is never left waiting out a cadence the outage booked.
@@ -846,20 +872,28 @@ export class PreviewMixer {
try {
const from = live.scheduled;
const sourceFrom = live.retime.srcAt(from - live.start);
- if (sourceFrom >= live.out - 1e-3) {
+ if (atSpanEnd(live, sourceFrom)) {
live.ended = true;
return;
}
let buffer: AudioBuffer | null;
+ // How far past `from` this window's first sample belongs. A window laid
+ // through the map can start short of the second it was asked for, when
+ // the read ran into the end of the source; played at `from` it would
+ // run early for its whole length.
+ let shift = 0;
try {
// Nothing scheduled means the sound is standing still — the play just
// began, a seek landed, a hold let go — and the picture is not
// waiting. The first window is short so the sound joins it now.
const group = live.windows.length ? GROUP_S : FIRST_GROUP_S;
- buffer =
- !live.retime.uniform || Math.abs(live.retime.rate - 1) > 1e-3
- ? await this.stretchedWindow(live, sourceFrom)
- : await this.walkGroup(live, sourceFrom, current, group);
+ if (retimeFits(live.retime)) {
+ const fit = await this.stretchedWindow(live, sourceFrom);
+ buffer = fit?.buffer ?? null;
+ shift = Math.max(0, fit?.shift ?? 0);
+ } else {
+ buffer = await this.walkGroup(live, sourceFrom, current, group);
+ }
} catch {
// The read is the only part of this that says anything about the
// source, so it is the only part a failure is spent on.
@@ -878,10 +912,10 @@ export class PreviewMixer {
// further than the one before it has found where the track really
// stops, and a track that runs a fraction short of its picture is
// inside the slack.
- if (sourceFrom >= live.out - END_SLACK_S || sourceFrom <= live.reached + 1e-3) {
+ if (atSpanEnd(live, sourceFrom, END_SLACK_S) || progress(live, sourceFrom) <= live.reached + 1e-3) {
live.ended = true;
} else {
- live.reached = sourceFrom;
+ live.reached = progress(live, sourceFrom);
// A source that stopped answering mid-file is the one case a
// re-mint cannot speak to, so this failure keeps to itself.
this.miss(live, false);
@@ -890,9 +924,10 @@ export class PreviewMixer {
}
const tNow = this.at();
if (!current() || live.scheduled !== from) return;
- const until = from + buffer.duration;
+ const at2 = from + shift;
+ const until = at2 + buffer.duration;
if (until <= tNow) {
- this.noteLate(live, tNow - from);
+ this.noteLate(live, tNow - at2);
// The read outlived the moment it was for — a long wait on bytes, a
// tab in the background. Where it left the walk is behind the clock
// now, so the voice re-aims at the clock and gives up the stretch in
@@ -903,7 +938,7 @@ export class PreviewMixer {
const node = this.ctx.createBufferSource();
node.buffer = buffer;
node.connect(live.head);
- const at = this.anchor.ctx + (from - this.anchor.timeline);
+ const at = this.anchor.ctx + (at2 - this.anchor.timeline);
const now = this.ctx.currentTime;
if (at >= now) {
node.start(at);
@@ -973,26 +1008,22 @@ export class PreviewMixer {
* Held briefly, because stepping back over a cut replays the same window and
* everything older is a full decode away anyway.
*/
- private async stretchedWindow(live: LiveVoice, sourceFrom: number): Promise<AudioBuffer | null> {
+ private async stretchedWindow(live: LiveVoice, sourceFrom: number): Promise<FittedWindow | null> {
const rt = live.retime;
const tFrom = rt.tAt(sourceFrom);
- const sourceTo = Math.min(live.out, rt.srcAt(tFrom + WINDOW_STRETCHED_S));
- const key = `${live.url}|${sourceFrom.toFixed(3)}|${sourceTo.toFixed(3)}|${rt.key}`;
+ // The window runs on from `sourceFrom` the way the voice reads: up the
+ // source, or down it on a reversed clip, and never past the span.
+ const far = rt.srcAt(tFrom + WINDOW_STRETCHED_S);
+ const lo = rt.reverse ? Math.max(live.in, far) : sourceFrom;
+ const hi = rt.reverse ? sourceFrom : Math.min(live.out, far);
+ const key = `${live.url}|${lo.toFixed(3)}|${hi.toFixed(3)}|${rt.key}`;
const held = this.decoded.get(key);
if (held) return held;
- const raw = await decodeAudioSpan(live.url, sourceFrom, sourceTo);
+ const raw = await decodeAudioSpan(live.url, lo, hi);
if (!raw) return null;
- // A curve's window is laid by the clip's own map from where the window
- // starts, so its length is exactly the timeline the picture spends on it.
- const buffer = this.stretch(
- raw,
- rt.uniform
- ? 1 / rt.rate
- : {
- factorAt: (sec) => 1 / rt.rateAtSrc(sourceFrom + sec),
- outLength: Math.round((rt.tAt(sourceFrom + raw.duration) - tFrom) * raw.sampleRate),
- }
- );
+ // The window is laid by the clip's own map from where it starts, so its
+ // length is exactly the timeline the picture spends on it.
+ const buffer = this.fit(raw, rt, lo, hi);
// Oldest first until the cache is back inside its share. Emptying the
// whole cache would throw away the window the playhead is standing on along
// with the ones it has finished, and the next frame would pay a full decode
@@ -1000,9 +1031,9 @@ export class PreviewMixer {
this.decoded.set(key, buffer);
const cap = allowance("mixerAudio", STRETCH_CACHE_BYTES);
let cached = decodedBytes(this.decoded);
- for (const [oldest, buf] of this.decoded) {
+ for (const [oldest, held] of this.decoded) {
if (cached <= cap || this.decoded.size <= 1) break;
- cached -= buf.length * buf.numberOfChannels * 4;
+ cached -= held.buffer.length * held.buffer.numberOfChannels * 4;
this.decoded.delete(oldest);
}
return buffer;
@@ -1052,18 +1083,23 @@ export class PreviewMixer {
}
/** Re-lay a buffer at a different length, keeping its pitch. */
- private stretch(buffer: AudioBuffer, factor: number | StretchSchedule): AudioBuffer {
+ private fit(
+ buffer: AudioBuffer,
+ rt: Retime,
+ lo: number,
+ hi: number
+ ): { buffer: AudioBuffer; shift: number } {
const channels: Float32Array[] = [];
for (let c = 0; c < buffer.numberOfChannels; c++) channels.push(buffer.getChannelData(c));
- const out = timeStretch(channels, buffer.sampleRate, factor);
+ const out = fitSpan(channels, buffer.sampleRate, rt, lo, hi);
const result = new AudioBuffer({
- length: Math.max(1, out[0]?.length ?? 1),
- numberOfChannels: Math.max(1, out.length),
+ length: Math.max(1, out.channels[0]?.length ?? 1),
+ numberOfChannels: Math.max(1, out.channels.length),
sampleRate: buffer.sampleRate,
});
// A fresh view per channel: `copyToChannel` wants a plain Float32Array,
// and the stretch hands back views whose buffer type it declines.
- out.forEach((data, i) => result.copyToChannel(new Float32Array(data), i));
- return result;
+ out.channels.forEach((data, i) => result.copyToChannel(new Float32Array(data), i));
+ return { buffer: result, shift: out.shift };
}
}
diff --git a/site/src/cut/lib/retimeFit.test.ts b/site/src/cut/lib/retimeFit.test.ts
new file mode 100644
index 00000000..34af8414
--- /dev/null
+++ b/site/src/cut/lib/retimeFit.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, test } from "bun:test";
+import { retimeOf } from "@donkeycut/effects-kit";
+import { fitSpan, retimeFits } from "./retimeFit";
+
+const ramp = (n: number) => Float32Array.from({ length: n }, (_, i) => i / n);
+
+describe("fitSpan", () => {
+ test("a plain span comes back as it went in", () => {
+ const rt = retimeOf({ in: 0, out: 1, speed: 1 });
+ expect(retimeFits(rt)).toBe(false);
+ const out = fitSpan([ramp(100)], 100, rt, 0);
+ expect(Array.from(out.channels[0])).toEqual(Array.from(ramp(100)));
+ expect(out.head).toBe(0);
+ });
+
+ test("a reversed span at 1× is the samples turned around", () => {
+ const rt = retimeOf({ in: 0, out: 1, speed: 1, reverse: true });
+ expect(retimeFits(rt)).toBe(true);
+ const out = fitSpan([ramp(100)], 100, rt, 0);
+ expect(out.channels[0].length).toBe(100);
+ expect(out.channels[0][0]).toBeCloseTo(0.99, 6);
+ expect(out.channels[0][99]).toBe(0);
+ // Turned around, the first sample is the far end of what was read.
+ expect(out.head).toBeCloseTo(1, 6);
+ });
+
+ test("a reversed span at 2× is half as long and runs downhill", () => {
+ const rt = retimeOf({ in: 0, out: 1, speed: 2, reverse: true });
+ const out = fitSpan([ramp(1000)], 1000, rt, 0);
+ expect(Math.abs(out.channels[0].length - 500)).toBeLessThan(40);
+ const head = out.channels[0].slice(0, 50).reduce((a, b) => a + b, 0) / 50;
+ const tail = out.channels[0].slice(-50).reduce((a, b) => a + b, 0) / 50;
+ expect(head).toBeGreaterThan(tail);
+ });
+
+ test("a reversed curve lands on the map's length", () => {
+ const rt = retimeOf({
+ in: 0,
+ out: 2,
+ speedCurve: [
+ [0, 0.5],
+ [2, 2],
+ ],
+ reverse: true,
+ });
+ const out = fitSpan([ramp(2000), ramp(2000)], 1000, rt, 0);
+ expect(out.channels.length).toBe(2);
+ expect(out.channels[0].length).toBe(Math.round(rt.len * 1000));
+ });
+
+ test("a reversed span read short of its far end starts later", () => {
+ const rt = retimeOf({ in: 0, out: 2, speed: 1, reverse: true });
+ // Asked for source [0, 2], the file gave [0, 1]. Turned around, the sound
+ // in hand opens at source second 1, which the clip reaches a second in —
+ // so it is laid a second after the span's own head.
+ const out = fitSpan([ramp(100)], 100, rt, 0, 2);
+ expect(out.head).toBeCloseTo(1, 6);
+ expect(out.shift).toBeCloseTo(1, 6);
+ });
+
+ test("a whole read is laid where the span says", () => {
+ const rt = retimeOf({ in: 0, out: 1, speed: 1, reverse: true });
+ expect(fitSpan([ramp(100)], 100, rt, 0, 1).shift).toBeCloseTo(0, 6);
+ const fwd = retimeOf({ in: 0, out: 1, speed: 1 });
+ expect(fitSpan([ramp(100)], 100, fwd, 0, 1).shift).toBeCloseTo(0, 6);
+ });
+
+ test("a rate a hair off 1 is still a fit", () => {
+ const rt = retimeOf({ in: 0, out: 1, speed: 1.0005 });
+ expect(retimeFits(rt)).toBe(true);
+ const out = fitSpan([ramp(1000)], 1000, rt, 0);
+ expect(Math.abs(out.channels[0].length - 1000 / 1.0005)).toBeLessThan(40);
+ });
+});
diff --git a/site/src/cut/lib/retimeFit.ts b/site/src/cut/lib/retimeFit.ts
new file mode 100644
index 00000000..c608a9d4
--- /dev/null
+++ b/site/src/cut/lib/retimeFit.ts
@@ -0,0 +1,87 @@
+/**
+ * A decoded stretch of a clip's sound, laid along the timeline by the clip's
+ * map: stretched to the seconds the map gives it, pitch kept, and turned
+ * around when the map runs backward. Every renderer of a clip's sound — the
+ * preview mixer, the in-tab export, the engine's bake — lays its spans through
+ * this, so all three hear the same thing.
+ */
+
+import type { Retime } from "@donkeycut/effects-kit";
+import { timeStretch } from "./timeStretch";
+
+/** A rate this close to 1 lays the sound at the source's own pace. The number
+ * is here once: a caller asking whether a fit is needed and the fit deciding
+ * it has nothing to do have to agree, and a caller with the looser bar hands
+ * a clip at 1.0005× its sound unstretched while the picture runs at the
+ * clip's rate — sixty milliseconds of drift over a minute, growing with the
+ * clip. */
+const SAME_RATE = 1e-9;
+
+/** Whether a map lays sound at anything but the source's own pace and
+ * direction. */
+export const retimeFits = (rt: Retime) =>
+ !rt.uniform || Math.abs(rt.rate - 1) > SAME_RATE || rt.reverse;
+
+const turned = (data: Float32Array) => {
+ const out = new Float32Array(data.length);
+ for (let i = 0, j = data.length - 1; j >= 0; i++, j--) out[i] = data[j];
+ return out;
+};
+
+export interface FittedSpan {
+ channels: Float32Array[];
+ /** The source second the first sample sits at: `lo` forward, and the far
+ * end of what was actually read once turned around. */
+ head: number;
+ /**
+ * Seconds to add to where the span says it starts, to land the samples in
+ * hand at the moment they belong to.
+ *
+ * Zero whenever the read came back with everything it asked for, which is
+ * nearly always. A read can end early — the source ends first — and on a
+ * reversed span the missing part is the end that plays first, so the sound
+ * in hand starts later than the span does. Laid at the span's own head it
+ * would run early for the clip's whole length, sound ahead of picture.
+ */
+ shift: number;
+}
+
+/**
+ * `channels` hold the source from second `lo` onward; the result is that
+ * sound in timeline order at the map's pace.
+ *
+ * `wanted` is the source second the read was meant to reach, which is what
+ * the caller placed the span by. Left out, the samples in hand are taken as
+ * the whole of what was asked for.
+ */
+export function fitSpan(
+ channels: Float32Array[],
+ sampleRate: number,
+ rt: Retime,
+ lo: number,
+ wanted?: number
+): FittedSpan {
+ const hi = lo + (channels[0]?.length ?? 0) / sampleRate;
+ const head = rt.reverse ? hi : lo;
+ const asked = rt.reverse ? (wanted ?? hi) : lo;
+ const shift = rt.tAt(head) - rt.tAt(asked);
+ const ordered = rt.reverse ? channels.map(turned) : channels;
+ if (rt.uniform && Math.abs(rt.rate - 1) <= SAME_RATE)
+ return { channels: ordered, head, shift };
+ // Sample `i` of the ordered input is source second lo + i/sr, or hi − i/sr
+ // once turned; the rate at that source second sets the stretch there.
+ return {
+ channels: timeStretch(
+ ordered,
+ sampleRate,
+ rt.uniform
+ ? 1 / rt.rate
+ : {
+ factorAt: (sec) => 1 / rt.rateAtSrc(rt.reverse ? hi - sec : lo + sec),
+ outLength: Math.round(Math.abs(rt.tAt(hi) - rt.tAt(lo)) * sampleRate),
+ }
+ ),
+ head,
+ shift,
+ };
+}
diff --git a/site/src/cut/lib/store.ts b/site/src/cut/lib/store.ts
index 90d41477..ddf1f196 100644
--- a/site/src/cut/lib/store.ts
+++ b/site/src/cut/lib/store.ts
@@ -8,7 +8,9 @@ import {
lineLikeShape,
maskKeyAt,
removeKeyAt,
+ headSrc,
retimeOf,
+ tailSrc,
speedCurveOf,
speedCurvePreset,
upsertKey,
@@ -451,6 +453,9 @@ export interface EditorState {
setClipSpeedCurve: (id: string, nodes: SpeedNode[] | undefined) => void;
/** Lay a preset ramp over the clip's trimmed span. */
setClipSpeedPreset: (id: string, preset: string) => void;
+ /** Play the clip's footage backward (picture and sound); the footprint
+ * stays. */
+ setClipReverse: (id: string, reverse: boolean) => void;
/** Set a clip's source trim points. While track 0 is the only video track,
* a track-0 resize ripples: everything past the clip's tail rides the moved
* edge both directions, gaps keeping their width. Otherwise the run rules
@@ -1332,6 +1337,7 @@ export function cutTranscribeSpec(
.filter(
(a) =>
!a.hidden &&
+ !a.reverse &&
a.start < duration &&
assetById.has(a.assetId) &&
!assetIsSilent(assetById.get(a.assetId)!)
@@ -1344,6 +1350,7 @@ export function cutTranscribeSpec(
volume: a.volume,
speed: a.speed,
speedCurve: a.speedCurve,
+ reverse: a.reverse,
}))
.concat(
overlayLayers(s.clips)
@@ -1351,6 +1358,7 @@ export function cutTranscribeSpec(
(c) =>
!c.hidden &&
!c.muted &&
+ !c.reverse &&
c.start < duration &&
assetById.has(c.assetId) &&
!assetIsSilent(assetById.get(c.assetId)!)
@@ -1363,6 +1371,7 @@ export function cutTranscribeSpec(
volume: 1,
speed: c.speed,
speedCurve: c.speedCurve,
+ reverse: c.reverse,
}))
);
if (spans.length === 0 && audio.length === 0) return null;
@@ -1382,7 +1391,9 @@ export function cutTranscribeSpec(
file: sp.asset.fileName,
in: sp.clip.in,
out: sp.clip.out,
- muted: sp.clip.muted || assetIsSilent(sp.asset),
+ // Sound played backward is not speech; the clip keeps its
+ // time in the mix as silence.
+ muted: sp.clip.muted || assetIsSilent(sp.asset) || !!sp.clip.reverse,
speed: clipSpeed(sp.clip),
speedCurve: sp.clip.speedCurve,
// The clamped cross-dissolve overlap, so the mix overlaps clip
@@ -2662,6 +2673,12 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
get().setClipSpeedCurve(id, nodes);
},
+ setClipReverse: (id, reverse) => {
+ const clip = get().clips.find((c) => c.id === id);
+ if (!clip || !!clip.reverse === reverse) return;
+ get().updateClip(id, { reverse: reverse || undefined });
+ },
+
setClipTrim: (id, nextIn, nextOut) => {
const clip = get().clips.find((c) => c.id === id);
if (!clip) return;
@@ -3376,6 +3393,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
// length and stays in sync (an AudioClip plays at its own `speed`).
...(clipSpeed(clip) !== 1 ? { speed: clipSpeed(clip) } : {}),
...(clip.speedCurve ? { speedCurve: clip.speedCurve } : {}),
+ ...(clip.reverse ? { reverse: true } : {}),
};
set((s) => ({
audioClips: [...s.audioClips, audio],
@@ -3394,9 +3412,10 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const len = a ? clipLen(a) : 0;
if (a && t > a.start + 0.05 && t < a.start + len - 0.05) {
push();
- const cutIn = a.in + (t - a.start);
- const left: AudioClip = { ...a, out: cutIn };
- const right: AudioClip = { ...a, id: uid(), start: t, in: cutIn };
+ const cutIn = retimeOf(a).srcAt(t - a.start);
+ const [head, tail] = splitTrims(a, cutIn);
+ const left: AudioClip = { ...a, ...head };
+ const right: AudioClip = { ...a, id: uid(), start: t, ...tail };
set((s) => {
const idx = s.audioClips.findIndex((c) => c.id === a.id);
const next = [...s.audioClips];
@@ -3422,8 +3441,9 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
// The cut lands mid-footage, so the edges it creates stay plain:
// the exit animation belongs to the right half's tail and the
// entrance to the left half's head.
- const left: VideoClip = { ...c, out: cutIn, transition: undefined, transitionStyle: undefined, animOut: undefined };
- const right: VideoClip = { ...c, id: uid(), start: t, in: cutIn, animIn: undefined };
+ const [head, tail] = splitTrims(c, cutIn);
+ const left: VideoClip = { ...c, ...head, transition: undefined, transitionStyle: undefined, animOut: undefined };
+ const right: VideoClip = { ...c, id: uid(), start: t, ...tail, animIn: undefined };
set((s) => {
const idx = s.clips.findIndex((x) => x.id === c.id);
const next = [...s.clips];
@@ -3497,8 +3517,9 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
// lands mid-footage, so the edges it creates stay plain: the exit
// animation stays on the right half's tail, the entrance on the left's
// head.
- const left: VideoClip = { ...span.clip, out: cutAt, transition: undefined, transitionStyle: undefined, animOut: undefined };
- const right: VideoClip = { ...span.clip, id: uid(), in: cutAt, start: t, animIn: undefined };
+ const [head, tail] = splitTrims(span.clip, cutAt);
+ const left: VideoClip = { ...span.clip, ...head, transition: undefined, transitionStyle: undefined, animOut: undefined };
+ const right: VideoClip = { ...span.clip, id: uid(), ...tail, start: t, animIn: undefined };
set((s) => {
const idx = s.clips.findIndex((c) => c.id === span.clip.id);
const next = [...s.clips];
@@ -3746,20 +3767,20 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
if (mi == null) continue;
// Track-0 clips re-materialize onto track 0 (asClip), so a template
// stands up its own video instead of an empty timeline.
- layers.push({ media: mi, start: sp.start - start0, in: sp.clip.in, out: sp.clip.out, ...framingOf(sp.clip), muted: sp.clip.muted, speed: sp.clip.speed, speedCurve: sp.clip.speedCurve, sound: sp.clip.sound, track: 1, asClip: true });
+ layers.push({ media: mi, start: sp.start - start0, in: sp.clip.in, out: sp.clip.out, ...framingOf(sp.clip), muted: sp.clip.muted, speed: sp.clip.speed, speedCurve: sp.clip.speedCurve, reverse: sp.clip.reverse, sound: sp.clip.sound, track: 1, asClip: true });
} else {
const c = s.clips.find((x) => x.id === sel.id);
if (!c) continue;
const mi = mediaFor(c.assetId);
if (mi == null) continue;
- layers.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, ...framingOf(c), muted: c.muted, speed: c.speed, speedCurve: c.speedCurve, sound: c.sound, track: c.track + 1 });
+ layers.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, ...framingOf(c), muted: c.muted, speed: c.speed, speedCurve: c.speedCurve, reverse: c.reverse, sound: c.sound, track: c.track + 1 });
}
} else if (sel.kind === "audio") {
const c = s.audioClips.find((x) => x.id === sel.id);
if (!c) continue;
const mi = mediaFor(c.assetId);
if (mi == null) continue;
- audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed, speedCurve: c.speedCurve, sound: c.sound, duck: c.duck, lane: c.lane });
+ audio.push({ media: mi, start: c.start - start0, in: c.in, out: c.out, volume: c.volume, fadeIn: c.fadeIn, fadeOut: c.fadeOut, speed: c.speed, speedCurve: c.speedCurve, reverse: c.reverse, sound: c.sound, duck: c.duck, lane: c.lane });
} else if (sel.kind === "overlay") {
const o = s.overlays.find((x) => x.id === sel.id);
// Asset-backed stickers stay out: a template copies only the media
@@ -3890,6 +3911,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
...templateFraming(l),
...(l.speed ? { speed: l.speed } : {}),
...(l.speedCurve ? { speedCurve: l.speedCurve } : {}),
+ ...(l.reverse ? { reverse: true } : {}),
...(l.sound ? { sound: l.sound } : {}),
}));
const topTrack = Math.max(0, ...overlayLayers(get().clips).map((c) => c.track));
@@ -3909,6 +3931,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
...templateFraming(l),
...(l.speed ? { speed: l.speed } : {}),
...(l.speedCurve ? { speedCurve: l.speedCurve } : {}),
+ ...(l.reverse ? { reverse: true } : {}),
...(l.sound ? { sound: l.sound } : {}),
}));
const newAudio: AudioClip[] = template.audio
@@ -3924,6 +3947,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
...(a.fadeOut ? { fadeOut: a.fadeOut } : {}),
...(a.speed ? { speed: a.speed } : {}),
...(a.speedCurve ? { speedCurve: a.speedCurve } : {}),
+ ...(a.reverse ? { reverse: true } : {}),
...(a.sound ? { sound: a.sound } : {}),
...(a.duck !== undefined && a.duck < 1 ? { duck: a.duck } : {}),
...(a.lane ? { lane: a.lane } : {}),
@@ -4132,6 +4156,7 @@ export const useEditor = create<EditorState>((baseSet, get, api) => {
const sp = clipWindow(s.clips, s.assets, clipId);
if (!sp) throw new Error("The clip is no longer on the timeline.");
if (assetIsSilent(sp.asset)) throw new Error("This clip is a still — it has no sound.");
+ if (sp.clip.reverse) throw new Error("This clip plays backward — its sound is not speech.");
const lane = s.subtitleLane;
const epoch = laneEpoch;
// The clip's own sound, deliberately unmuted: this transcribes what the
@@ -5616,8 +5641,9 @@ function buildClipSpans(clips: VideoClip[], assets: MediaAsset[], track: number)
len,
transitionOut: onSound ? 0 : overlap,
soundOut,
- soundAhead: handleSeconds(soundOut, asset.duration - clip.out, clip, "tail"),
- soundBack: handleSeconds(prevSound, clip.in, clip, "head"),
+ // A reversed clip's head faces the source's end and its tail its start.
+ soundAhead: handleSeconds(soundOut, clip.reverse ? clip.in : asset.duration - clip.out, clip, "tail"),
+ soundBack: handleSeconds(prevSound, clip.reverse ? asset.duration - clip.out : clip.in, clip, "head"),
});
}
return spans;
@@ -5635,10 +5661,20 @@ function handleSeconds(
// The handle plays at the pace of the footage beside the edge: a source
// second past `out` lasts as long as the last source second inside it.
const rt = retimeOf(clip);
- const edgeRate = rt.rateAtSrc(edge === "head" ? clip.in : clip.out);
+ const edgeRate = rt.rateAtSrc(edge === "head" ? headSrc(clip) : tailSrc(clip));
return Math.max(0, Math.min(want, Math.max(0, sourceLeft) / edgeRate));
}
+/** The trims a split at source second `cut` leaves each half: the half
+ * playing first keeps the footage up to the cut on a forward item and the
+ * footage after it on a reversed one. */
+function splitTrims(
+ c: { in: number; out: number; reverse?: boolean },
+ cut: number
+): [{ in?: number; out?: number }, { in?: number; out?: number }] {
+ return c.reverse ? [{ in: cut }, { out: cut }] : [{ out: cut }, { in: cut }];
+}
+
/** One row of the timeline, whichever kind of thing sits on it. Video rows are
* `track`; audio and title rows are the item's `lane`. */
export type LaneRef =
diff --git a/site/src/cut/lib/types.ts b/site/src/cut/lib/types.ts
index 33350f19..ce7dcc6c 100644
--- a/site/src/cut/lib/types.ts
+++ b/site/src/cut/lib/types.ts
@@ -446,6 +446,7 @@ export function clipPoseAt(
out: number;
speed?: number;
speedCurve?: SpeedNode[];
+ reverse?: boolean;
rotation?: number;
opacity?: number;
kf?: OverlayKey[];
@@ -548,6 +549,10 @@ export interface VideoClip {
* integral of the curve over the trim (see retimeOf). Nodes sit in source
* seconds, so trims and splits leave them where they are. */
speedCurve?: SpeedNode[];
+ /** Plays the footage backward: the head of the clip shows `out` and the
+ * tail shows `in`, picture and sound alike. The rate still applies, so the
+ * footprint is unchanged. */
+ reverse?: boolean;
/** Transition into the next clip on this clip's track, in timeline seconds
* (absent/0 = hard cut). Every style overlaps the two clips by this much,
* so the cut shortens. On upper tracks a transition blends the incoming
@@ -995,6 +1000,9 @@ export interface AudioClip {
speed?: number;
/** The video clip's speed curve, carried along on detach for the same reason. */
speedCurve?: SpeedNode[];
+ /** The video clip's reverse, carried along on detach so the sound keeps
+ * running backward with the picture. */
+ reverse?: boolean;
/** Voiceover ducking: while this clip is audible, every other sound (clip
* audio and other soundtrack clips) drops to this gain, 0..1. Absent = no
* ducking. Ducking clips never duck each other. */
@@ -1034,6 +1042,7 @@ export interface TemplateLayer {
muted: boolean;
speed?: number;
speedCurve?: SpeedNode[];
+ reverse?: boolean;
sound?: ClipSound;
track: number;
/** Came from video track 0 — re-materializes as a timeline clip, not an
@@ -1050,6 +1059,7 @@ export interface TemplateAudio {
fadeOut?: number;
speed?: number;
speedCurve?: SpeedNode[];
+ reverse?: boolean;
sound?: ClipSound;
duck?: number;
lane?: number;
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index fbd3f25b..53bbd81e 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -97,10 +97,10 @@ Times are in seconds on the shared timeline. The playhead is currentTime; a skim
- Two ways to move a track-0 clip: place_clip sets its start (respects gaps, slides right if the spot is taken); move_clip reorders by index, opening a slot at the landing point — clips after it shift right, every other gap survives. Index-based inserts (freeze_frame, generated clips) open a slot the same way.
- add_clip puts a project asset on the timeline the way a drag does: video/image onto track 0 (a \`start\`, an \`index\` insert, or appended at the end), audio onto the soundtrack.
- Overlay video: a video/image asset can sit on a track above track 0 (track 1, 2… — topmost wins). A full-frame overlay covers everything below it; give it a layout to share the frame — top/bottom/left/right halves for a split screen, pip for a floating corner box, or a custom region rect. add_overlay_video creates one from a media asset; update_overlay_video moves/trims/regions/mutes/hides it. The user makes them by dragging media above track 0; they drag the region in the preview.
-- A clip's timeline length is (out-in)/speed — or, for a clip with a speed curve, the integral of its curve over the trim (editor_state reports \`len\` either way, and lists a curved clip's \`speedCurve\` nodes as [sourceSeconds, rate]). Total duration runs to the last clip's end, gaps included. Transitions blend at cuts and never change layout or length.
+- A clip's timeline length is (out-in)/speed — or, for a clip with a speed curve, the integral of its curve over the trim (editor_state reports \`len\` either way, and lists a curved clip's \`speedCurve\` nodes as [sourceSeconds, rate]). A clip with \`reverse: true\` plays its trim backward at that same rate — same length, head showing source \`out\`, sound running backward too. Total duration runs to the last clip's end, gaps included. Transitions blend at cuts and never change layout or length.
- trim_clip changes in/out inside the source media. in >= 0, out <= source duration, out-in >= 0.1.
- Resizes ripple the same way deletes do: while track 0 is the only video track, a track-0 trim or speed change slides everything past the clip's tail — clips, titles, captions, soundtrack — with the moved edge, in both directions, every existing gap keeping its width. With overlay video tracks present, growth pushes the track-0 run and a shrink leaves a gap.
-- set_speed sets a clip's playback rate; it changes the clip's timeline length and carries the timeline behind it like a trim. set_speed_curve makes the rate change through the footage — nodes of {at: source seconds, speed} or a named preset ramp — for speed ramps, whips, holds, and hits on the beat: detect_beats first, then place nodes at the beats it returns (same unit, no arithmetic). set_speed on a curved clip makes it uniform again.
+- set_speed sets a clip's playback rate; it changes the clip's timeline length and carries the timeline behind it like a trim. set_speed with \`reverse: true\` plays the clip backward (a rewind, a drop that rises, a pour that un-pours); it changes nothing about length or the curve. set_speed_curve makes the rate change through the footage — nodes of {at: source seconds, speed} or a named preset ramp — for speed ramps, whips, holds, and hits on the beat: detect_beats first, then place nodes at the beats it returns (same unit, no arithmetic). set_speed on a curved clip makes it uniform again.
- set_transition joins a clip into the next one (0–2s, ${TRANSITION_STYLE_IDS.length} styles); set_animation animates one clip's own entrance/exit — read the transitions-and-fades skill before styling cuts. Splitting or deleting clears the affected transition. A transition is a bar on its own row at an absolute time, so an edit can leave one lining up with nothing: every timeline mutation reports those as \`parkedTransitions\`, and clearing them (remove_transition) is part of finishing the edit. Grading a clip's picture is the color tools (set_color_preset, set_color_grade, set_color_curves, set_color_wheels, set_color_hsl — read the color-grading skill); a stylized post treatment (grain, VHS, halation…) is add_effect, dropped over the stretch of timeline it covers — as is a treatment on the sound (echo, reverb, telephone…).
- Cutting a clip's background away — the AI person matte, ink around the silhouette, a fill behind the subject — is the cutout suite (set_removal, set_removal_stroke, set_removal_background); read the background-removal skill.
- split_at cuts the track-0 clip under that time into two clips at the exact frame. With a soundtrack or overlay clip selected it splits that instead.
@@ -171,7 +171,7 @@ The flow for "edit this for me":
Time math (get this right):
- watch_video, detect_silence, and trim_clip speak SOURCE seconds; split_at and place_clip speak TIMELINE seconds.
-- timeline_t = clip.start + (source_t − clip.in) / clip.speed, valid while source_t is inside [in, out]. Each watch result's clip block carries this formula with the real numbers filled in. A clip with a speed curve has no closed form: work in source seconds there (trim_clip, set_speed_curve, split by proportion of its reported len) and read the clip's len from editor_state after each change.
+- timeline_t = clip.start + (source_t − clip.in) / clip.speed, valid while source_t is inside [in, out]; a reversed clip runs the other way, timeline_t = clip.start + (clip.out − source_t) / clip.speed. Each watch result's clip block carries the right formula with the real numbers filled in. A clip with a speed curve has no closed form: work in source seconds there (trim_clip, set_speed_curve, split by proportion of its reported len) and read the clip's len from editor_state after each change.
- The same source can appear in several clips — map per clip.
Cutting speech well: pace is part of the message, and it is set in one place — refine_speech_cuts' \`pace\`. "Fast paced", "punchy", "tight" means pace: fast there; a calm piece means relaxed. Placing your own edges closer to the words is not a faster cut, it is a clipped one: a word's tail runs past its cue, the ear hears the truncation, and no amount of tightening reads as energy. So cut loose — up to a second of spare air on each side — and let the refine step take it back to the beat the pace asks for. Shorten a long pause to that beat rather than deleting it; speech butted directly together reads as rushed however fast the piece is meant to be. Prefer split_at + delete_item, then place_clip to close the gap (a beat of black may be wanted — ask the cut, not the tool); trim_clip only tightens a clip's edges.`,
diff --git a/site/src/cut/server/exportPipeline.test.ts b/site/src/cut/server/exportPipeline.test.ts
index 64eaec41..e8bfc2f9 100644
--- a/site/src/cut/server/exportPipeline.test.ts
+++ b/site/src/cut/server/exportPipeline.test.ts
@@ -10,8 +10,13 @@ import {
// Builds the real encode filtergraph for a spec by running the pipeline with
// its edges stubbed: media exists, every stream probes present, SDR color,
// libx264, and ffmpeg runs are captured instead of spawned.
-const graphFor = async (over: Partial<ExportSpec>): Promise<string[]> => {
+/** Every ffmpeg run the pipeline made for a spec, in order; the graph is the
+ * one carrying `-filter_complex`. */
+const runsFor = async (over: Partial<ExportSpec>): Promise<string[][]> => {
const ffmpegCalls: string[][] = [];
+ // Seconds each turned file was asked to produce, summed off the `-t` of the
+ // chunk runs that wrote its pieces, so the bake reads back a whole file.
+ const produced = new Map<string, number>();
const io: ExportPipelineIO = {
stat: (async () => ({ isFile: () => true })) as unknown as ExportPipelineIO["stat"],
writeFile: (async () => {}) as unknown as ExportPipelineIO["writeFile"],
@@ -19,9 +24,14 @@ const graphFor = async (over: Partial<ExportSpec>): Promise<string[]> => {
unlink: (async () => {}) as unknown as ExportPipelineIO["unlink"],
hasStream: async () => true,
videoColorInfo: async () => null,
+ videoDecodeCost: async () => null,
+ mediaDuration: async (file) => produced.get(file) ?? 0,
h264Encoder: async () => "libx264",
runFfmpeg: async (_job, args) => {
ffmpegCalls.push(args);
+ const piece = args[args.length - 1].match(/^(.*)\.\d+\.(?:mov|wav)$/);
+ const len = args.indexOf("-t");
+ if (piece && len >= 0) produced.set(piece[1], (produced.get(piece[1]) ?? 0) + Number(args[len + 1]));
},
};
const clips = over.clips ?? [];
@@ -45,7 +55,12 @@ const graphFor = async (over: Partial<ExportSpec>): Promise<string[]> => {
log: [],
};
await runExport(job, spec, (f) => `/media/${f}`, io);
- const enc = ffmpegCalls.find((a) => a.includes("-filter_complex"))!;
+ return ffmpegCalls;
+};
+
+const graphFor = async (over: Partial<ExportSpec>): Promise<string[]> => {
+ const runs = await runsFor(over);
+ const enc = runs.find((a) => a.includes("-filter_complex"))!;
return enc[enc.indexOf("-filter_complex") + 1].split(";");
};
@@ -704,3 +719,60 @@ describe("audio effects in the filtergraph", () => {
expect(joined).toContain("concat=n=3:v=0:a=1[afx1]");
});
});
+
+describe("a reversed clip in the filtergraph", () => {
+ const reversed = clip("a.mp4", { in: 2, out: 8, speed: 2, reverse: true, soundBack: 0.5, soundAhead: 0.25 });
+
+ test("is baked turned around in chunks and read forward off the copy", async () => {
+ const runs = await runsFor({ clips: [reversed, clip("b.mp4")] });
+ const graph = runs.find((a) => a.includes("-filter_complex"))!;
+ const bakes = runs.filter((a) => a.includes("-i") && a.includes("/media/a.mp4"));
+ // The reach: the trim plus the handles at the clip's rate, [1.5, 9].
+ // Three-second chunks from the top: [6, 9], [3, 6], [1.5, 3].
+ expect(bakes.map((a) => [a[a.indexOf("-ss") + 1], a[a.indexOf("-t") + 1]])).toEqual([
+ ["6.000", "3.000"],
+ ["3.000", "3.000"],
+ ["1.500", "1.500"],
+ ]);
+ for (const a of bakes) {
+ expect(a[a.indexOf("-vf") + 1]).toBe("reverse,format=yuv420p");
+ expect(a[a.indexOf("-af") + 1]).toBe("areverse");
+ expect(a.indexOf("-ss")).toBeLessThan(a.indexOf("-i"));
+ expect(a.indexOf("-t")).toBeLessThan(a.indexOf("-i"));
+ }
+ const join = runs.find((a) => a.includes("concat"))!;
+ expect(join).toContain("-c");
+ expect(join[join.indexOf("-c") + 1]).toBe("copy");
+ // The graph reads the copy, never the source, and trims the mirrored
+ // span: source [2, 8] under a pivot of 9 is [1, 7] in the copy.
+ const inputs = graph.slice(0, graph.indexOf("-filter_complex"));
+ expect(inputs).not.toContain("/media/a.mp4");
+ expect(inputs.some((p) => p.endsWith("turned_clip_0.mov"))).toBe(true);
+ const idx = inputs.filter((p, i) => inputs[i - 1] === "-i").findIndex((p) => p.endsWith("turned_clip_0.mov"));
+ const g = graph[graph.indexOf("-filter_complex") + 1].split(";");
+ const video = g.find((f) => f.startsWith(`[${idx}:v]trim=`))!;
+ expect(video).toContain("trim=1.000:7.000,setpts=(PTS-STARTPTS)/2");
+ expect(video).not.toContain("reverse");
+ const audio = g.find((f) => f.startsWith(`[${idx}:a]atrim=`))!;
+ expect(audio).toContain("atrim=1.000:7.000");
+ expect(audio).toContain("atempo");
+ expect(audio).not.toContain("areverse");
+ });
+
+ test("a reversed curve keeps its length and lands mirrored on the copy", async () => {
+ const curved = clip("a.mp4", {
+ in: 0,
+ out: 4,
+ speedCurve: [
+ [0, 1],
+ [4, 4],
+ ],
+ reverse: true,
+ });
+ const g = await graphFor({ clips: [curved, clip("b.mp4")] });
+ const video = g.find((f) => f.startsWith("[1:v]trim="))!;
+ expect(video).toContain("trim=0.000:4.000,setpts='(clip(T-STARTT");
+ const first = g.find((f) => f.includes("apad=whole_dur="))!;
+ expect(first).toContain(`apad=whole_dur=${retimeOf(curved).len.toFixed(3)}`);
+ });
+});
diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.ts
index d9e34c76..1ca52cfe 100644
--- a/site/src/cut/server/exportPipeline.ts
+++ b/site/src/cut/server/exportPipeline.ts
@@ -1,11 +1,12 @@
import { spawn, type ChildProcess } from "node:child_process";
import { readFile, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
-import { atempoChain, hasStream, num, videoColorInfo } from "./util";
+import { atempoChain, hasStream, mediaDuration, num, videoColorInfo, videoDecodeCost } from "./util";
import { assertGraphSafe, fexpr } from "./filterGraph";
import { bakeRetimedAudio, setptsExpr, type BakedAudio } from "./retimeAudio";
+import { bakeTurnedMedia } from "./turnMedia";
import { CLIP_MAX_ZOOM, projectFadeSeconds, regionPx, TRANSITION_XFADE, TRANSITION_ZOOM, type ColorGrade, type TransitionStyle } from "../lib/types";
-import { audioFxFilters, buildGradeLut, effectFilterLines, gradeKey, gradeNeedsLut, gradeToFfmpegFilter, isAudioEffect, lookFilterLines, lutToCube, retimeOf, shortestTurn, sortedKeys, soundFilters, type ClipSound, type OverlayKey, type Retime, type SpeedNode } from "@donkeycut/effects-kit";
+import { audioFxFilters, buildGradeLut, effectFilterLines, gradeKey, gradeNeedsLut, gradeToFfmpegFilter, isAudioEffect, lookFilterLines, lutToCube, mirrorRetimable, retimeOf, shortestTurn, srcSpan, sortedKeys, soundFilters, type ClipSound, type OverlayKey, type Retime, type SpeedNode } from "@donkeycut/effects-kit";
// The render pipeline itself: spec in, finished mp4 out. Shared by the local
// engine's job registry (jobs.ts) and the cloud render worker, which stage
@@ -92,6 +93,7 @@ export interface ExportSpec {
/** A rate that changes through the footage: [source second, rate] nodes
* (see retimeOf); present, `speed` is ignored. */
speedCurve?: SpeedNode[];
+ reverse?: boolean;
/** Transition into the next clip, in timeline seconds (overlap). */
transition?: number;
/** Half the cross dissolve into the next clip, in timeline seconds: the
@@ -182,6 +184,7 @@ export interface ExportSpec {
/** A rate that changes through the footage: [source second, rate] nodes
* (see retimeOf); present, `speed` is ignored. */
speedCurve?: SpeedNode[];
+ reverse?: boolean;
/** Transition ramps, timeline seconds from this overlay's head/tail. On
* an upper track a fade is an alpha fade (the tracks beneath show
* through); a cross transition arrives as the incoming clip's headFade
@@ -245,6 +248,7 @@ export interface ExportSpec {
/** A rate that changes through the footage: [source second, rate] nodes
* (see retimeOf); present, `speed` is ignored. */
speedCurve?: SpeedNode[];
+ reverse?: boolean;
sound?: ClipSound;
/** Voiceover ducking: while this clip plays, every other sound drops to
* this gain (0..1). Ducking clips never duck each other. */
@@ -393,7 +397,7 @@ const retimedPts = (rt: Retime) =>
rt.uniform ? `(PTS-STARTPTS)/${num(rt.rate)}` : fexpr(setptsExpr(rt));
/** Timeline length of a media clip's span through its rate or curve. */
-const spanLen = (c: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[] }) =>
+const spanLen = (c: { in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean }) =>
Math.max(0.1, retimeOf(c).len);
/** A clip's frame region in even pixels, or null when it fills the whole frame
@@ -465,11 +469,24 @@ export interface ExportPipelineIO {
unlink: typeof unlink;
hasStream: typeof hasStream;
videoColorInfo: typeof videoColorInfo;
+ videoDecodeCost: typeof videoDecodeCost;
+ mediaDuration: typeof mediaDuration;
h264Encoder: () => Promise<"libx264" | "h264_videotoolbox">;
runFfmpeg: typeof runFfmpeg;
}
-const realIO: ExportPipelineIO = { stat, writeFile, readFile, unlink, hasStream, videoColorInfo, h264Encoder, runFfmpeg };
+const realIO: ExportPipelineIO = {
+ stat,
+ writeFile,
+ readFile,
+ unlink,
+ hasStream,
+ videoColorInfo,
+ videoDecodeCost,
+ mediaDuration,
+ h264Encoder,
+ runFfmpeg,
+};
/** Render `spec` into `job.outPath`. `mediaPathFor` maps a spec media file
* name to its staged path on disk (the engine reads the project folder; the
@@ -484,6 +501,67 @@ export async function runExport(
if (spec.clips.length === 0) throw new Error("Nothing to export.");
const { width: W, height: H, fps } = spec;
+ // A clip that plays backward is rendered off a turned copy of its span,
+ // baked ahead of the graph in bounded chunks (turnMedia.ts): the clip
+ // becomes a forward clip over that file, its curve's nodes carried along,
+ // and everything below reads it like any other footage. The copy joins the
+ // inputs by its own path, past the project-folder lookup.
+ const turned = new Map<string, { video: boolean; audio: boolean }>();
+ const turn = async <
+ T extends {
+ file: string;
+ in: number;
+ out: number;
+ speed?: number;
+ speedCurve?: SpeedNode[];
+ reverse?: boolean;
+ soundBack?: number;
+ soundAhead?: number;
+ image?: boolean;
+ },
+ >(
+ c: T,
+ tag: string,
+ /** A soundtrack entry, whose picture the graph never reads. Detached from
+ * a video file it would otherwise have its whole span re-encoded backward
+ * frame by frame for nothing. */
+ soundOnly = false
+ ): Promise<T> => {
+ if (!c.reverse || !c.file || c.image) return c;
+ const src = await resolveMedia(io.stat, mediaPathFor, c.file);
+ const rt = retimeOf(c);
+ // The span plus the handles a crossing reaches into, so the copy holds
+ // what the sound of a cross dissolve needs on either side.
+ const reach = srcSpan(rt, -(c.soundBack ?? 0), rt.len + (c.soundAhead ?? 0));
+ const lo = Math.max(0, reach.lo);
+ const hi = Math.max(lo + 0.001, reach.hi);
+ const video = !soundOnly && (await io.hasStream(src, "v"));
+ const audio = await io.hasStream(src, "a");
+ const colorFix = video ? sdrConvert(await io.videoColorInfo(src)) : "";
+ const decodeCost = video ? ((await io.videoDecodeCost(src)) ?? 0) : 0;
+ const file = path.join(job.tmpDir, `turned_${tag}.${video ? "mov" : "wav"}`);
+ const pivot = await bakeTurnedMedia(
+ {
+ ffmpeg: (args) => io.runFfmpeg(job, args),
+ writeFile: (p, data) => io.writeFile(p, data),
+ h264Encoder: io.h264Encoder,
+ duration: io.mediaDuration,
+ },
+ src,
+ { lo, hi, video, audio, colorFix, decodeCost },
+ file
+ );
+ turned.set(file, { video, audio });
+ return { ...mirrorRetimable(c, pivot), file };
+ };
+ const turnedClips: ExportSpec["clips"] = [];
+ for (const [j, c] of spec.clips.entries()) turnedClips.push(await turn(c, `clip_${j}`));
+ const turnedOverlays: NonNullable<ExportSpec["overlayVideos"]> = [];
+ for (const [k, oc] of (spec.overlayVideos ?? []).entries()) turnedOverlays.push(await turn(oc, `ovl_${k}`));
+ const turnedAudio: ExportSpec["audio"] = [];
+ for (const [k, a] of spec.audio.entries()) turnedAudio.push(await turn(a, `snd_${k}`, true));
+ spec = { ...spec, clips: turnedClips, overlayVideos: turnedOverlays, audio: turnedAudio };
+
// Tracks number 0..N bottom-up: track 0 folds sequentially into the base
// picture, the rest overlay it in track order (highest last = frontmost).
// Within a track, earlier clips composite first, so a dissolving pair
@@ -537,7 +615,7 @@ export async function runExport(
...overlayVideos.filter((o) => !o.image),
]
.map((c) => c.file)
- .filter(Boolean)
+ .filter((f) => f && !turned.has(f))
),
];
const audioPresence = new Map<string, boolean>();
@@ -572,6 +650,14 @@ export async function runExport(
colorFix.set(f, sdrConvert(await io.videoColorInfo(paths[i])));
})
);
+ // The turned copies: already probed at the bake, already folded to SDR.
+ for (const [file, streams] of turned) {
+ inputIndex.set(file, nInputs++);
+ inputs.push("-i", file);
+ audioPresence.set(file, streams.audio);
+ videoPresence.set(file, streams.video);
+ colorFix.set(file, "");
+ }
// Animated overlays: each is its own concat-demuxer slideshow (region-sized
// frames with transparent filler around the element's window), the exact
// mechanism the caption lanes use. Static overlays stay single PNG inputs.
@@ -810,6 +896,7 @@ export async function runExport(
out: number;
speed?: number;
speedCurve?: SpeedNode[];
+ reverse?: boolean;
soundBack?: number;
soundAhead?: number;
muted?: boolean;
diff --git a/site/src/cut/server/retimeAudio.ts b/site/src/cut/server/retimeAudio.ts
index e602cdaf..ae8f2804 100644
--- a/site/src/cut/server/retimeAudio.ts
+++ b/site/src/cut/server/retimeAudio.ts
@@ -12,8 +12,8 @@
* export path promises.
*/
-import type { Retime } from "@donkeycut/effects-kit";
-import { timeStretch } from "../lib/timeStretch";
+import { srcSpan, type Retime } from "@donkeycut/effects-kit";
+import { fitSpan } from "../lib/retimeFit";
import { num } from "./util";
/** The bake's sample rate: what the graphs resample every input to. */
@@ -54,8 +54,9 @@ export async function bakeRetimedAudio(
const rt = retime;
// A handle cannot reach before the source's first sample; the head reach
// is whatever the source really had.
- const from = Math.max(0, rt.srcAt(-Math.max(0, back)));
- const to = Math.max(from, rt.srcAt(rt.len + Math.max(0, ahead)));
+ const reach = srcSpan(rt, -Math.max(0, back), rt.len + Math.max(0, ahead));
+ const from = Math.max(0, reach.lo);
+ const to = Math.max(from, reach.hi);
const pcm = `${outFile}.f32`;
await io.ffmpeg([
"-y",
@@ -92,16 +93,14 @@ export async function bakeRetimedAudio(
// it here keeps the stretch from running beside a second copy of the span.
raw = null;
// The file may run short of `to` — the source ended first — so the output
- // length follows the samples actually read, through the same map.
- const inSec = frames / BAKE_RATE;
- const tFrom = rt.tAt(from);
- const outLength = Math.max(1, Math.round((rt.tAt(from + inSec) - tFrom) * BAKE_RATE));
- const out = timeStretch(channels, BAKE_RATE, {
- factorAt: (sec) => 1 / rt.rateAtSrc(from + sec),
- outLength,
- });
- await io.writeFile(outFile, wavFloat32(out, BAKE_RATE));
- return { file: outFile, back: -tFrom, len: outLength / BAKE_RATE };
+ // length follows the samples actually read, through the same map, and so
+ // does the head the fit reports: `from` on a forward clip, the far end of
+ // what was read on a reversed one.
+ const out = fitSpan(channels, BAKE_RATE, rt, from);
+ const tHead = rt.tAt(out.head);
+ const outLength = Math.max(1, out.channels[0]?.length ?? 1);
+ await io.writeFile(outFile, wavFloat32(out.channels, BAKE_RATE));
+ return { file: outFile, back: -tHead, len: outLength / BAKE_RATE };
}
/** A WAV container around float samples: what ffmpeg reads back as pcm_f32le. */
diff --git a/site/src/cut/server/transcribe.ts b/site/src/cut/server/transcribe.ts
index 2e2f1bb8..3e66ab27 100644
--- a/site/src/cut/server/transcribe.ts
+++ b/site/src/cut/server/transcribe.ts
@@ -23,6 +23,7 @@ export interface TranscribeSpec {
muted: boolean;
speed?: number;
speedCurve?: SpeedNode[];
+ reverse?: boolean;
/** Cross-dissolve overlap into the next clip, timeline seconds. */
transition?: number;
}[];
@@ -34,6 +35,7 @@ export interface TranscribeSpec {
volume: number;
speed?: number;
speedCurve?: SpeedNode[];
+ reverse?: boolean;
}[];
}
@@ -357,7 +359,7 @@ async function runTranscribe(job: TranscribeJob, spec: TranscribeSpec) {
// A clip whose rate changes through its footage is baked to a WAV in
// timeline seconds first (the same stretch the export and the preview
// use), so its words land where they play.
- type Sounding = { file: string; in: number; out: number; speed?: number; speedCurve?: SpeedNode[] };
+ type Sounding = { file: string; in: number; out: number; speed?: number; speedCurve?: SpeedNode[]; reverse?: boolean };
const baked = new Map<Sounding, BakedAudio & { idx: number }>();
const bakeIO = {
ffmpeg: async (args: string[]) => {
diff --git a/site/src/cut/server/turnMedia.test.ts b/site/src/cut/server/turnMedia.test.ts
new file mode 100644
index 00000000..35e6c311
--- /dev/null
+++ b/site/src/cut/server/turnMedia.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, test } from "bun:test";
+import { bakeTurnedMedia, turnChunkSeconds, TURN_CHUNK_S, type TurnIO, type TurnSpec } from "./turnMedia";
+
+const FOURK30 = 3840 * 2160 * 1.5 * 30;
+
+/** A bake that records its runs and hands back however much of the span the
+ * source actually had. `capped` cuts the file off at that source second. */
+const fakeIO = (capped = Infinity) => {
+ const runs: string[][] = [];
+ let made = 0;
+ const io: TurnIO = {
+ ffmpeg: async (args) => {
+ runs.push(args);
+ const at = args.indexOf("-ss");
+ const len = args.indexOf("-t");
+ if (at < 0 || len < 0) return;
+ const from = Number(args[at + 1]);
+ made += Math.max(0, Math.min(from + Number(args[len + 1]), capped) - from);
+ },
+ writeFile: async () => {},
+ h264Encoder: async () => "libx264",
+ duration: async () => made,
+ };
+ return { io, runs, chunks: () => runs.filter((a) => a.includes("-ss")) };
+};
+
+const spec = (over: Partial<TurnSpec> = {}): TurnSpec => ({
+ lo: 0,
+ hi: 6,
+ video: true,
+ audio: true,
+ colorFix: "",
+ ...over,
+});
+
+describe("turnChunkSeconds", () => {
+ test("footage nothing is known about gets the plain ceiling", () => {
+ expect(turnChunkSeconds()).toBe(TURN_CHUNK_S);
+ expect(turnChunkSeconds(0)).toBe(TURN_CHUNK_S);
+ });
+
+ test("light footage gets the ceiling, heavy footage gets less", () => {
+ expect(turnChunkSeconds(1280 * 720 * 1.5 * 30)).toBe(TURN_CHUNK_S);
+ const fourK = turnChunkSeconds(FOURK30);
+ expect(fourK).toBeLessThan(TURN_CHUNK_S);
+ // Whatever the ceiling is, one chunk of 4K30 stays inside half a gigabyte.
+ expect(fourK * FOURK30).toBeLessThan(512 * 1024 * 1024);
+ // And 4K60 costs twice as much a second, so it gets half as long a chunk.
+ expect(turnChunkSeconds(FOURK30 * 2)).toBeCloseTo(fourK / 2, 6);
+ });
+
+ test("even the heaviest source keeps a chunk long enough to encode", () => {
+ expect(turnChunkSeconds(7680 * 4320 * 1.5 * 120)).toBeGreaterThanOrEqual(0.2);
+ });
+});
+
+describe("bakeTurnedMedia", () => {
+ test("a heavy source is cut into more, shorter chunks", async () => {
+ const light = fakeIO();
+ await bakeTurnedMedia(light.io, "/s.mov", spec(), "/out.mov");
+ const heavy = fakeIO();
+ await bakeTurnedMedia(heavy.io, "/s.mov", spec({ decodeCost: FOURK30 }), "/out.mov");
+ expect(heavy.chunks().length).toBeGreaterThan(light.chunks().length);
+ });
+
+ test("sound alone is not cut by the picture's weight", async () => {
+ const { io, chunks } = fakeIO();
+ await bakeTurnedMedia(io, "/s.wav", spec({ video: false, decodeCost: FOURK30 }), "/out.wav");
+ expect(chunks().length).toBe(2);
+ });
+
+ test("chunks run from the span's end back to its start", async () => {
+ const { io, chunks } = fakeIO();
+ await bakeTurnedMedia(io, "/s.mov", spec({ lo: 1, hi: 7 }), "/out.mov");
+ const starts = chunks().map((a) => Number(a[a.indexOf("-ss") + 1]));
+ expect(starts).toEqual([4, 1]);
+ });
+
+ test("a whole span pivots on the second it was asked for", async () => {
+ const { io } = fakeIO();
+ expect(await bakeTurnedMedia(io, "/s.mov", spec({ lo: 2, hi: 8 }), "/out.mov")).toBeCloseTo(8, 6);
+ });
+
+ test("a span reaching past the source's end pivots on what came back", async () => {
+ // Asked for source [2, 8] of a file that stops at 5.
+ const { io } = fakeIO(5);
+ expect(await bakeTurnedMedia(io, "/s.mov", spec({ lo: 2, hi: 8 }), "/out.mov")).toBeCloseTo(5, 6);
+ });
+
+ test("a file it cannot read back is an error", async () => {
+ const { io } = fakeIO();
+ io.duration = async () => null;
+ let thrown: unknown;
+ await bakeTurnedMedia(io, "/s.mov", spec(), "/out.mov").catch((e) => (thrown = e));
+ expect(String(thrown).includes("read back")).toBe(true);
+ });
+});
diff --git a/site/src/cut/server/turnMedia.ts b/site/src/cut/server/turnMedia.ts
new file mode 100644
index 00000000..8e6b9db2
--- /dev/null
+++ b/site/src/cut/server/turnMedia.ts
@@ -0,0 +1,117 @@
+/**
+ * A stretch of a source played backward, laid on disk for the graph.
+ *
+ * ffmpeg turns a stream around by holding every frame of it, so one pass over
+ * a long span would hold the whole span decoded at once — a minute of 4K is
+ * gigabytes. The span is baked in chunks, from its end back to its start, each
+ * turned on its own and encoded; the pieces are then joined stream-copy in
+ * that order. The file plays the span backward, and the decoded picture held
+ * at any moment is one chunk's worth, which is sized in bytes off the source's
+ * frame size and rate. Source second `s` of the span sits at `pivot − s` in
+ * the file, where `pivot` is what the bake reports back.
+ *
+ * A clip that plays backward is rendered off this file as a forward clip
+ * (see `mirrorRetimable`), so the graph itself never turns anything around.
+ */
+
+import { num } from "./util";
+
+/** The longest stretch of source one chunk turns at once, and the shortest.
+ * The ceiling keeps the join list short on ordinary footage; the floor stops
+ * a very heavy source from being cut into pieces too small to encode well. */
+export const TURN_CHUNK_S = 3;
+const TURN_CHUNK_MIN_S = 0.2;
+/** Decoded picture one `reverse` pass may hold. ffmpeg keeps every frame of
+ * the chunk in memory until the chunk ends, so this is the bake's real
+ * ceiling: at 4K30 it comes to about a second of source, at 4K60 half of one. */
+const TURN_HOLD_BYTES = 384 * 1024 * 1024;
+
+/** Seconds of source a chunk may cover, given what a second of the source's
+ * picture comes to decoded. */
+export function turnChunkSeconds(decodeCost = 0): number {
+ if (!(decodeCost > 0)) return TURN_CHUNK_S;
+ return Math.max(TURN_CHUNK_MIN_S, Math.min(TURN_CHUNK_S, TURN_HOLD_BYTES / decodeCost));
+}
+
+/** The intermediate's H.264 quality, on the CRF scale; near-transparent, since
+ * the graph encodes it once more. */
+const TURN_CRF = 14;
+
+export interface TurnIO {
+ ffmpeg: (args: string[]) => Promise<void>;
+ writeFile: (path: string, data: string) => Promise<void>;
+ h264Encoder: () => Promise<"libx264" | "h264_videotoolbox">;
+ /** How long a file runs; the bake reads the joined file back to learn what
+ * it actually got. */
+ duration: (path: string) => Promise<number | null>;
+}
+
+export interface TurnSpec {
+ /** Absolute source seconds, `lo < hi`. */
+ lo: number;
+ hi: number;
+ /** Which streams the source carries; the file carries the same. */
+ video: boolean;
+ audio: boolean;
+ /** The picture's fold to BT.709 (see `sdrConvert`), run before the turn so
+ * the file is plain SDR the graph converts nothing about. */
+ colorFix: string;
+ /** Bytes a second of the source's picture comes to decoded (see
+ * `videoDecodeCost`), which sizes the chunks. */
+ decodeCost?: number;
+}
+
+const vtQuality = (crf: number) => Math.round(Math.max(35, Math.min(80, 100 - crf * 1.8)));
+
+/**
+ * Bake `src`'s `[lo, hi]` turned around into `outFile`: a `.mov` when the
+ * source has a picture, a `.wav` when it is sound alone.
+ *
+ * Returns the pivot the file is read through — source second `s` sits at
+ * `pivot − s`. A span reaching past where the source ends comes back short,
+ * and the missing part is the end that plays first, so the pivot is measured
+ * from what the bake produced. Taking `hi` on faith would slide the clip's
+ * whole length by the shortfall.
+ */
+export async function bakeTurnedMedia(
+ io: TurnIO,
+ src: string,
+ spec: TurnSpec,
+ outFile: string
+): Promise<number> {
+ const span = Math.max(0.001, spec.hi - spec.lo);
+ const chunk = spec.video ? turnChunkSeconds(spec.decodeCost) : TURN_CHUNK_S;
+ const n = Math.max(1, Math.ceil(span / chunk));
+ const pieces: string[] = [];
+ const enc = spec.video ? await io.h264Encoder() : null;
+ for (let i = 0; i < n; i++) {
+ // Chunks run from the span's end back to its start, so the joined file
+ // plays the span backward.
+ const to = spec.hi - i * chunk;
+ const from = Math.max(spec.lo, to - chunk);
+ if (to - from <= 1e-4) break;
+ const piece = `${outFile}.${i}${spec.video ? ".mov" : ".wav"}`;
+ const args = ["-y", "-hide_banner", "-loglevel", "error", "-ss", num(from), "-t", num(to - from), "-i", src];
+ if (spec.video) {
+ args.push("-vf", `${spec.colorFix}reverse,format=yuv420p`);
+ args.push(
+ ...(enc === "libx264"
+ ? ["-c:v", "libx264", "-preset", "veryfast", "-crf", String(TURN_CRF)]
+ : ["-c:v", "h264_videotoolbox", "-q:v", String(vtQuality(TURN_CRF)), "-allow_sw", "1"])
+ );
+ } else {
+ args.push("-vn");
+ }
+ if (spec.audio) args.push("-af", "areverse", "-c:a", spec.video ? "pcm_s16le" : "pcm_f32le");
+ else args.push("-an");
+ args.push(piece);
+ await io.ffmpeg(args);
+ pieces.push(piece);
+ }
+ const list = `${outFile}.txt`;
+ await io.writeFile(list, pieces.map((p) => `file '${p.replace(/'/g, "'\\''")}'`).join("\n") + "\n");
+ await io.ffmpeg(["-y", "-hide_banner", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", list, "-c", "copy", outFile]);
+ const made = await io.duration(outFile);
+ if (made == null) throw new Error(`could not read back the turned file for ${src}`);
+ return spec.lo + made;
+}
diff --git a/site/src/cut/server/util.ts b/site/src/cut/server/util.ts
index 0c37e9b7..1b458384 100644
--- a/site/src/cut/server/util.ts
+++ b/site/src/cut/server/util.ts
@@ -175,6 +175,82 @@ export function videoDimensions(
});
}
+/**
+ * Bytes of decoded picture one second of a file's video comes to — width ×
+ * height × 1.5 for yuv420p, times the frame rate. A pass that has to hold a
+ * stretch of decoded frames at once sizes that stretch by this. Null when the
+ * probe fails or the file carries no picture.
+ */
+export function videoDecodeCost(file: string): Promise<number | null> {
+ return new Promise((resolve) => {
+ const p = spawn("ffprobe", [
+ "-v", "error",
+ "-select_streams", "v:0",
+ "-show_entries", "stream=width,height,avg_frame_rate,r_frame_rate",
+ "-of", "json",
+ file,
+ ]);
+ let out = "";
+ const timer = setTimeout(() => {
+ p.kill("SIGKILL");
+ resolve(null);
+ }, 30_000);
+ timer.unref();
+ p.stdout.on("data", (d) => (out += d));
+ p.on("close", (code) => {
+ clearTimeout(timer);
+ if (code !== 0) return resolve(null);
+ try {
+ const s = JSON.parse(out).streams?.[0];
+ const width = Number(s?.width);
+ const height = Number(s?.height);
+ if (!(width > 0) || !(height > 0)) return resolve(null);
+ const ratio = (v: unknown) => {
+ const [n, d] = String(v ?? "").split("/");
+ const fps = Number(n) / (Number(d) || 1);
+ return Number.isFinite(fps) && fps > 0 && fps < 1000 ? fps : 0;
+ };
+ const fps = ratio(s?.avg_frame_rate) || ratio(s?.r_frame_rate) || 30;
+ resolve(width * height * 1.5 * fps);
+ } catch {
+ resolve(null);
+ }
+ });
+ p.on("error", () => {
+ clearTimeout(timer);
+ resolve(null);
+ });
+ });
+}
+
+/** How long a media file runs, in seconds, or null when the probe fails. */
+export function mediaDuration(file: string): Promise<number | null> {
+ return new Promise((resolve) => {
+ const p = spawn("ffprobe", [
+ "-v", "error",
+ "-show_entries", "format=duration",
+ "-of", "csv=p=0",
+ file,
+ ]);
+ let out = "";
+ const timer = setTimeout(() => {
+ p.kill("SIGKILL");
+ resolve(null);
+ }, 30_000);
+ timer.unref();
+ p.stdout.on("data", (d) => (out += d));
+ p.on("close", (code) => {
+ clearTimeout(timer);
+ const seconds = Number(out.trim());
+ resolve(code === 0 && Number.isFinite(seconds) && seconds >= 0 ? seconds : null);
+ });
+ p.on("error", () => {
+ clearTimeout(timer);
+ resolve(null);
+ });
+ });
+}
+
/**
* Whether a media file carries a stream of the given kind ("a" audio /
* "v" video). Resolves false only when ffprobe reports no such stream; a