Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(core): speed ramps as a rate lane in data-automation (#4129)
Miguel Ángel7f452ad27656
diff --git a/packages/core/src/audioAutomation.ts b/packages/core/src/audioAutomation.tsindex ec873d6cdd..18cae25305 100644--- a/packages/core/src/audioAutomation.ts+++ b/packages/core/src/audioAutomation.ts@@ -13,6 +13,7 @@import { getAudioFxDef, type HfAudioFxChain } from "./audioFx.js";import { MAX_AUDIO_GAIN } from "./audioGain.js";+import { MAX_PLAYBACK_RATE, MIN_PLAYBACK_RATE } from "./playbackRateBounds.js";export const HF_AUDIO_AUTOMATION_ATTR = "data-automation";@@ -80,14 +81,19 @@ export class AudioAutomationError extends Error {export const VOLUME_TARGET = "volume";+/** Playback-rate lane: `v` is a speed multiplier over clip-local time. See `speedRamp.ts`. */+export const RATE_TARGET = "rate";+export type HfAutomationTarget =| { kind: "volume" }+ | { kind: "rate" }| { kind: "fx"; nodeId: string; param: string }| { kind: "preset"; presetId: string };/** Split a target string. Returns null for anything unrecognised. */export function parseAutomationTarget(target: string): HfAutomationTarget | null {if (target === VOLUME_TARGET) return { kind: "volume" };+ if (target === RATE_TARGET) return { kind: "rate" };const parts = target.split(".");// `fx.preset.<id>` before the 3-part fx form, because it IS a 3-part fx form// with a reserved node id — an effect can never be called "preset", since ids@@ -169,6 +175,16 @@ export const VOLUME_RANGE: AutomationRange = {default: 1,};+export const RATE_RANGE: AutomationRange = {+ min: MIN_PLAYBACK_RATE,+ max: MAX_PLAYBACK_RATE,+ step: 0.05,+ unit: "x",+ label: "Speed",+ scale: "log",+ default: 1,+};+/*** Resolve a lane's target against a chain. Returns null when the target names* a node or parameter that is not there — the effect was deleted, or the@@ -181,6 +197,7 @@ export function resolveAutomationRange(const parsed = parseAutomationTarget(target);if (!parsed) return null;if (parsed.kind === "volume") return VOLUME_RANGE;+ if (parsed.kind === "rate") return RATE_RANGE;if (parsed.kind === "preset") {// Only for a preset the chain actually carries, so a lane left behind by a// removed preset resolves to nothing and is dropped at read time — the same@@ -335,7 +352,12 @@ export function normalizeAutomation(automation: HfAutomation): HfAutomation {const lanes: HfAutomationLane[] = [];for (const lane of automation.lanes) {if (!parseAutomationTarget(lane.target)) continue;- const range = lane.target === VOLUME_TARGET ? VOLUME_RANGE : null;+ const range =+ lane.target === VOLUME_TARGET+ ? VOLUME_RANGE+ : lane.target === RATE_TARGET+ ? RATE_RANGE+ : null;const points = normalizePoints(lane.points ?? [], range);if (points.length > 0) lanes.push({ target: lane.target, points });}diff --git a/packages/core/src/playbackRateBounds.ts b/packages/core/src/playbackRateBounds.tsnew file mode 100644index 0000000000..a82cb0eaf3--- /dev/null+++ b/packages/core/src/playbackRateBounds.ts@@ -0,0 +1,3 @@+/** The one clamp for a playback rate: the constant attribute and the rate lane alike. */+export const MIN_PLAYBACK_RATE = 0.1;+export const MAX_PLAYBACK_RATE = 10;diff --git a/packages/core/src/runtime/audioAutomationVolume.ts b/packages/core/src/runtime/audioAutomationVolume.tsindex 733a3bfec9..3a4ea306d1 100644--- a/packages/core/src/runtime/audioAutomationVolume.ts+++ b/packages/core/src/runtime/audioAutomationVolume.ts@@ -24,18 +24,20 @@ import {const cache = new Map<string, HfAutomationLane | null>();const CACHE_LIMIT = 64;-function laneFromAttr(raw: string): HfAutomationLane | null {- const hit = cache.get(raw);+/** The lane for `target` inside a `data-automation` value, or null when absent or unreadable. */+export function laneFromAttr(raw: string, target: string = VOLUME_TARGET): HfAutomationLane | null {+ const key = `${target}\0${raw}`;+ const hit = cache.get(key);if (hit !== undefined) return hit;let lane: HfAutomationLane | null = null;try {- lane = parseAutomation(raw).lanes.find((l) => l.target === VOLUME_TARGET) ?? null;+ lane = parseAutomation(raw).lanes.find((l) => l.target === target) ?? null;} catch {// Unreadable automation plays the track flat rather than silencing it.lane = null;}if (cache.size > CACHE_LIMIT) cache.clear();- cache.set(raw, lane);+ cache.set(key, lane);return lane;}diff --git a/packages/core/src/runtime/clock.test.ts b/packages/core/src/runtime/clock.test.tsindex 5801ee1f78..6e4e1672f8 100644--- a/packages/core/src/runtime/clock.test.ts+++ b/packages/core/src/runtime/clock.test.ts@@ -272,6 +272,21 @@ describe("TransportClock", () => {expect(clock.getSource()).toBe("monotonic");});+ it("maps audio position back to composition time through a rate lane", () => {+ const { clock } = createClock({ duration: 20 });+ const rate = {+ target: "rate",+ points: [+ { t: 0, v: 1 },+ { t: 2, v: 3 },+ ],+ };+ const audioEl = createMockAudioEl(4, false);+ clock.play();+ clock.attachAudioSource({ el: audioEl, compositionStart: 1, mediaStart: 0, rate });+ expect(clock.now()).toBeCloseTo(1 + 2 + (4 - 3.641) / 3, 2);+ });+it("accounts for compositionStart offset", () => {const { clock } = createClock({ duration: 20 });const audioEl = createMockAudioEl(2.0, false);diff --git a/packages/core/src/runtime/clock.ts b/packages/core/src/runtime/clock.tsindex b18b3ee98a..13d5a17878 100644--- a/packages/core/src/runtime/clock.ts+++ b/packages/core/src/runtime/clock.ts@@ -1,3 +1,5 @@+import { timeAtSourceTime, type RateSpec } from "../speedRamp.js";+export type TransportClockSnapshot = {time: number;playing: boolean;@@ -11,6 +13,8 @@ export type AudioClockSource =el: HTMLMediaElement;compositionStart: number;mediaStart: number;+ /** The clip's rate lane; a constant rate is read from `el.playbackRate`. */+ rate?: RateSpec;}| {currentTimeSeconds: number;@@ -54,12 +58,14 @@ export class TransportClock {if ("currentTimeSeconds" in this._audioSource) {audioTime = this._audioSource.currentTimeSeconds;} else {- const { el, compositionStart, mediaStart } = this._audioSource;+ const { el, compositionStart, mediaStart, rate } = this._audioSource;if (!el.paused && Number.isFinite(el.currentTime)) {audioTime =- ((el.currentTime - mediaStart) / (el.playbackRate > 0 ? el.playbackRate : 1)) *- this._rate +- compositionStart;+ typeof rate === "object"+ ? timeAtSourceTime(rate, el.currentTime - mediaStart) + compositionStart+ : ((el.currentTime - mediaStart) / (el.playbackRate > 0 ? el.playbackRate : 1)) *+ this._rate ++ compositionStart;}}if (audioTime !== null) {diff --git a/packages/core/src/runtime/init.test.ts b/packages/core/src/runtime/init.test.tsindex 2e533380ce..12f6a0e7ef 100644--- a/packages/core/src/runtime/init.test.ts+++ b/packages/core/src/runtime/init.test.ts@@ -4171,6 +4171,20 @@ describe("derived duration floor recomputation", () => {expect(await runFrames(1)).toBe(25);});+ it("re-derives when a speed-ramp lane is edited", async () => {+ mountComposition(`<video data-start="0"></video>`);+ const video = document.querySelector("video")!;+ setNativeDuration(video, 10);+ initSandboxRuntimeModular();+ expect(await runFrames(2)).toBe(10);++ video.setAttribute(+ "data-automation",+ JSON.stringify({ version: 1, lanes: [{ target: "rate", points: [{ t: 0, v: 2 }] }] }),+ );+ expect(await runFrames(1)).toBe(5);+ });+it("re-derives when a clip is moved later on the timeline", async () => {mountComposition(`<video data-start="0" data-duration="10"></video>`);initSandboxRuntimeModular();diff --git a/packages/core/src/runtime/init.ts b/packages/core/src/runtime/init.tsindex 215e523d57..3076ea13bc 100644--- a/packages/core/src/runtime/init.ts+++ b/packages/core/src/runtime/init.ts@@ -18,9 +18,11 @@ import {patchWebGLVideoTextureCompat,} from "./adapters/video-texture-compat";import { forceDispatchSeekEvent, waitForSeekCompletion } from "./adapters/seek-dispatch";+import { sourceTimeAt } from "../speedRamp";import { createWaapiAdapter } from "./adapters/waapi";import {readElementPlaybackRate,+ readElementRateSpec,readElementPlaybackStart,refreshRuntimeMediaCache,resolveRuntimeMediaClipDuration,@@ -1068,6 +1070,7 @@ export function initSandboxRuntimeModular(): void {"data-hf-auto-start",MEDIA_START_BASIS_ATTR,"data-playback-rate",+ "data-automation","data-playback-start","data-media-start",// `data-start` may be an expression referencing another element by id, and@@ -3366,7 +3369,7 @@ export function initSandboxRuntimeModular(): void {const timelineDuration = getTimelineDurationSeconds(timeline);const sourceTime =readElementPlaybackStart(node) +- Math.max(0, timeSeconds - start) * readElementPlaybackRate(node);+ sourceTimeAt(readElementRateSpec(node), Math.max(0, timeSeconds - start));const localTime = Math.max(0,timelineDuration != null && timelineDuration > 0@@ -3800,7 +3803,12 @@ export function initSandboxRuntimeModular(): void {const mediaStart = readElementPlaybackStart(rawEl);if (Number.isFinite(start) && state.currentTime >= start && state.currentTime < end) {if (!rawEl.paused) {- clock.attachAudioSource({ el: rawEl, compositionStart: start, mediaStart });+ clock.attachAudioSource({+ el: rawEl,+ compositionStart: start,+ mediaStart,+ rate: readElementRateSpec(rawEl),+ });foundActive = true;} else if (!rawEl.error && rawEl.readyState < HTMLMediaElement.HAVE_FUTURE_DATA) {// Audio is buffering — freeze visuals at last known position@@ -3953,6 +3961,8 @@ export function initSandboxRuntimeModular(): void {// that existed before (#3458).const route = classifyWebAudioMediaRoute(rawEl);reportWebAudioMediaRoute(rawEl, route);+ // Decoded buffers cannot follow a rate curve without shifting pitch; the media element can.+ if (typeof readElementRateSpec(rawEl) !== "number") continue;// The cross-origin verdict's BEST outcome is decode, since a CDN that// sends `Access-Control-Allow-Origin` (the author just never wrote the// `crossorigin` attribute) decodes fine and keeps the whole FX graph.diff --git a/packages/core/src/runtime/media.test.ts b/packages/core/src/runtime/media.test.tsindex d6a2d46c3c..7ad12fc255 100644--- a/packages/core/src/runtime/media.test.ts+++ b/packages/core/src/runtime/media.test.ts@@ -42,12 +42,12 @@ describe("readElementPlaybackRate", () => {expect(readElementPlaybackRate(el)).toBe(1);});- it("clamps to [0.1, 5]", () => {+ it("clamps to [0.1, 10]", () => {const el = document.createElement("video");Object.defineProperty(el, "defaultPlaybackRate", { value: 0.01, writable: true });expect(readElementPlaybackRate(el)).toBe(0.1);- Object.defineProperty(el, "defaultPlaybackRate", { value: 10, writable: true });- expect(readElementPlaybackRate(el)).toBe(5);+ Object.defineProperty(el, "defaultPlaybackRate", { value: 20, writable: true });+ expect(readElementPlaybackRate(el)).toBe(10);});it("defaults to 1 for NaN/negative/zero", () => {@@ -165,16 +165,16 @@ describe("refreshRuntimeMediaCache", () => {expect(result.mediaClips[0].playbackRate).toBe(1);});- it("clamps playback rate to [0.1, 5]", () => {+ it("clamps playback rate to [0.1, 10]", () => {const el1 = createVideo({ "data-start": "0", "data-duration": "5" });Object.defineProperty(el1, "defaultPlaybackRate", { value: 0.01, writable: true });const r1 = refreshRuntimeMediaCache();expect(r1.mediaClips[0].playbackRate).toBe(0.1);document.body.innerHTML = "";const el2 = createVideo({ "data-start": "0", "data-duration": "5" });- Object.defineProperty(el2, "defaultPlaybackRate", { value: 10, writable: true });+ Object.defineProperty(el2, "defaultPlaybackRate", { value: 20, writable: true });const r2 = refreshRuntimeMediaCache();- expect(r2.mediaClips[0].playbackRate).toBe(5);+ expect(r2.mediaClips[0].playbackRate).toBe(10);});it("adjusts fallback duration by playback rate", () => {@@ -365,6 +365,25 @@ describe("syncRuntimeMedia", () => {document.body.innerHTML = "";});+ describe("speed ramp", () => {+ it("seeks to the integrated source time and plays at the instantaneous rate", () => {+ const rate = {+ target: "rate",+ points: [+ { t: 0, v: 1 },+ { t: 2, v: 3 },+ ],+ };+ const clip = createMockClip({ start: 1, end: 5, rate });+ Object.defineProperty(clip.el, "readyState", { value: 4, writable: true });+ syncRuntimeMedia({ clips: [clip], timeSeconds: 3, playing: false, playbackRate: 1 });+ expect(clip.el.currentTime).toBeCloseTo(3.641, 2);+ syncRuntimeMedia({ clips: [clip], timeSeconds: 3, playing: true, playbackRate: 1 });+ expect(clip.el.playbackRate).toBeCloseTo(3, 5);+ expect(clip.el.preservesPitch).toBe(true);+ });+ });+describe("volume automation lane", () => {const DUCK = JSON.stringify({version: 1,diff --git a/packages/core/src/runtime/media.ts b/packages/core/src/runtime/media.tsindex abb774a139..d535000c89 100644--- a/packages/core/src/runtime/media.ts+++ b/packages/core/src/runtime/media.ts@@ -1,11 +1,22 @@import { swallow } from "./diagnostics";import { interpolateVolumeGain, type VolumeKeyframe } from "./mediaVolumeEnvelope.js";import { elementVolumeLaneGain } from "./audioAutomationVolume.js";-import { readElementPlaybackRate, readMediaStart } from "./playbackRate.js";+import { readElementPlaybackRate, readElementRateSpec, readMediaStart } from "./playbackRate.js";+import {+ rateAt,+ readPreservePitch,+ sourceTimeAt,+ timeAtSourceTime,+ type RateSpec,+} from "../speedRamp.js";import { clampAudioGain } from "../audioGain.js";import { isMemberGroupHidden } from "../audioGroups.js";import { findInjectedRenderFrame } from "./renderFrameSibling.js";-export { readElementPlaybackRate, resolveNaturalMediaTimelineDuration } from "./playbackRate.js";+export {+ readElementPlaybackRate,+ readElementRateSpec,+ resolveNaturalMediaTimelineDuration,+} from "./playbackRate.js";export function readElementPlaybackStart(el: Element): number {return readMediaStart(el);@@ -43,6 +54,8 @@ export type RuntimeMediaClip = {end: number;volume: number | null;playbackRate: number;+ /** The rate lane when the clip has one; otherwise `playbackRate`. */+ rate?: RateSpec;loop: boolean;/** Source media duration in seconds (from el.duration). Used for loop wrapping. */sourceDuration: number | null;@@ -94,6 +107,7 @@ export function refreshRuntimeMediaCache(params?: {if (!Number.isFinite(start)) continue;const mediaStart = readElementPlaybackStart(el);const playbackRate = readElementPlaybackRate(el);+ const rate = readElementRateSpec(el);const loop = el.loop;const sourceDuration = Number.isFinite(el.duration) && el.duration > 0 ? el.duration : null;let duration =@@ -101,7 +115,7 @@ export function refreshRuntimeMediaCache(params?: {if ((!Number.isFinite(duration) || duration < 0) && sourceDuration != null) {// Effective duration accounts for playback rate:// at 0.5x, a 10s source plays for 20s on the timeline- duration = Math.max(0, (sourceDuration - mediaStart) / playbackRate);+ duration = Math.max(0, timeAtSourceTime(rate, sourceDuration - mediaStart));}const hasKnownDuration = Number.isFinite(duration) && duration >= 0;const end = hasKnownDuration ? start + duration : Number.POSITIVE_INFINITY;@@ -114,6 +128,7 @@ export function refreshRuntimeMediaCache(params?: {end,volume: Number.isFinite(volumeRaw) ? volumeRaw : null,playbackRate,+ rate,loop,sourceDuration,};@@ -243,7 +258,8 @@ export function syncRuntimeMedia(params: {for (const clip of params.clips) {const { el } = clip;if (!el.isConnected) continue;- let relTime = (params.timeSeconds - clip.start) * clip.playbackRate + clip.mediaStart;+ const clipRate = clip.rate ?? clip.playbackRate;+ let relTime = sourceTimeAt(clipRate, params.timeSeconds - clip.start) + clip.mediaStart;const isNonLoopVideo = el.tagName === "VIDEO" && !clip.loop;const isHeldVideoTail =isNonLoopVideo &&@@ -369,7 +385,8 @@ export function syncRuntimeMedia(params: {if (el.preload !== "auto") el.preload = "auto";try {// Per-element rate × global transport rate- el.playbackRate = clip.playbackRate * params.playbackRate;+ el.playbackRate = rateAt(clipRate, params.timeSeconds - clip.start) * params.playbackRate;+ el.preservesPitch = readPreservePitch(el);} catch (err) {// ignore unsupported playbackRateswallow("runtime.media.site1", err);diff --git a/packages/core/src/runtime/playbackRate.test.ts b/packages/core/src/runtime/playbackRate.test.tsindex 8daf2d43a6..71f2613f31 100644--- a/packages/core/src/runtime/playbackRate.test.ts+++ b/packages/core/src/runtime/playbackRate.test.ts@@ -1,5 +1,8 @@import { describe, expect, it } from "vitest";-import { resolveNaturalMediaTimelineDuration } from "./playbackRate";+import {+ resolveNaturalMediaTimelineDuration,+ resolveNaturalMediaTimelineDurationFromValues,+} from "./playbackRate";function elementWith(attributes: Record<string, string>): Pick<Element, "getAttribute"> {return {@@ -29,3 +32,23 @@ describe("resolveNaturalMediaTimelineDuration", () => {expect(resolveNaturalMediaTimelineDuration(elementWith({}), Number.NaN)).toBeNull();});});++describe("rate lane duration", () => {+ it("resolves natural media duration through the lane", () => {+ const lane = {+ target: "rate",+ points: [+ { t: 0, v: 1 },+ { t: 2, v: 3 },+ ],+ };+ expect(resolveNaturalMediaTimelineDurationFromValues(4, 0, lane)).toBeCloseTo(+ 2 + (4 - 3.641) / 3,+ 2,+ );+ expect(resolveNaturalMediaTimelineDurationFromValues(10, 0, lane)).toBeCloseTo(+ 2 + (10 - 3.641) / 3,+ 2,+ );+ });+});diff --git a/packages/core/src/runtime/playbackRate.ts b/packages/core/src/runtime/playbackRate.tsindex 7af919a2c1..82df1e9cc6 100644--- a/packages/core/src/runtime/playbackRate.ts+++ b/packages/core/src/runtime/playbackRate.ts@@ -1,7 +1,11 @@+import { MAX_PLAYBACK_RATE, MIN_PLAYBACK_RATE } from "../playbackRateBounds";+import { resolveRateSpec, timeAtSourceTime, type RateSpec } from "../speedRamp";import { isMediaElement } from "./domRealm";export function normalizePlaybackRate(raw: number): number {- return Number.isFinite(raw) && raw > 0 ? Math.max(0.1, Math.min(5, raw)) : 1;+ return Number.isFinite(raw) && raw > 0+ ? Math.max(MIN_PLAYBACK_RATE, Math.min(MAX_PLAYBACK_RATE, raw))+ : 1;}/** Parse a literal numeric timing attribute without accepting trailing units or garbage. */@@ -20,6 +24,11 @@ export function readElementPlaybackRate(el: Pick<Element, "getAttribute">): numbreturn normalizePlaybackRate(raw);}+/** The clip's rate: its `rate` lane when present, otherwise the constant rate. */+export function readElementRateSpec(el: Pick<Element, "getAttribute">): RateSpec {+ return resolveRateSpec(el.getAttribute("data-automation"), readElementPlaybackRate(el));+}+export function readMediaStart(el: Pick<Element, "getAttribute">): number {const parse = (raw: string | null): number | null => {const value = parseStrictFiniteTimingNumber(raw);@@ -37,7 +46,7 @@ export function resolveNaturalMediaTimelineDuration(return resolveNaturalMediaTimelineDurationFromValues(sourceDuration,readMediaStart(el),- readElementPlaybackRate(el),+ readElementRateSpec(el),);}@@ -61,10 +70,13 @@ export function resolveMediaElementDurationSeconds(export function resolveNaturalMediaTimelineDurationFromValues(sourceDuration: number,mediaStart: number,- playbackRate: number,+ playbackRate: RateSpec,): number | null {if (!Number.isFinite(sourceDuration)) return null;const remaining = Math.max(0, sourceDuration - mediaStart);- return remaining / normalizePlaybackRate(playbackRate);+ return timeAtSourceTime(+ typeof playbackRate === "number" ? normalizePlaybackRate(playbackRate) : playbackRate,+ remaining,+ );}import { parseNumeric } from "./startExpression";diff --git a/packages/core/src/runtime/startResolver.ts b/packages/core/src/runtime/startResolver.tsindex fafbf191ac..d2b3b0c744 100644--- a/packages/core/src/runtime/startResolver.ts+++ b/packages/core/src/runtime/startResolver.ts@@ -6,8 +6,9 @@ import { resolveAuthoredTimingWindow } from "./authoredTiming";// would be an import cycle.import {parseStrictFiniteTimingNumber,- readElementPlaybackRate,+ readElementRateSpec,readMediaStart,+ resolveNaturalMediaTimelineDurationFromValues,} from "./playbackRate";import { isMediaElement } from "./domRealm";import { parseStartExpression } from "./startExpression";@@ -73,7 +74,12 @@ export function createRuntimeStartTimeResolver(params: {if ((resolved == null || resolved <= 0) && isMediaElement(element)) {const playbackStart = readMediaStart(element);if (Number.isFinite(element.duration) && element.duration > playbackStart) {- resolved = (element.duration - playbackStart) / readElementPlaybackRate(element);+ resolved =+ resolveNaturalMediaTimelineDurationFromValues(+ element.duration,+ playbackStart,+ readElementRateSpec(element),+ ) ?? 0;}}if (resolved == null || resolved <= 0) {diff --git a/packages/core/src/runtime/timeline.test.ts b/packages/core/src/runtime/timeline.test.tsindex 3eeb95069c..4cdd1372d7 100644--- a/packages/core/src/runtime/timeline.test.ts+++ b/packages/core/src/runtime/timeline.test.ts@@ -369,7 +369,7 @@ describe("collectRuntimeTimelinePayload", () => {[0, 2, 5],[2, 2, 4],[2, 0.01, 80],- [2, 20, 1.6],+ [2, 20, 0.8],[0, "2x", 5],[0, "0x2", 10],])("rate-scales natural media duration (start=%s rate=%s)", (mediaStart, rate, expected) => {diff --git a/packages/core/src/speedRamp.test.ts b/packages/core/src/speedRamp.test.tsnew file mode 100644index 0000000000..b25e9be07c--- /dev/null+++ b/packages/core/src/speedRamp.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from "vitest";+import { RATE_TARGET, type HfAutomationLane } from "./audioAutomation.js";+import {+ SPEED_PRESETS,+ parseRateLane,+ rateAt,+ readPreservePitch,+ resolveRateSpec,+ sourceTimeAt,+ speedPresetLane,+ timeAtSourceTime,+} from "./speedRamp.js";++const ramp = (points: Array<[number, number]>): HfAutomationLane => ({+ target: RATE_TARGET,+ points: points.map(([t, v]) => ({ t, v })),+});++describe("sourceTimeAt", () => {+ it("is t * rate for a constant", () => {+ expect(sourceTimeAt(2, 3)).toBe(6);+ });++ it("integrates a geometric 1x to 3x ramp: 2s * (3-1)/ln 3 source seconds", () => {+ expect(+ sourceTimeAt(+ ramp([+ [0, 1],+ [2, 3],+ ]),+ 2,+ ),+ ).toBeCloseTo(3.641, 3);+ });++ it("holds the last rate past the final point", () => {+ expect(+ sourceTimeAt(+ ramp([+ [0, 1],+ [2, 3],+ ]),+ 4,+ ),+ ).toBeCloseTo(3.641 + 2 * 3, 3);+ });++ it("round-trips through timeAtSourceTime", () => {+ const lane = ramp([+ [0, 0.5],+ [1, 4],+ [3, 0.25],+ ]);+ for (const t of [0, 0.4, 1, 2.2, 3, 5]) {+ expect(timeAtSourceTime(lane, sourceTimeAt(lane, t))).toBeCloseTo(t, 3);+ }+ });+});++describe("rateAt", () => {+ it("interpolates geometrically: the midpoint of 1x to 3x is sqrt(3)", () => {+ expect(+ rateAt(+ ramp([+ [0, 1],+ [2, 3],+ ]),+ 1,+ ),+ ).toBeCloseTo(Math.sqrt(3), 5);+ });+});++describe("lane parsing", () => {+ const attr = JSON.stringify({+ version: 1,+ lanes: [{ target: "rate", points: [{ t: 0, v: 20 }] }],+ });++ it("clamps a stored rate to the shared 0.1..10 range", () => {+ expect(rateAt(resolveRateSpec(attr, 1), 0)).toBe(10);+ });++ it("falls back to the constant when the attribute is absent or unreadable", () => {+ expect(resolveRateSpec(null, 1.5)).toBe(1.5);+ expect(resolveRateSpec("{nope", 2)).toBe(2);+ expect(parseRateLane("{nope")).toBeNull();+ });+});++describe("presets and pitch", () => {+ it("stretches every preset over the clip and keeps it in range", () => {+ for (const { id } of SPEED_PRESETS) {+ const lane = speedPresetLane(id, 8);+ expect(lane.points[lane.points.length - 1]!.t).toBe(8);+ for (const p of lane.points) expect(p.v).toBeGreaterThanOrEqual(0.1);+ }+ });++ it("preserves pitch unless the clip opts out", () => {+ const el = (v: string | null) => ({ getAttribute: () => v });+ expect(readPreservePitch(el(null))).toBe(true);+ expect(readPreservePitch(el("false"))).toBe(false);+ });+});diff --git a/packages/core/src/speedRamp.ts b/packages/core/src/speedRamp.tsnew file mode 100644index 0000000000..a9b684a915--- /dev/null+++ b/packages/core/src/speedRamp.ts@@ -0,0 +1,209 @@+/** A ramp is a `rate` lane in `data-automation`; `sourceTimeAt` is the one rate-to-time mapping consumers share. */++import { RATE_TARGET, sampleAutomationLane, type HfAutomationLane } from "./audioAutomation.js";+import { laneFromAttr } from "./runtime/audioAutomationVolume.js";+import { MAX_PLAYBACK_RATE, MIN_PLAYBACK_RATE } from "./playbackRateBounds.js";++/** A constant multiplier, or a lane whose `v` is the multiplier over clip-local time. */+export type RateSpec = number | HfAutomationLane;++const PRESERVE_PITCH_ATTR = "data-preserve-pitch";++const CELLS_PER_SEGMENT = 48;++interface RateTable {+ /** Ascending clip-local times and the source seconds consumed by each. */+ ts: Float64Array;+ ss: Float64Array;+ firstRate: number;+ lastRate: number;+}++const tables = new WeakMap<HfAutomationLane, RateTable>();++function buildTable(lane: HfAutomationLane): RateTable {+ const pts = lane.points;+ const firstRate = pts[0]!.v;+ const lastRate = pts[pts.length - 1]!.v;+ const ts: number[] = [0];+ const ss: number[] = [0];+ const push = (t: number) => {+ const prevT = ts[ts.length - 1]!;+ if (t <= prevT) return;+ const prevRate = sampleAutomationLane(lane, prevT, "log");+ ts.push(t);+ ss.push(+ ss[ss.length - 1]! + ((prevRate + sampleAutomationLane(lane, t, "log")) / 2) * (t - prevT),+ );+ };+ const first = Math.max(0, pts[0]!.t);+ push(first);+ for (let i = 1; i < pts.length; i += 1) {+ const a = pts[i - 1]!.t;+ const b = pts[i]!.t;+ if (b <= 0) continue;+ for (let k = 1; k <= CELLS_PER_SEGMENT; k += 1)+ push(Math.max(a, 0) + ((b - a) * k) / CELLS_PER_SEGMENT);+ }+ return { ts: Float64Array.from(ts), ss: Float64Array.from(ss), firstRate, lastRate };+}++function tableFor(lane: HfAutomationLane): RateTable {+ let table = tables.get(lane);+ if (!table) {+ table = buildTable(lane);+ tables.set(lane, table);+ }+ return table;+}++function usable(spec: RateSpec): spec is HfAutomationLane {+ return typeof spec !== "number" && spec.points.length > 0;+}++/** Speed multiplier at clip-local time `t`. */+export function rateAt(spec: RateSpec, t: number): number {+ if (typeof spec === "number") return spec;+ return usable(spec) ? sampleAutomationLane(spec, t, "log") : 1;+}++/** Piecewise-linear lookup of `x` in the ascending `xs`, read off `ys`; caller keeps `x` inside `xs`. */+function interpolate(xs: Float64Array, ys: Float64Array, x: number): number {+ let lo = 0;+ let hi = xs.length - 1;+ while (hi - lo > 1) {+ const mid = (lo + hi) >> 1;+ if (xs[mid]! <= x) lo = mid;+ else hi = mid;+ }+ return ys[lo]! + ((ys[hi]! - ys[lo]!) * (x - xs[lo]!)) / (xs[hi]! - xs[lo]!);+}++/** Source seconds consumed by clip-local time `t` (the integral of the rate). */+export function sourceTimeAt(spec: RateSpec, t: number): number {+ if (typeof spec === "number") return t * spec;+ if (!usable(spec)) return t;+ const { ts, ss, firstRate, lastRate } = tableFor(spec);+ const last = ts.length - 1;+ if (t <= 0) return t * firstRate;+ if (t >= ts[last]!) return ss[last]! + (t - ts[last]!) * lastRate;+ return interpolate(ts, ss, t);+}++/** Inverse of `sourceTimeAt`: the clip-local time at which `source` seconds have been consumed. */+export function timeAtSourceTime(spec: RateSpec, source: number): number {+ if (typeof spec === "number") return source / spec;+ if (!usable(spec)) return source;+ const { ts, ss, firstRate, lastRate } = tableFor(spec);+ const last = ts.length - 1;+ if (source <= 0) return source / firstRate;+ if (source >= ss[last]!) return ts[last]! + (source - ss[last]!) / lastRate;+ return interpolate(ss, ts, source);+}++/** The `rate` lane inside a `data-automation` attribute value, or null when absent or unreadable. */+export function parseRateLane(raw: string | null | undefined): HfAutomationLane | null {+ return raw ? laneFromAttr(raw, RATE_TARGET) : null;+}++/** A clip's rate: its `rate` lane when it has one, otherwise the constant. */+export function resolveRateSpec(+ automationAttr: string | null | undefined,+ constant: number,+): RateSpec {+ return parseRateLane(automationAttr) ?? constant;+}++/** Pitch is preserved unless the clip opts out with `data-preserve-pitch="false"`. */+export function readPreservePitch(el: Pick<Element, "getAttribute">): boolean {+ return el.getAttribute(PRESERVE_PITCH_ATTR) !== "false";+}++interface RatePreset {+ id: string;+ label: string;+ /** Points as [progress 0..1 through the clip, speed]. */+ points: ReadonlyArray<readonly [number, number]>;+}++/** The CapCut-style presets; `speedPresetLane` stretches one over a clip's duration. */+export const SPEED_PRESETS = [+ {+ id: "montage",+ label: "Montage",+ points: [+ [0, 0.9],+ [0.15, 0.3],+ [0.5, 2.5],+ [0.85, 0.3],+ [1, 0.9],+ ],+ },+ {+ id: "hero",+ label: "Hero",+ points: [+ [0, 1],+ [0.25, 1.6],+ [0.5, 0.25],+ [0.75, 1.6],+ [1, 1],+ ],+ },+ {+ id: "bullet",+ label: "Bullet",+ points: [+ [0, 3],+ [0.4, 3],+ [0.5, 0.15],+ [0.6, 3],+ [1, 3],+ ],+ },+ {+ id: "jump-cut",+ label: "Jump cut",+ points: [+ [0, 0.5],+ [0.24, 0.5],+ [0.26, 3],+ [0.5, 3],+ [0.52, 0.5],+ [0.74, 0.5],+ [0.76, 3],+ [1, 3],+ ],+ },+ {+ id: "flash-in",+ label: "Flash in",+ points: [+ [0, 0.3],+ [0.6, 0.6],+ [1, 5],+ ],+ },+ {+ id: "flash-out",+ label: "Flash out",+ points: [+ [0, 5],+ [0.4, 0.6],+ [1, 0.3],+ ],+ },+] as const satisfies readonly RatePreset[];++export type SpeedPresetId = (typeof SPEED_PRESETS)[number]["id"];++export function speedPresetLane(id: SpeedPresetId, clipDuration: number): HfAutomationLane {+ const preset = SPEED_PRESETS.find((p) => p.id === id)!;+ return {+ target: RATE_TARGET,+ points: preset.points.map(([x, v]) => ({+ t: x * clipDuration,+ v: Math.min(MAX_PLAYBACK_RATE, Math.max(MIN_PLAYBACK_RATE, v)),+ })),+ };+}diff --git a/packages/engine/src/services/audioMixer.test.ts b/packages/engine/src/services/audioMixer.test.tsindex e7b1fb5ac7..6837d35972 100644--- a/packages/engine/src/services/audioMixer.test.ts+++ b/packages/engine/src/services/audioMixer.test.ts@@ -65,6 +65,7 @@ vi.mock("../utils/ffprobe.js", async (importOriginal) => {return { ...actual, extractAudioMetadata: extractAudioMetadataMock };});+import { RATE_RANGE } from "@hyperframes/core/audio-automation";import { parseAudioElements, processCompositionAudio } from "./audioMixer.js";describe("parseAudioElements strict literal timing", () => {@@ -1395,8 +1396,8 @@ describe("parseAudioElements — relative data-start resolution", () => {const tracks = parseAudioElements(html);expect(tracks.find((track) => track.id === "fast")?.playbackRate).toBe(2);- expect(tracks.find((track) => track.id === "low")?.playbackRate).toBe(0.1);- expect(tracks.find((track) => track.id === "high")?.playbackRate).toBe(5);+ expect(tracks.find((track) => track.id === "low")?.playbackRate).toBe(RATE_RANGE.min);+ expect(tracks.find((track) => track.id === "high")?.playbackRate).toBe(RATE_RANGE.max);expect(tracks.find((track) => track.id === "invalid")?.playbackRate).toBe(1);});diff --git a/packages/engine/src/services/videoFrameExtractor.test.ts b/packages/engine/src/services/videoFrameExtractor.test.tsindex f1e023f02e..6e9408696e 100644--- a/packages/engine/src/services/videoFrameExtractor.test.ts+++ b/packages/engine/src/services/videoFrameExtractor.test.ts@@ -58,6 +58,7 @@ import { runFfmpeg } from "../utils/runFfmpeg.js";import { COMPLETE_SENTINEL, GC_MARKER, SCHEMA_PREFIX } from "./extractionCache.js";import { resolveRuntimeMediaClipDuration } from "../../../core/src/runtime/media.js";import { compileTimingAttrs } from "@hyperframes/core";+import { RATE_RANGE } from "@hyperframes/core/audio-automation";// ffmpeg is not preinstalled on GitHub's ubuntu-24.04 runners. The producer// regression test at packages/producer/tests/vfr-screen-recording/ runs inside@@ -771,8 +772,8 @@ describe("parseVideoElements", () => {);expect(fast?.playbackRate).toBe(2);- expect(low?.playbackRate).toBe(0.1);- expect(high?.playbackRate).toBe(5);+ expect(low?.playbackRate).toBe(RATE_RANGE.min);+ expect(high?.playbackRate).toBe(RATE_RANGE.max);expect(invalid?.playbackRate).toBe(1);});diff --git a/packages/lint/src/rules/media.test.ts b/packages/lint/src/rules/media.test.tsindex 52bc93812a..6d27a56043 100644--- a/packages/lint/src/rules/media.test.ts+++ b/packages/lint/src/rules/media.test.ts@@ -1011,3 +1011,21 @@ describe("media_src_kind_mismatch", () => {expect(result.findings.find((f) => f.code === "media_src_kind_mismatch")).toBeUndefined();});});++describe("speed_ramp_on_non_media", () => {+ const RATE = `data-automation='{"version":1,"lanes":[{"target":"rate","points":[{"t":0,"v":1},{"t":2,"v":3}]}]}'`;+ const page = (tag: string) => `<!DOCTYPE html><html><body>+ <div id="root" data-composition-id="main" data-start="0" data-width="1920" data-height="1080" data-duration="10">${tag}</div>+ </body></html>`;++ it("warns on a rate lane outside video and audio, and stays quiet on a clip", async () => {+ const bad = await lintHyperframeHtml(+ page(`<img id="pic" src="a.png" data-start="0" data-duration="4" ${RATE}>`),+ );+ const good = await lintHyperframeHtml(+ page(`<video id="v" src="a.mp4" data-start="0" data-duration="4" ${RATE}></video>`),+ );+ expect(bad.findings.find((f) => f.code === "speed_ramp_on_non_media")?.elementId).toBe("pic");+ expect(good.findings.some((f) => f.code === "speed_ramp_on_non_media")).toBe(false);+ });+});diff --git a/packages/lint/src/rules/media.ts b/packages/lint/src/rules/media.tsindex 592a4f8861..3e4bebd4b2 100644--- a/packages/lint/src/rules/media.ts+++ b/packages/lint/src/rules/media.ts@@ -400,6 +400,7 @@ function findRuntimeMediaSrcMutationFindings(ctx: LintContext): HyperframeLintFiexport const mediaRules: Array<(ctx: LintContext) => HyperframeLintFinding[]> = [findNestedMediaStartBasisFindings,+ findSpeedRampOnNonMediaFindings,// duplicate_media_id + duplicate_media_discovery_risk({ tags }) => {const findings: HyperframeLintFinding[] = [];@@ -913,6 +914,24 @@ function findVolumeDoubleAutomationFindings(ctx: LintContext): HyperframeLintFinreturn findings;}+/** A `rate` lane only retimes video and audio; anywhere else it is silently inert. */+function findSpeedRampOnNonMediaFindings(ctx: LintContext): HyperframeLintFinding[] {+ return ctx.tags+ .filter((tag) => tag.name !== "video" && tag.name !== "audio")+ .filter((tag) =>+ /"target"\s*:\s*"rate"/.test(readDecodedAttr(tag.raw, "data-automation") ?? ""),+ )+ .map((tag) => ({+ code: "speed_ramp_on_non_media",+ severity: "warning",+ message: `<${tag.name}> has a speed-ramp lane, but only <video> and <audio> clips can be retimed. The lane does nothing here.`,+ elementId: readAttr(tag.raw, "id") || undefined,+ fixHint:+ "Move the rate lane onto the <video> or <audio> clip, or retime an animation with a GSAP timeline instead.",+ snippet: truncateSnippet(tag.raw),+ }));+}+/*** A carve's `sources` naming two or more plain clip ids is the normative* mistake groups exist to prevent (groups doc §1.6): the list silently rotsdiff --git a/packages/studio/src/components/editor/audioFxRevealTarget.ts b/packages/studio/src/components/editor/audioFxRevealTarget.tsindex 764d7bf56f..a2625a114a 100644--- a/packages/studio/src/components/editor/audioFxRevealTarget.ts+++ b/packages/studio/src/components/editor/audioFxRevealTarget.ts@@ -37,6 +37,7 @@ export function audioFxRevealTarget(const parsed = parseAutomationTarget(target);if (!parsed) return null;if (parsed.kind === "volume") return { kind: "volume" };+ if (parsed.kind === "rate") return null;if (parsed.kind === "preset") {// A preset-level lane names the preset, not a node inside it: find its run// by the first node that belongs to it, which is how `runKey` is built.