Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

feat: raise playback-speed cap to 100x

my_mac27363e70f234
diff --git a/src/components/video-editor/SettingsPanel.tsx b/src/components/video-editor/SettingsPanel.tsx
index 5e0cc8062..282a295fd 100644
--- a/src/components/video-editor/SettingsPanel.tsx
+++ b/src/components/video-editor/SettingsPanel.tsx
@@ -89,6 +89,8 @@ import type {
import {
DEFAULT_WEBCAM_MIRRORED,
DEFAULT_WEBCAM_REACTIVE_ZOOM,
+ MAX_NATIVE_PLAYBACK_RATE,
+ MAX_PLAYBACK_SPEED,
MAX_ZOOM_SCALE,
MIN_ZOOM_SCALE,
ROTATION_3D_PRESET_ORDER,
@@ -1214,7 +1216,9 @@ export function SettingsPanel({
<CustomSpeedInput
value={selectedSpeedValue ?? 1}
onChange={(val) => onSpeedChange?.(val)}
- onError={() => toast.error(t("speed.maxSpeedError"))}
+ onError={() =>
+ toast.error(t("speed.maxSpeedError", { max: MAX_PLAYBACK_SPEED }))
+ }
/>
) : (
<div className="flex items-center gap-1 opacity-40">
@@ -1225,6 +1229,13 @@ export function SettingsPanel({
</div>
)}
</div>
+ {selectedSpeedId &&
+ selectedSpeedValue != null &&
+ selectedSpeedValue > MAX_NATIVE_PLAYBACK_RATE && (
+ <p className="px-1 text-[10px] leading-snug text-slate-500">
+ {t("speed.previewFrameSteppingHint", { native: MAX_NATIVE_PLAYBACK_RATE })}
+ </p>
+ )}
{selectedSpeedId && (
<Button
onClick={() => selectedSpeedId && onSpeedDelete?.(selectedSpeedId)}
diff --git a/src/components/video-editor/VideoPlayback.tsx b/src/components/video-editor/VideoPlayback.tsx
index 1b4ad5263..31b8fa89f 100644
--- a/src/components/video-editor/VideoPlayback.tsx
+++ b/src/components/video-editor/VideoPlayback.tsx
@@ -62,6 +62,7 @@ import {
getZoomScale,
isRotation3DIdentity,
lerpRotation3D,
+ MAX_NATIVE_PLAYBACK_RATE,
rotation3DPerspective,
type SpeedRegion,
type TrimRegion,
@@ -336,6 +337,11 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(
const scrubEndTimerRef = useRef<number | null>(null);
const [isScrubbing, setIsScrubbing] = useState(false);
const allowPlaybackRef = useRef(false);
+ // Seek-stepping state for speed regions above the native playbackRate cap (16×).
+ const seekSteppingRef = useRef(false);
+ const stepVirtualSecRef = useRef(0);
+ const stepLastTsRef = useRef(0);
+ const stepPrevMutedRef = useRef(false);
const lockedVideoDimensionsRef = useRef<{
width: number;
height: number;
@@ -630,7 +636,9 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(
const supplementalAudio = supplementalAudioRef.current;
if (supplementalAudio) {
supplementalAudio.currentTime = vid.currentTime;
- supplementalAudio.playbackRate = vid.playbackRate;
+ // vid.playbackRate is already capped at the native ceiling; clamp
+ // defensively so the supplemental track never throws either.
+ supplementalAudio.playbackRate = Math.min(vid.playbackRate, MAX_NATIVE_PLAYBACK_RATE);
await supplementalAudio.play().catch(() => {
// The main video remains the source of truth for playback state.
});
@@ -1136,7 +1144,16 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(
speedRegions.find(
(region) => currentTime * 1000 >= region.startMs && currentTime * 1000 < region.endMs,
) ?? null;
- supplementalAudio.playbackRate = activeSpeedRegion ? activeSpeedRegion.speed : 1;
+ const activeSpeed = activeSpeedRegion ? activeSpeedRegion.speed : 1;
+
+ // Above the native rate the main preview frame-steps silently; a media
+ // element can't play that fast (setting playbackRate > 16 throws), so mute
+ // the supplemental track by pausing it for the duration of the region.
+ if (activeSpeed > MAX_NATIVE_PLAYBACK_RATE) {
+ supplementalAudio.pause();
+ return;
+ }
+ supplementalAudio.playbackRate = activeSpeed;
if (!isPlaying) {
supplementalAudio.pause();
@@ -1227,6 +1244,10 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(
isScrubbingRef,
scrubEndTimerRef,
onScrubChange: (scrubbing) => setIsScrubbing(scrubbing),
+ seekSteppingRef,
+ stepVirtualSecRef,
+ stepLastTsRef,
+ stepPrevMutedRef,
});
video.addEventListener("play", handlePlay);
@@ -1826,7 +1847,13 @@ const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(
speedRegions.find(
(region) => currentTime * 1000 >= region.startMs && currentTime * 1000 < region.endMs,
) ?? null;
- webcamVideo.playbackRate = activeSpeedRegion ? activeSpeedRegion.speed : 1;
+ // Cap the (silent) webcam element at the native rate so playbackRate never
+ // throws; the per-frame currentTime resync below keeps it aligned with the
+ // stepped playhead in >16× regions.
+ webcamVideo.playbackRate = Math.min(
+ activeSpeedRegion ? activeSpeedRegion.speed : 1,
+ MAX_NATIVE_PLAYBACK_RATE,
+ );
if (!isPlaying) {
webcamVideo.pause();
diff --git a/src/components/video-editor/customPlaybackSpeed.test.ts b/src/components/video-editor/customPlaybackSpeed.test.ts
index 223175cfe..aaffb2b5a 100644
--- a/src/components/video-editor/customPlaybackSpeed.test.ts
+++ b/src/components/video-editor/customPlaybackSpeed.test.ts
@@ -41,10 +41,27 @@ describe("parseCustomPlaybackSpeedInput", () => {
});
});
- it("rejects speeds above the editor maximum", () => {
+ it("accepts the maximum editor speed", () => {
+ expect(parseCustomPlaybackSpeedInput("100")).toEqual({
+ status: "valid",
+ draft: "100",
+ speed: 100,
+ });
+ });
+
+ it("accepts high speeds that exceed the native preview rate", () => {
+ // 16.1× was rejected under the old 16× cap; it must now be valid.
expect(parseCustomPlaybackSpeedInput("16.1")).toEqual({
- status: "too-fast",
+ status: "valid",
draft: "16.1",
+ speed: 16.1,
+ });
+ });
+
+ it("rejects speeds above the editor maximum", () => {
+ expect(parseCustomPlaybackSpeedInput("100.1")).toEqual({
+ status: "too-fast",
+ draft: "100.1",
});
});
});
diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.ts
index 93ae00237..4406ee961 100644
--- a/src/components/video-editor/types.ts
+++ b/src/components/video-editor/types.ts
@@ -368,8 +368,11 @@ export const DEFAULT_CROP_REGION: CropRegion = {
export type PlaybackSpeed = number;
export const MIN_PLAYBACK_SPEED = 0.1;
-// Above 16x the decoder can't keep up and the playhead stalls during preview.
-export const MAX_PLAYBACK_SPEED = 16;
+export const MAX_PLAYBACK_SPEED = 100;
+// Chromium hard-caps HTMLMediaElement.playbackRate at 16 (setting more throws
+// NotSupportedError). At or below this, preview plays natively; above it, preview
+// frame-steps by seeking and audio export uses an offline pitch-preserved stretch.
+export const MAX_NATIVE_PLAYBACK_RATE = 16;
export function clampPlaybackSpeed(speed: number): PlaybackSpeed {
return Math.round(Math.min(MAX_PLAYBACK_SPEED, Math.max(MIN_PLAYBACK_SPEED, speed)) * 100) / 100;
diff --git a/src/components/video-editor/videoPlayback/videoEventHandlers.ts b/src/components/video-editor/videoPlayback/videoEventHandlers.ts
index 3b26aa812..6d03e7692 100644
--- a/src/components/video-editor/videoPlayback/videoEventHandlers.ts
+++ b/src/components/video-editor/videoPlayback/videoEventHandlers.ts
@@ -1,9 +1,20 @@
import type React from "react";
-import type { SpeedRegion, TrimRegion } from "../types";
+import { MAX_NATIVE_PLAYBACK_RATE, type SpeedRegion, type TrimRegion } from "../types";
// Keep "scrub mode" on for a brief tail after `seeked`: rapid drag-scrubbing fires
// `seeking`/`seeked` dozens of times a second and toggling effects each time would flicker.
const SCRUB_END_DEBOUNCE_MS = 150;
+// When seek-stepping crosses a speed region's end, land this far past it so the next
+// frame's `currentTimeMs < endMs` check exits the region. A plain clamp to endMs/1000
+// can stall: (endMs/1000)*1000 may read back below endMs. 0.5 ms is imperceptible and
+// dominates any floating-point round-trip error.
+const REGION_EXIT_MARGIN_SEC = 0.0005;
+// Minimum forward distance (seconds) before seek-stepping issues a seek, so a no-op
+// seek to the element's current position never arms the in-flight throttle.
+const STEP_MIN_SEEK_SEC = 0.01;
+// Recover the throttle if a step seek never reports `seeked` (e.g. seeking past a
+// non-finite-duration source's buffered end) rather than freezing for the session.
+const STEP_SEEK_TIMEOUT_MS = 500;
interface VideoEventHandlersParams {
video: HTMLVideoElement;
@@ -19,6 +30,13 @@ interface VideoEventHandlersParams {
isScrubbingRef?: React.MutableRefObject<boolean>;
scrubEndTimerRef?: React.MutableRefObject<number | null>;
onScrubChange?: (scrubbing: boolean) => void;
+ // Seek-stepping state for speed regions above the native playbackRate cap (16×):
+ // the element can't play that fast, so the rAF loop advances a virtual clock and
+ // forward-seeks the muted element to it each frame.
+ seekSteppingRef: React.MutableRefObject<boolean>;
+ stepVirtualSecRef: React.MutableRefObject<number>;
+ stepLastTsRef: React.MutableRefObject<number>;
+ stepPrevMutedRef: React.MutableRefObject<boolean>;
}
export function createVideoEventHandlers(params: VideoEventHandlersParams) {
@@ -36,8 +54,22 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {
isScrubbingRef,
scrubEndTimerRef,
onScrubChange,
+ seekSteppingRef,
+ stepVirtualSecRef,
+ stepLastTsRef,
+ stepPrevMutedRef,
} = params;
+ // True while a seek-stepping forward seek is in flight (cleared by its `seeked`).
+ // Prevents issuing the next seek before the element has presented the current
+ // frame — seeking every rAF frame keeps a slow decoder perpetually mid-seek so
+ // the preview freezes. Local to the handler set (recreated when the video rewires).
+ let stepSeekInFlight = false;
+ let stepSeekIssuedAtMs = 0;
+ // One-shot: suppress scrub-mode for the internal catch-up seek issued when stepping
+ // hands back to native playback (that seek must not soften the preview / snap effects).
+ let suppressSeekScrubOnce = false;
+
const clearScrubEndTimer = () => {
if (scrubEndTimerRef && scrubEndTimerRef.current !== null) {
window.clearTimeout(scrubEndTimerRef.current);
@@ -67,10 +99,45 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {
);
};
- function updateTime() {
+ // Enter seek-stepping: mute the element, cap its rate to the native ceiling, and
+ // seed the virtual clock from the current position. The element keeps "playing"
+ // (paused would tear the rAF loop down) but every frame we override its time.
+ const beginSeekStepping = (fromSec: number, nowMs: number) => {
+ stepVirtualSecRef.current = fromSec;
+ stepLastTsRef.current = nowMs;
+ stepPrevMutedRef.current = video.muted;
+ video.muted = true;
+ // Clear any real/trim seek that was still pending when stepping began — our
+ // per-frame step-seeks are suppressed in handleSeeked, so its `seeked` would
+ // otherwise never run and isSeekingRef would strand true (blocking the next play).
+ isSeekingRef.current = false;
+ try {
+ video.playbackRate = MAX_NATIVE_PLAYBACK_RATE;
+ } catch {
+ /* some elements reject rate changes mid-seek; the forward seek still drives time */
+ }
+ stepSeekInFlight = false;
+ seekSteppingRef.current = true;
+ };
+
+ // Leave seek-stepping and restore the element's prior mute state so native
+ // playback (≤16×) resumes with sound.
+ const endSeekStepping = () => {
+ if (!seekSteppingRef.current) return;
+ seekSteppingRef.current = false;
+ video.muted = stepPrevMutedRef.current;
+ };
+
+ function updateTime(now?: number) {
if (!video) return;
- const currentTimeMs = video.currentTime * 1000;
+ const nowMs = now ?? performance.now();
+ // While stepping, the virtual clock — not the lagging element time — is the
+ // authority for which region is active and where the playhead sits.
+ const authoritativeSec = seekSteppingRef.current
+ ? stepVirtualSecRef.current
+ : video.currentTime;
+ const currentTimeMs = authoritativeSec * 1000;
const activeTrimRegion = findActiveTrimRegion(currentTimeMs);
// In a trim region during playback: skip to its end
@@ -79,15 +146,81 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {
// Pause if the skip would run past the end
if (skipToTime >= video.duration) {
+ endSeekStepping();
video.pause();
} else {
video.currentTime = skipToTime;
+ if (seekSteppingRef.current) {
+ stepVirtualSecRef.current = skipToTime;
+ stepLastTsRef.current = nowMs;
+ stepSeekInFlight = false;
+ }
emitTime(skipToTime);
}
} else {
const activeSpeedRegion = findActiveSpeedRegion(currentTimeMs);
- video.playbackRate = activeSpeedRegion ? activeSpeedRegion.speed : 1;
- emitTime(video.currentTime);
+ const speed = activeSpeedRegion ? activeSpeedRegion.speed : 1;
+
+ if (speed <= MAX_NATIVE_PLAYBACK_RATE) {
+ // Native path (unchanged for ≤16×): let the element play at `speed`.
+ if (seekSteppingRef.current) {
+ endSeekStepping();
+ // Snap the (possibly seek-lagged) element up to the virtual playhead so
+ // native playback resumes exactly where the playhead is, no backward jump.
+ // Flag it so the async seeking/seeked don't flip on scrub mode (which would
+ // soften the preview and snap effects for ~150ms at the boundary).
+ if (Math.abs(video.currentTime - stepVirtualSecRef.current) > STEP_MIN_SEEK_SEC) {
+ suppressSeekScrubOnce = true;
+ video.currentTime = stepVirtualSecRef.current;
+ }
+ }
+ video.playbackRate = speed;
+ emitTime(video.currentTime);
+ } else {
+ // Seek-stepping: advance a virtual clock at the true speed and yank the
+ // muted element forward to it each frame.
+ if (!seekSteppingRef.current) beginSeekStepping(video.currentTime, nowMs);
+ const dtSec = Math.max(0, (nowMs - stepLastTsRef.current) / 1000);
+ stepLastTsRef.current = nowMs;
+ // A non-finite duration (some WebM sources report Infinity until fully
+ // buffered) is not an end boundary — keep stepping until the region exits.
+ const endSec = Number.isFinite(video.duration) ? video.duration : Number.POSITIVE_INFINITY;
+ // Bound the advance to the active region so a fast frame doesn't overshoot
+ // far into the next region and skip its content — but land just *past* the
+ // end (not exactly on it) so the region is actually exited next frame.
+ const regionEndSec = activeSpeedRegion ? activeSpeedRegion.endMs / 1000 : endSec;
+ const rawNextSec = stepVirtualSecRef.current + speed * dtSec;
+ const nextSec = Math.min(
+ rawNextSec > regionEndSec ? regionEndSec + REGION_EXIT_MARGIN_SEC : rawNextSec,
+ endSec,
+ );
+
+ if (nextSec >= endSec) {
+ stepVirtualSecRef.current = endSec;
+ video.currentTime = endSec;
+ emitTime(endSec);
+ endSeekStepping();
+ video.pause();
+ return;
+ }
+ stepVirtualSecRef.current = nextSec;
+ // The playhead advances at the true speed every frame; the muted element
+ // is seeked toward it only when the previous seek has landed (its `seeked`
+ // fired), so a slow decoder still presents/steps frames instead of freezing
+ // perpetually mid-seek. Require a real forward jump so a no-op seek (e.g. the
+ // first frame, where dt≈0) can't leave the in-flight flag stuck with no `seeked`.
+ // Recover if a prior seek never reported `seeked` (would otherwise strand the
+ // throttle and freeze the frame for the rest of the session).
+ if (stepSeekInFlight && nowMs - stepSeekIssuedAtMs > STEP_SEEK_TIMEOUT_MS) {
+ stepSeekInFlight = false;
+ }
+ if (!stepSeekInFlight && nextSec - video.currentTime > STEP_MIN_SEEK_SEC) {
+ stepSeekInFlight = true;
+ stepSeekIssuedAtMs = nowMs;
+ video.currentTime = nextSec;
+ }
+ emitTime(nextSec);
+ }
}
if (!video.paused && !video.ended) {
@@ -115,6 +248,7 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {
};
const handlePause = () => {
+ endSeekStepping();
isPlayingRef.current = false;
onPlayStateChange(false);
if (timeUpdateAnimationRef.current) {
@@ -125,6 +259,12 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {
};
const handleSeeked = () => {
+ // Our own stepping seek landed (frame presented): allow the next one, then
+ // ignore the event — the rAF loop is the sole time authority while stepping.
+ if (seekSteppingRef.current) {
+ stepSeekInFlight = false;
+ return;
+ }
isSeekingRef.current = false;
if (isScrubbingRef && scrubEndTimerRef) {
@@ -158,6 +298,18 @@ export function createVideoEventHandlers(params: VideoEventHandlersParams) {
};
const handleSeeking = () => {
+ // Our per-frame forward seeks must not flip the element into scrub mode
+ // (which would disable zoom/blur effects every frame during stepping).
+ // Known limitation: while a >16× region is actively playing, the virtual clock
+ // owns the playhead, so scrubbing mid-playback is overridden on the next frame —
+ // pause first to reposition. (Distinguishing a user scrub from our own large
+ // async forward seeks reliably isn't feasible, so we don't try.)
+ if (seekSteppingRef.current) return;
+ // The internal catch-up seek on stepping->native handback must not enter scrub.
+ if (suppressSeekScrubOnce) {
+ suppressSeekScrubOnce = false;
+ return;
+ }
isSeekingRef.current = true;
if (isScrubbingRef) {
diff --git a/src/i18n/locales/ar/settings.json b/src/i18n/locales/ar/settings.json
index 2e34bae8b..a800fb64c 100644
--- a/src/i18n/locales/ar/settings.json
+++ b/src/i18n/locales/ar/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "حدد منطقة السرعة للتعديل",
"deleteRegion": "حذف منطقة السرعة",
"customPlaybackSpeed": "سرعة تشغيل مخصصة",
- "maxSpeedError": "لا يمكن للسرعة أن تتجاوز 16×"
+ "maxSpeedError": "لا يمكن للسرعة أن تتجاوز {{max}}×",
+ "previewFrameSteppingHint": "فوق {{native}}×، تعرض المعاينة إطارًا تلو الآخر وبدون صوت. لا يتأثر التصدير."
},
"trim": {
"deleteRegion": "حذف منطقة القص"
diff --git a/src/i18n/locales/en/settings.json b/src/i18n/locales/en/settings.json
index 93cef6d4c..03c240c39 100644
--- a/src/i18n/locales/en/settings.json
+++ b/src/i18n/locales/en/settings.json
@@ -32,7 +32,8 @@
"selectRegion": "Select a speed region to adjust",
"deleteRegion": "Delete Speed Region",
"customPlaybackSpeed": "Custom Playback Speed",
- "maxSpeedError": "Speed can't go higher than 16×"
+ "maxSpeedError": "Speed can't go higher than {{max}}×",
+ "previewFrameSteppingHint": "Above {{native}}×, preview is frame-stepped and muted. Export is unaffected."
},
"trim": {
"deleteRegion": "Delete Trim Region"
diff --git a/src/i18n/locales/es/settings.json b/src/i18n/locales/es/settings.json
index ac9267b41..3013b9278 100644
--- a/src/i18n/locales/es/settings.json
+++ b/src/i18n/locales/es/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "Selecciona una región de velocidad para ajustar",
"deleteRegion": "Eliminar región de velocidad",
"customPlaybackSpeed": "Velocidad personalizada",
- "maxSpeedError": "La velocidad no puede superar 16×"
+ "maxSpeedError": "La velocidad no puede superar {{max}}×",
+ "previewFrameSteppingHint": "Por encima de {{native}}×, la vista previa avanza fotograma a fotograma y sin sonido. La exportación no se ve afectada."
},
"trim": {
"deleteRegion": "Eliminar región de recorte"
diff --git a/src/i18n/locales/fr/settings.json b/src/i18n/locales/fr/settings.json
index 0b67cd266..a779def86 100644
--- a/src/i18n/locales/fr/settings.json
+++ b/src/i18n/locales/fr/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "Sélectionnez une région de vitesse à ajuster",
"deleteRegion": "Supprimer la région de vitesse",
"customPlaybackSpeed": "Vitesse de lecture personnalisée",
- "maxSpeedError": "La vitesse ne peut pas dépasser 16×"
+ "maxSpeedError": "La vitesse ne peut pas dépasser {{max}}×",
+ "previewFrameSteppingHint": "Au-delà de {{native}}×, l'aperçu avance image par image et sans son. L'export n'est pas affecté."
},
"trim": {
"deleteRegion": "Supprimer la région de coupe"
diff --git a/src/i18n/locales/it/settings.json b/src/i18n/locales/it/settings.json
index 9ee07a16a..48091c4fb 100644
--- a/src/i18n/locales/it/settings.json
+++ b/src/i18n/locales/it/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "Seleziona una regione velocità da regolare",
"deleteRegion": "Elimina regione velocità",
"customPlaybackSpeed": "Velocità di riproduzione personalizzata",
- "maxSpeedError": "La velocità non può superare 16×"
+ "maxSpeedError": "La velocità non può superare {{max}}×",
+ "previewFrameSteppingHint": "Oltre {{native}}×, l'anteprima procede fotogramma per fotogramma e senza audio. L'esportazione non è influenzata."
},
"trim": {
"deleteRegion": "Elimina regione taglio"
diff --git a/src/i18n/locales/ja-JP/settings.json b/src/i18n/locales/ja-JP/settings.json
index 69af9b2e7..0bf3b7ef7 100644
--- a/src/i18n/locales/ja-JP/settings.json
+++ b/src/i18n/locales/ja-JP/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "再生速度の範囲を選択して調整",
"deleteRegion": "再生速度の範囲を削除",
"customPlaybackSpeed": "カスタム再生速度",
- "maxSpeedError": "速度は16×を超えることはできません"
+ "maxSpeedError": "速度は{{max}}×を超えることはできません",
+ "previewFrameSteppingHint": "{{native}}×を超えるとプレビューはフレーム送りかつ無音になります。書き出しには影響しません。"
},
"trim": {
"deleteRegion": "トリム範囲を削除"
diff --git a/src/i18n/locales/ko-KR/settings.json b/src/i18n/locales/ko-KR/settings.json
index 808fd71a9..898048164 100644
--- a/src/i18n/locales/ko-KR/settings.json
+++ b/src/i18n/locales/ko-KR/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "조정할 속도 구간을 선택하세요",
"deleteRegion": "속도 구간 삭제",
"customPlaybackSpeed": "재생 속도 직접 입력",
- "maxSpeedError": "속도는 16×를 초과할 수 없습니다"
+ "maxSpeedError": "속도는 {{max}}×를 초과할 수 없습니다",
+ "previewFrameSteppingHint": "{{native}}×를 초과하면 미리보기가 프레임 단위로 재생되고 음소거됩니다. 내보내기에는 영향이 없습니다."
},
"trim": {
"deleteRegion": "트림 구간 삭제"
diff --git a/src/i18n/locales/pt-BR/settings.json b/src/i18n/locales/pt-BR/settings.json
index eddd1c43b..3e9d616b2 100644
--- a/src/i18n/locales/pt-BR/settings.json
+++ b/src/i18n/locales/pt-BR/settings.json
@@ -30,7 +30,8 @@
"selectRegion": "Selecione uma região de velocidade para ajustar",
"deleteRegion": "Excluir Região de Velocidade",
"customPlaybackSpeed": "Velocidade Personalizada",
- "maxSpeedError": "A velocidade não pode ser superior a 16×"
+ "maxSpeedError": "A velocidade não pode ser superior a {{max}}×",
+ "previewFrameSteppingHint": "Acima de {{native}}×, a prévia avança quadro a quadro e sem som. A exportação não é afetada."
},
"trim": {
"deleteRegion": "Excluir Região de Recorte"
diff --git a/src/i18n/locales/ru/settings.json b/src/i18n/locales/ru/settings.json
index 3b83a98dd..f8f8749c8 100644
--- a/src/i18n/locales/ru/settings.json
+++ b/src/i18n/locales/ru/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "Выберите область скорости для настройки",
"deleteRegion": "Удалить область скорости",
"customPlaybackSpeed": "Пользовательская скорость воспроизведения",
- "maxSpeedError": "Скорость не может быть выше 16×"
+ "maxSpeedError": "Скорость не может быть выше {{max}}×",
+ "previewFrameSteppingHint": "Выше {{native}}× предпросмотр идёт покадрово и без звука. На экспорт это не влияет."
},
"trim": {
"deleteRegion": "Удалить область обрезки"
diff --git a/src/i18n/locales/tr/settings.json b/src/i18n/locales/tr/settings.json
index b19fd8075..4b68ec2c3 100644
--- a/src/i18n/locales/tr/settings.json
+++ b/src/i18n/locales/tr/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "Ayarlamak için bir hız bölgesi seçin",
"deleteRegion": "Hız Bölgesini Sil",
"customPlaybackSpeed": "Özel Oynatma Hızı",
- "maxSpeedError": "Hız 16× değerinden yüksek olamaz"
+ "maxSpeedError": "Hız {{max}}× değerinden yüksek olamaz",
+ "previewFrameSteppingHint": "{{native}}× üzerinde önizleme kare kare ilerler ve sessizdir. Dışa aktarma etkilenmez."
},
"trim": {
"deleteRegion": "Kırpma Bölgesini Sil"
diff --git a/src/i18n/locales/vi/settings.json b/src/i18n/locales/vi/settings.json
index fe1585e75..4125ce192 100644
--- a/src/i18n/locales/vi/settings.json
+++ b/src/i18n/locales/vi/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "Chọn vùng tốc độ để điều chỉnh",
"deleteRegion": "Xóa vùng tốc độ",
"customPlaybackSpeed": "Tốc độ phát tùy chỉnh",
- "maxSpeedError": "Tốc độ không thể cao hơn 16×"
+ "maxSpeedError": "Tốc độ không thể cao hơn {{max}}×",
+ "previewFrameSteppingHint": "Trên {{native}}×, bản xem trước tua từng khung hình và tắt tiếng. Xuất video không bị ảnh hưởng."
},
"trim": {
"deleteRegion": "Xóa vùng cắt"
diff --git a/src/i18n/locales/zh-CN/settings.json b/src/i18n/locales/zh-CN/settings.json
index d1e7c0136..a1a949ab6 100644
--- a/src/i18n/locales/zh-CN/settings.json
+++ b/src/i18n/locales/zh-CN/settings.json
@@ -31,7 +31,8 @@
"selectRegion": "选择要调整的速度区域",
"deleteRegion": "删除速度区域",
"customPlaybackSpeed": "自定义播放速度",
- "maxSpeedError": "速度不能超过 16×"
+ "maxSpeedError": "速度不能超过 {{max}}×",
+ "previewFrameSteppingHint": "超过 {{native}}× 时,预览为逐帧跳转且静音,导出不受影响。"
},
"trim": {
"deleteRegion": "删除剪辑区域"
diff --git a/src/i18n/locales/zh-TW/settings.json b/src/i18n/locales/zh-TW/settings.json
index 5ec315819..28240463b 100644
--- a/src/i18n/locales/zh-TW/settings.json
+++ b/src/i18n/locales/zh-TW/settings.json
@@ -32,7 +32,8 @@
"selectRegion": "選擇要調整的速度區域",
"deleteRegion": "刪除速度區域",
"customPlaybackSpeed": "自訂播放速度",
- "maxSpeedError": "速度不能超過 16×"
+ "maxSpeedError": "速度不能超過 {{max}}×",
+ "previewFrameSteppingHint": "超過 {{native}}× 時,預覽為逐幀跳轉且靜音,匯出不受影響。"
},
"trim": {
"deleteRegion": "刪除剪輯區域"
diff --git a/src/lib/exporter/audioEncoder.ts b/src/lib/exporter/audioEncoder.ts
index 7514907e2..ec715880c 100644
--- a/src/lib/exporter/audioEncoder.ts
+++ b/src/lib/exporter/audioEncoder.ts
@@ -1,11 +1,27 @@
import { WebDemuxer } from "web-demuxer";
-import type { SpeedRegion, TrimRegion } from "@/components/video-editor/types";
+import {
+ MAX_NATIVE_PLAYBACK_RATE,
+ type SpeedRegion,
+ type TrimRegion,
+} from "@/components/video-editor/types";
+import { WsolaTimeStretcher } from "./audioTimeStretch";
import type { ExportAudioMuxerCodec, VideoMuxer } from "./muxer";
+import {
+ buildSpeedSegments,
+ maxTimelineSpeed,
+ type SpeedTimelineSegment,
+} from "./timelineSegments";
const AUDIO_BITRATE = 128_000;
const DECODE_BACKPRESSURE_LIMIT = 20;
const MIN_SPEED_REGION_DELTA_MS = 0.0001;
const SEEK_TIMEOUT_MS = 5_000;
+// AudioData slice size fed to the encoder from the offline time-stretch path.
+const OFFLINE_OUTPUT_FRAMES = 4096;
+const ENCODE_BACKPRESSURE_LIMIT = 20;
+// Must match streamingDecoder's EPSILON_SEC so the offline audio segment lengths
+// use the same per-frame quantization as the video output.
+const VIDEO_EPSILON_SEC = 0.001;
export interface ExportAudioCodec {
encoderCodec: string;
@@ -221,6 +237,7 @@ export class AudioProcessor {
speedRegions: SpeedRegion[] | undefined,
validatedDurationSec: number,
exportCodec: ExportAudioCodec,
+ targetFrameRate: number,
): Promise<void> {
const sortedTrims = trimRegions ? [...trimRegions].sort((a, b) => a.startMs - b.startMs) : [];
const sortedSpeedRegions = speedRegions
@@ -229,8 +246,24 @@ export class AudioProcessor {
.sort((a, b) => a.startMs - b.startMs)
: [];
- // Speed edits need timeline playback to preserve pitch.
+ // Speed edits need pitch preservation. Segments at or below the native
+ // playbackRate cap use the real-time <audio> capture (proven, sounds best);
+ // anything faster can't be played in real time, so the whole timeline is
+ // rendered offline with a WSOLA time-stretch instead.
if (sortedSpeedRegions.length > 0) {
+ const segments = buildSpeedSegments(validatedDurationSec, sortedTrims, sortedSpeedRegions);
+
+ if (maxTimelineSpeed(segments) > MAX_NATIVE_PLAYBACK_RATE) {
+ await this.renderOfflineTimelineAudio(
+ demuxer,
+ muxer,
+ segments,
+ exportCodec,
+ targetFrameRate,
+ );
+ return;
+ }
+
const renderedAudioBlob = await this.renderPitchPreservedTimelineAudio(
videoUrl,
sortedTrims,
@@ -599,6 +632,286 @@ export class AudioProcessor {
return recordedBlob;
}
+ /**
+ * Offline pitch-preserved timeline audio for projects that contain a segment
+ * faster than the native playbackRate cap (which the real-time capture path
+ * can't reach). Streams the source once, routes each frame's PCM into the
+ * active timeline segment, applies a WSOLA time-stretch per segment, and
+ * encodes the result — clamping each segment to its exact expected length so
+ * the audio stays locked to the (independently retimed) video.
+ */
+ private async renderOfflineTimelineAudio(
+ demuxer: WebDemuxer,
+ muxer: VideoMuxer,
+ segments: SpeedTimelineSegment[],
+ exportCodec: ExportAudioCodec,
+ targetFrameRate: number,
+ ): Promise<void> {
+ let audioConfig: AudioDecoderConfig;
+ try {
+ audioConfig = await demuxer.getDecoderConfig("audio");
+ } catch {
+ console.warn("[AudioProcessor] No audio track found, skipping");
+ return;
+ }
+
+ const codecCheck = await AudioDecoder.isConfigSupported(audioConfig);
+ if (!codecCheck.supported) {
+ console.warn("[AudioProcessor] Audio codec not supported:", audioConfig.codec);
+ return;
+ }
+
+ const sampleRate = audioConfig.sampleRate || 48000;
+ const outputChannels = exportCodec.numberOfChannels || audioConfig.numberOfChannels || 2;
+ const outputSampleRate = exportCodec.sampleRate || sampleRate;
+
+ const encodeConfig: AudioEncoderConfig = {
+ codec: exportCodec.encoderCodec,
+ sampleRate: outputSampleRate,
+ numberOfChannels: outputChannels,
+ bitrate: AUDIO_BITRATE,
+ };
+ const encodeSupport = await AudioEncoder.isConfigSupported(encodeConfig);
+ if (!encodeSupport.supported) {
+ console.warn(`[AudioProcessor] ${exportCodec.label} encoding not supported, skipping audio`);
+ return;
+ }
+
+ const encodedChunks: { chunk: EncodedAudioChunk; meta?: EncodedAudioChunkMetadata }[] = [];
+ const encoder = new AudioEncoder({
+ output: (chunk, meta) => encodedChunks.push({ chunk, meta }),
+ error: (e: DOMException) => console.error("[AudioProcessor] Encode error:", e),
+ });
+ encoder.configure(encodeConfig);
+
+ // Output-side accumulator: buffered stretched PCM flushed as fixed-size
+ // AudioData slices with running (monotonic) output timestamps.
+ const outAcc: Float32Array[] = Array.from(
+ { length: outputChannels },
+ () => new Float32Array(0),
+ );
+ let outTimestampSamples = 0;
+
+ const flushOutput = (drainAll: boolean) => {
+ while (outAcc[0].length >= OFFLINE_OUTPUT_FRAMES || (drainAll && outAcc[0].length > 0)) {
+ const take = Math.min(OFFLINE_OUTPUT_FRAMES, outAcc[0].length);
+ const data = new Float32Array(take * outputChannels);
+ for (let c = 0; c < outputChannels; c++) {
+ data.set(outAcc[c].subarray(0, take), c * take);
+ outAcc[c] = outAcc[c].slice(take);
+ }
+ const audioData = new AudioData({
+ format: "f32-planar",
+ sampleRate: outputSampleRate,
+ numberOfFrames: take,
+ numberOfChannels: outputChannels,
+ timestamp: Math.round((outTimestampSamples / outputSampleRate) * 1_000_000),
+ data: data.buffer,
+ });
+ outTimestampSamples += take;
+ encoder.encode(audioData);
+ audioData.close();
+ }
+ };
+
+ const appendOutput = (planes: Float32Array[], count: number) => {
+ if (count <= 0) return;
+ for (let c = 0; c < outputChannels; c++) {
+ const merged = new Float32Array(outAcc[c].length + count);
+ merged.set(outAcc[c], 0);
+ merged.set(planes[c].subarray(0, count), outAcc[c].length);
+ outAcc[c] = merged;
+ }
+ };
+
+ // Per-segment state.
+ let segIdx = 0;
+ let stretcher: WsolaTimeStretcher | null = null;
+ let segExpectedOut = 0;
+ let segEmittedOut = 0;
+
+ const startSegment = (seg: SpeedTimelineSegment) => {
+ // Match the video path's per-segment frame quantization exactly (streamingDecoder
+ // emits ceil((dur - EPSILON)/speed * fps) frames) so audio and video advance by
+ // the same amount each segment and never accumulate drift.
+ const frameCount = Math.ceil(
+ ((seg.endSec - seg.startSec - VIDEO_EPSILON_SEC) / seg.speed) * targetFrameRate,
+ );
+ segExpectedOut = Math.max(0, Math.round((frameCount / targetFrameRate) * outputSampleRate));
+ segEmittedOut = 0;
+ stretcher = new WsolaTimeStretcher({
+ sampleRate,
+ channels: outputChannels,
+ speed: seg.speed,
+ expectedOutputSamples: segExpectedOut,
+ });
+ };
+
+ // Clamp each segment's emitted output to its expected length (drops the WSOLA
+ // tail overshoot; pads with silence on the rare underrun) so cumulative A/V
+ // timing matches the video the audio is retimed against.
+ const emitStretched = (planes: Float32Array[]) => {
+ const produced = planes[0]?.length ?? 0;
+ const allowed = Math.max(0, segExpectedOut - segEmittedOut);
+ const take = Math.min(produced, allowed);
+ appendOutput(planes, take);
+ segEmittedOut += take;
+ };
+
+ const finalizeSegment = () => {
+ if (!stretcher) return;
+ emitStretched(stretcher.flush());
+ if (segEmittedOut < segExpectedOut) {
+ const pad = segExpectedOut - segEmittedOut;
+ const silence = Array.from({ length: outputChannels }, () => new Float32Array(pad));
+ appendOutput(silence, pad);
+ segEmittedOut += pad;
+ }
+ stretcher = null;
+ };
+
+ const segStartSample = (seg: SpeedTimelineSegment) => Math.round(seg.startSec * sampleRate);
+ const segEndSample = (seg: SpeedTimelineSegment) => Math.round(seg.endSec * sampleRate);
+
+ const routeFrame = (planes: Float32Array[], frameStartSample: number, frameCount: number) => {
+ let local = 0;
+ while (local < frameCount && segIdx < segments.length) {
+ const seg = segments[segIdx];
+ const segStart = segStartSample(seg);
+ const segEnd = segEndSample(seg);
+ const currentAbs = frameStartSample + local;
+
+ if (currentAbs < segStart) {
+ // In a trimmed gap (or before the first segment): discard.
+ local += Math.min(segStart - currentAbs, frameCount - local);
+ continue;
+ }
+ if (currentAbs >= segEnd) {
+ finalizeSegment();
+ segIdx += 1;
+ continue;
+ }
+ if (!stretcher) startSegment(seg);
+ const take = Math.min(segEnd, frameStartSample + frameCount) - currentAbs;
+ const slice = planes.map((p) => p.subarray(local, local + take));
+ emitStretched((stretcher as WsolaTimeStretcher).push(slice));
+ local += take;
+ }
+ };
+
+ // Streaming decode: frames arrive in source order via the decoder callback.
+ const pending: AudioData[] = [];
+ const decoder = new AudioDecoder({
+ output: (data: AudioData) => pending.push(data),
+ error: (e: DOMException) => console.error("[AudioProcessor] Decode error:", e),
+ });
+ decoder.configure(audioConfig);
+
+ const drainPending = async () => {
+ while (pending.length > 0) {
+ if (this.cancelled) {
+ for (const d of pending) d.close();
+ pending.length = 0;
+ return;
+ }
+ const data = pending.shift();
+ if (!data) continue;
+ const frameCount = data.numberOfFrames;
+ const sourceChannels = data.numberOfChannels;
+ const srcPlanes: Float32Array[] = [];
+ for (let c = 0; c < sourceChannels; c++) {
+ const plane = new Float32Array(frameCount);
+ data.copyTo(plane, { format: "f32-planar", planeIndex: c });
+ srcPlanes.push(plane);
+ }
+ const frameStartSample = Math.round((data.timestamp / 1_000_000) * sampleRate);
+ data.close();
+
+ // Match source channels through untouched; otherwise downmix (to 1 or 2).
+ let planes: Float32Array[];
+ if (outputChannels === sourceChannels) {
+ planes = srcPlanes;
+ } else {
+ const downmixed = downmixPlanarChannelsForExport(srcPlanes, outputChannels);
+ planes = [];
+ for (let c = 0; c < outputChannels; c++) {
+ planes.push(downmixed.subarray(c * frameCount, (c + 1) * frameCount));
+ }
+ }
+
+ routeFrame(planes, frameStartSample, frameCount);
+ flushOutput(false);
+
+ while (encoder.encodeQueueSize > ENCODE_BACKPRESSURE_LIMIT && !this.cancelled) {
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }
+ }
+ };
+
+ // Read past the last segment's source end (mirrors streamingDecoder's +0.5s
+ // window so both paths read the same distance past the boundary).
+ const lastSegmentEndSec = segments.length > 0 ? segments[segments.length - 1].endSec : 0;
+ const readEndSec = lastSegmentEndSec + 0.5;
+ const reader = demuxer.read("audio", 0, readEndSec).getReader();
+ try {
+ while (!this.cancelled) {
+ const { done, value: chunk } = await reader.read();
+ if (done || !chunk) break;
+ decoder.decode(chunk);
+ while (decoder.decodeQueueSize > DECODE_BACKPRESSURE_LIMIT && !this.cancelled) {
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }
+ await drainPending();
+ }
+ } finally {
+ try {
+ await reader.cancel();
+ } catch {
+ /* reader already closed */
+ }
+ }
+
+ if (decoder.state === "configured") {
+ if (!this.cancelled) {
+ await decoder.flush();
+ }
+ decoder.close();
+ }
+ await drainPending();
+
+ if (this.cancelled) {
+ if (encoder.state === "configured") encoder.close();
+ return;
+ }
+
+ // Finalize the segment still open at end-of-stream, then pad any segments that
+ // never received audio (source shorter than the timeline) with silence.
+ if (stretcher) {
+ finalizeSegment();
+ segIdx += 1;
+ }
+ for (; segIdx < segments.length; segIdx++) {
+ startSegment(segments[segIdx]);
+ finalizeSegment();
+ }
+
+ flushOutput(true);
+
+ if (encoder.state === "configured") {
+ await encoder.flush();
+ encoder.close();
+ }
+
+ for (const { chunk, meta } of encodedChunks) {
+ if (this.cancelled) break;
+ await muxer.addAudioChunk(chunk, meta);
+ }
+
+ console.log(
+ `[AudioProcessor] Offline timeline audio: ${segments.length} segments, ${encodedChunks.length} chunks`,
+ );
+ }
+
// Demux the rendered speed-adjusted blob and feed its chunks into the MP4 muxer.
private async muxRenderedAudioBlob(
blob: Blob,
diff --git a/src/lib/exporter/audioTimeStretch.test.ts b/src/lib/exporter/audioTimeStretch.test.ts
new file mode 100644
index 000000000..dfc3f6728
--- /dev/null
+++ b/src/lib/exporter/audioTimeStretch.test.ts
@@ -0,0 +1,144 @@
+import { describe, expect, it } from "vitest";
+import { WsolaTimeStretcher } from "./audioTimeStretch";
+
+const SR = 48000;
+
+function sine(freq: number, seconds: number, sampleRate = SR): Float32Array {
+ const out = new Float32Array(Math.round(seconds * sampleRate));
+ for (let i = 0; i < out.length; i++) {
+ out[i] = Math.sin((2 * Math.PI * freq * i) / sampleRate);
+ }
+ return out;
+}
+
+// Feed a signal through the stretcher in small chunks (as decoding would) and
+// return the concatenated per-channel output.
+function stretch(channelsIn: Float32Array[], speed: number, chunk = 2048): Float32Array[] {
+ const channels = channelsIn.length;
+ const st = new WsolaTimeStretcher({ sampleRate: SR, channels, speed });
+ const acc: Float32Array[] = Array.from({ length: channels }, () => new Float32Array(0));
+ const append = (dst: Float32Array[], next: Float32Array[]) => {
+ for (let c = 0; c < channels; c++) {
+ const merged = new Float32Array(dst[c].length + next[c].length);
+ merged.set(dst[c], 0);
+ merged.set(next[c], dst[c].length);
+ dst[c] = merged;
+ }
+ };
+ for (let off = 0; off < channelsIn[0].length; off += chunk) {
+ const slice = channelsIn.map((p) => p.subarray(off, Math.min(off + chunk, p.length)));
+ append(acc, st.push(slice));
+ }
+ append(acc, st.flush());
+ return acc;
+}
+
+function rms(signal: Float32Array, from = 0, to = signal.length): number {
+ let sum = 0;
+ for (let i = from; i < to; i++) sum += signal[i] * signal[i];
+ return Math.sqrt(sum / Math.max(1, to - from));
+}
+
+// Zero-crossings per second — a pitch proxy that is invariant to time-stretching.
+function crossingsPerSecond(signal: Float32Array): number {
+ let crossings = 0;
+ for (let i = 1; i < signal.length; i++) {
+ if ((signal[i - 1] < 0 && signal[i] >= 0) || (signal[i - 1] >= 0 && signal[i] < 0)) {
+ crossings++;
+ }
+ }
+ return crossings / (signal.length / SR);
+}
+
+describe("WsolaTimeStretcher", () => {
+ it("compresses duration by the speed factor", () => {
+ const input = sine(440, 1.0);
+ const [out] = stretch([input], 4);
+ const expected = input.length / 4;
+ // WSOLA overshoots the ideal length by up to ~one trailing grain (~40 ms); the
+ // exporter clamps each segment to its exact expected length for A/V sync.
+ const grain = Math.round(SR * 0.04);
+ expect(out.length).toBeGreaterThan(expected - grain);
+ expect(out.length).toBeLessThan(expected + 2 * grain);
+ });
+
+ it("preserves pitch when speeding up 4x", () => {
+ const input = sine(440, 1.0);
+ const [out] = stretch([input], 4);
+ // A 440 Hz tone crosses zero ~880 times/second regardless of tempo.
+ expect(crossingsPerSecond(out)).toBeGreaterThan(880 * 0.85);
+ expect(crossingsPerSecond(out)).toBeLessThan(880 * 1.15);
+ });
+
+ it("preserves pitch at an extreme 50x speed-up", () => {
+ const input = sine(440, 4.0);
+ const [out] = stretch([input], 50);
+ expect(out.length).toBeGreaterThan(0);
+ expect(out.every((s) => Number.isFinite(s))).toBe(true);
+ expect(crossingsPerSecond(out)).toBeGreaterThan(880 * 0.7);
+ expect(crossingsPerSecond(out)).toBeLessThan(880 * 1.3);
+ });
+
+ it("expands duration when slowing down below 1x", () => {
+ const input = sine(300, 0.5);
+ const [out] = stretch([input], 0.5);
+ const expected = input.length / 0.5;
+ expect(out.length).toBeGreaterThan(expected * 0.9);
+ expect(out.length).toBeLessThan(expected * 1.1);
+ expect(crossingsPerSecond(out)).toBeGreaterThan(600 * 0.85);
+ expect(crossingsPerSecond(out)).toBeLessThan(600 * 1.15);
+ });
+
+ it("passes 1x audio through untouched (per channel)", () => {
+ const left = sine(220, 0.2);
+ const right = sine(330, 0.2);
+ const [outL, outR] = stretch([left, right], 1);
+ expect(outL.length).toBe(left.length);
+ expect(outR.length).toBe(right.length);
+ expect(Array.from(outL.slice(0, 100))).toEqual(Array.from(left.slice(0, 100)));
+ expect(Array.from(outR.slice(0, 100))).toEqual(Array.from(right.slice(0, 100)));
+ });
+
+ it("keeps output bounded to roughly unit amplitude (constant-overlap-add)", () => {
+ const input = sine(500, 0.5);
+ const [out] = stretch([input], 8);
+ let peak = 0;
+ for (const s of out) peak = Math.max(peak, Math.abs(s));
+ expect(peak).toBeGreaterThan(0.7);
+ expect(peak).toBeLessThan(1.2);
+ });
+
+ it("samples across a short high-speed region instead of only its first grain", () => {
+ // 1s of tone at 100x -> ~480 output samples. Without the adaptive grain hint the
+ // default 40ms hop (Ha=96000) places a single grain and drops ~99% of the region.
+ const input = sine(440, 1.0);
+ const st = new WsolaTimeStretcher({
+ sampleRate: SR,
+ channels: 1,
+ speed: 100,
+ expectedOutputSamples: 480,
+ });
+ const first = st.push([input])[0];
+ const tail = st.flush()[0];
+ const out = new Float32Array(first.length + tail.length);
+ out.set(first, 0);
+ out.set(tail, first.length);
+
+ // Content is present across the whole output, including its second half (which
+ // comes from grains sampled ~500-750ms into the region, not just the start).
+ expect(out.length).toBeGreaterThan(300);
+ expect(rms(out)).toBeGreaterThan(0.2);
+ expect(rms(out, Math.floor(out.length / 2))).toBeGreaterThan(0.2);
+ });
+
+ it("does not fade in from silence at the start of a segment", () => {
+ // Window-sum normalization must give the first grain's leading half full
+ // amplitude rather than a ~20ms Hann ramp up from zero.
+ const input = sine(440, 2.0);
+ const [out] = stretch([input], 20);
+ let peakStart = 0;
+ for (let i = 0; i < Math.min(200, out.length); i++)
+ peakStart = Math.max(peakStart, Math.abs(out[i]));
+ expect(peakStart).toBeGreaterThan(0.3);
+ });
+});
diff --git a/src/lib/exporter/audioTimeStretch.ts b/src/lib/exporter/audioTimeStretch.ts
new file mode 100644
index 000000000..d93016375
--- /dev/null
+++ b/src/lib/exporter/audioTimeStretch.ts
@@ -0,0 +1,306 @@
+// Pitch-preserving audio time-stretch (WSOLA) used by the offline export path for
+// speed regions faster than the browser's 16× playbackRate ceiling.
+//
+// WSOLA (Waveform Similarity Overlap-Add) resamples the *time* axis while leaving
+// the frequency content — and therefore the pitch — untouched: it slides a
+// windowed grain along the input at the analysis hop (speed × synthesis hop) and
+// overlap-adds it at the fixed synthesis hop, nudging each grain by up to a search
+// radius to the position that best continues the previous output (avoiding the
+// phase-cancellation clicks of plain overlap-add).
+//
+// The stretcher is streaming: push() feeds decoded PCM incrementally and returns
+// finished output, so a multi-hour region never has to be held in memory at once.
+
+export interface WsolaOptions {
+ sampleRate: number;
+ channels: number;
+ /** Output is 1/speed as long as the input (speed > 1 compresses / speeds up). */
+ speed: number;
+ frameSize?: number;
+ searchRadius?: number;
+ /**
+ * Hint of the total output length (samples). When the output is short relative
+ * to the default grain — a short region at very high speed — the grain size is
+ * shrunk so several grains still sample across the whole region instead of one
+ * grain capturing only its first few ms.
+ */
+ expectedOutputSamples?: number;
+}
+
+const DEFAULT_FRAME_SEC = 0.04; // 40 ms grains
+const MIN_FRAME_SEC = 0.005; // floor grain size for extreme compression
+const DEFAULT_SEARCH_SEC = 0.01; // ±10 ms similarity search
+const TARGET_GRAINS = 8; // aim for at least this many grains across a region
+const PASSTHROUGH_EPSILON = 1e-3;
+
+function hann(length: number): Float32Array {
+ const w = new Float32Array(length);
+ for (let i = 0; i < length; i++) {
+ w[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (length - 1));
+ }
+ return w;
+}
+
+/**
+ * Streaming WSOLA time-stretcher. One instance handles a single constant speed.
+ * All channels share the grain positions chosen from a mono mix so the stereo
+ * image is preserved.
+ */
+export class WsolaTimeStretcher {
+ private readonly channels: number;
+ private readonly passthrough: boolean;
+ private readonly N: number;
+ private readonly Hs: number;
+ private readonly Ha: number;
+ private readonly W: number;
+ private readonly window: Float32Array;
+
+ // Input sliding buffer (per channel + a mono mix for the similarity search).
+ private buf: Float32Array[];
+ private mono: Float32Array;
+ private bufStart = 0; // absolute input index of buf[*][0]
+
+ // Output sliding accumulator + the summed window weight per output sample, used
+ // to normalize the overlap-add so grain-edge samples reach full amplitude (no
+ // fade-in from silence at a segment start) regardless of the WSOLA shifts.
+ private out: Float32Array[];
+ private winSum: Float32Array;
+ private outStart = 0; // absolute output index of out[*][0]
+
+ private idealPos = 0; // fractional ideal analysis position for the next grain
+ private grainPos = 0; // integer input index of the next grain to place
+ private frame = 0; // synthesis frame counter
+ private placedAny = false;
+
+ constructor(opts: WsolaOptions) {
+ this.channels = Math.max(1, opts.channels);
+ this.passthrough = Math.abs(opts.speed - 1) < PASSTHROUGH_EPSILON;
+
+ let n = opts.frameSize ?? Math.round(opts.sampleRate * DEFAULT_FRAME_SEC);
+ if (n < 4) n = 4;
+ if (n % 2 !== 0) n += 1;
+ let hs = n / 2;
+
+ // Shrink the grain when the whole output would otherwise be shorter than a
+ // few default grains, so short/high-speed regions are still sampled across.
+ if (opts.expectedOutputSamples != null && opts.expectedOutputSamples > 0) {
+ const minHs = Math.max(2, Math.round((opts.sampleRate * MIN_FRAME_SEC) / 2));
+ const targetHs = Math.floor(opts.expectedOutputSamples / TARGET_GRAINS);
+ hs = Math.min(hs, Math.max(minHs, targetHs));
+ }
+
+ this.Hs = hs;
+ this.N = hs * 2;
+ this.Ha = hs * opts.speed;
+ this.W = Math.min(opts.searchRadius ?? Math.round(opts.sampleRate * DEFAULT_SEARCH_SEC), hs);
+ this.window = hann(this.N);
+
+ this.buf = Array.from({ length: this.channels }, () => new Float32Array(0));
+ this.mono = new Float32Array(0);
+ this.out = Array.from({ length: this.channels }, () => new Float32Array(0));
+ this.winSum = new Float32Array(0);
+ }
+
+ /** Feed more input PCM (per-channel planar). Returns any finished output PCM. */
+ push(planar: Float32Array[]): Float32Array[] {
+ if (this.passthrough) {
+ // Copy so callers may reuse their buffers; output === input for 1× spans.
+ return planar.map((p) => p.slice());
+ }
+ this.append(planar);
+ return this.process(false);
+ }
+
+ /** Drain all remaining output. Call once after the final push(). */
+ flush(): Float32Array[] {
+ if (this.passthrough) return this.emptyChunk();
+ return this.process(true);
+ }
+
+ private emptyChunk(): Float32Array[] {
+ return Array.from({ length: this.channels }, () => new Float32Array(0));
+ }
+
+ private append(planar: Float32Array[]): void {
+ const addLen = planar[0]?.length ?? 0;
+ if (addLen === 0) return;
+ const oldLen = this.buf[0].length;
+ for (let c = 0; c < this.channels; c++) {
+ const next = new Float32Array(oldLen + addLen);
+ next.set(this.buf[c], 0);
+ next.set(planar[c] ?? planar[0], oldLen);
+ this.buf[c] = next;
+ }
+ const mono = new Float32Array(oldLen + addLen);
+ mono.set(this.mono, 0);
+ for (let i = 0; i < addLen; i++) {
+ let sum = 0;
+ for (let c = 0; c < this.channels; c++) sum += planar[c]?.[i] ?? planar[0][i];
+ mono[oldLen + i] = sum / this.channels;
+ }
+ this.mono = mono;
+ }
+
+ private bufEnd(): number {
+ return this.bufStart + this.buf[0].length;
+ }
+
+ private sampleAt(channel: number, absIndex: number): number {
+ return this.buf[channel][absIndex - this.bufStart] ?? 0;
+ }
+
+ private monoAt(absIndex: number): number {
+ const i = absIndex - this.bufStart;
+ return i >= 0 && i < this.mono.length ? this.mono[i] : 0;
+ }
+
+ private process(final: boolean): Float32Array[] {
+ const emitted: Float32Array[] = Array.from(
+ { length: this.channels },
+ () => new Float32Array(0),
+ );
+
+ while (true) {
+ // Input we must have buffered before this frame can be placed and the next
+ // grain position searched.
+ const searchTarget = Math.round(this.idealPos + this.Ha);
+ const requiredEnd = Math.max(
+ this.grainPos + this.N,
+ this.grainPos + this.Hs + this.N,
+ searchTarget + this.W + this.N,
+ );
+ if (!final && this.bufEnd() < requiredEnd) break;
+ // Nothing left to place once the grain itself runs past the buffer.
+ if (this.grainPos + this.N > this.bufEnd()) break;
+
+ this.placeGrain(this.grainPos);
+ const placedFrame = this.frame;
+
+ // Choose the next grain: search near the ideal position for the shift that
+ // best continues the just-placed grain.
+ const refStart = this.grainPos + this.Hs;
+ const bestDelta = this.findBestDelta(refStart, searchTarget);
+ this.grainPos = searchTarget + bestDelta;
+ this.idealPos += this.Ha;
+ this.frame += 1;
+
+ // Output below the placed frame's start is final; emit and drop it.
+ this.collect(placedFrame * this.Hs, emitted);
+ // Input below the next grain is no longer referenced.
+ this.discardBelow(this.grainPos);
+ }
+
+ if (final) {
+ this.collectAll(emitted);
+ }
+ return emitted;
+ }
+
+ private placeGrain(pos: number): void {
+ const outAbs = this.frame * this.Hs;
+ this.ensureOut(outAbs + this.N);
+ const base = outAbs - this.outStart;
+ for (let c = 0; c < this.channels; c++) {
+ const dst = this.out[c];
+ for (let k = 0; k < this.N; k++) {
+ dst[base + k] += this.sampleAt(c, pos + k) * this.window[k];
+ }
+ }
+ for (let k = 0; k < this.N; k++) {
+ this.winSum[base + k] += this.window[k];
+ }
+ this.placedAny = true;
+ }
+
+ private findBestDelta(refStart: number, target: number): number {
+ // Normalized cross-correlation of the natural continuation (ref) against each
+ // candidate grain within ±W. Falls back to 0 when input is too short (flush tail).
+ if (refStart + this.N > this.bufEnd()) return 0;
+
+ let refEnergy = 0;
+ for (let k = 0; k < this.N; k++) {
+ const r = this.monoAt(refStart + k);
+ refEnergy += r * r;
+ }
+ if (refEnergy === 0) return 0;
+
+ let bestDelta = 0;
+ let bestScore = -Infinity;
+ const loDelta = Math.max(-this.W, this.bufStart - target);
+ const hiDelta = Math.min(this.W, this.bufEnd() - this.N - target);
+ for (let delta = loDelta; delta <= hiDelta; delta++) {
+ const candStart = target + delta;
+ let dot = 0;
+ let energy = 0;
+ for (let k = 0; k < this.N; k++) {
+ const c = this.monoAt(candStart + k);
+ dot += c * this.monoAt(refStart + k);
+ energy += c * c;
+ }
+ const score = energy > 0 ? dot / Math.sqrt(energy) : 0;
+ if (score > bestScore) {
+ bestScore = score;
+ bestDelta = delta;
+ }
+ }
+ return bestDelta;
+ }
+
+ private ensureOut(absEnd: number): void {
+ const needed = absEnd - this.outStart;
+ if (needed <= this.out[0].length) return;
+ const nextLen = Math.max(needed, this.out[0].length * 2, this.N * 4);
+ for (let c = 0; c < this.channels; c++) {
+ const grown = new Float32Array(nextLen);
+ grown.set(this.out[c], 0);
+ this.out[c] = grown;
+ }
+ const grownWin = new Float32Array(nextLen);
+ grownWin.set(this.winSum, 0);
+ this.winSum = grownWin;
+ }
+
+ private collect(absEnd: number, emitted: Float32Array[]): void {
+ const count = absEnd - this.outStart;
+ if (count <= 0) return;
+ for (let c = 0; c < this.channels; c++) {
+ const chunk = this.out[c].slice(0, count);
+ // Normalize by the summed window weight so overlap-add gain is 1 everywhere,
+ // including the first/last grain edges (no fade-in from silence).
+ for (let i = 0; i < count; i++) {
+ const w = this.winSum[i];
+ if (w > 1e-6) chunk[i] /= w;
+ }
+ emitted[c] = concat(emitted[c], chunk);
+ this.out[c] = this.out[c].slice(count);
+ }
+ this.winSum = this.winSum.slice(count);
+ this.outStart = absEnd;
+ }
+
+ private collectAll(emitted: Float32Array[]): void {
+ if (!this.placedAny) return;
+ // The last placed frame ends at (frame-1)*Hs + N.
+ const end = (this.frame - 1) * this.Hs + this.N;
+ this.collect(end, emitted);
+ }
+
+ private discardBelow(absIndex: number): void {
+ const drop = absIndex - this.bufStart;
+ if (drop <= 0) return;
+ for (let c = 0; c < this.channels; c++) {
+ this.buf[c] = this.buf[c].slice(drop);
+ }
+ this.mono = this.mono.slice(drop);
+ this.bufStart = absIndex;
+ }
+}
+
+function concat(a: Float32Array, b: Float32Array): Float32Array {
+ if (a.length === 0) return b;
+ if (b.length === 0) return a;
+ const out = new Float32Array(a.length + b.length);
+ out.set(a, 0);
+ out.set(b, a.length);
+ return out;
+}
diff --git a/src/lib/exporter/streamingDecoder.ts b/src/lib/exporter/streamingDecoder.ts
index 34cfcd568..54f4b9f8d 100644
--- a/src/lib/exporter/streamingDecoder.ts
+++ b/src/lib/exporter/streamingDecoder.ts
@@ -6,6 +6,7 @@ import {
releaseLocalSourceFile,
} from "./localSourceFile";
import { MAX_IN_MEMORY_SOURCE_BYTES } from "./sourceFileLimits";
+import { computeKeepSegments, splitBySpeed } from "./timelineSegments";
const SOURCE_LOAD_TIMEOUT_MS = 60_000;
// Large local recordings are streamed into OPFS before demuxing, which is
@@ -383,8 +384,8 @@ export class StreamingVideoDecoder {
codec.includes("av1") ||
codec.includes("vp09") ||
codec.includes("vp9");
- const segments = this.splitBySpeed(
- this.computeSegments(this.metadata.duration, trimRegions),
+ const segments = splitBySpeed(
+ computeKeepSegments(this.metadata.duration, trimRegions),
speedRegions,
);
const requiredEndSec = segments[segments.length - 1]?.endSec ?? 0;
@@ -671,38 +672,6 @@ export class StreamingVideoDecoder {
}
}
- /**
- * Converts trim regions into the segments that should be kept.
- * Returns a single full-duration segment when no trim regions are present.
- */
- private computeSegments(
- totalDuration: number,
- trimRegions?: TrimRegion[],
- ): Array<{ startSec: number; endSec: number }> {
- if (!trimRegions || trimRegions.length === 0) {
- return [{ startSec: 0, endSec: totalDuration }];
- }
-
- const sorted = [...trimRegions].sort((a, b) => a.startMs - b.startMs);
- const segments: Array<{ startSec: number; endSec: number }> = [];
- let cursor = 0;
-
- for (const trim of sorted) {
- const trimStart = trim.startMs / 1000;
- const trimEnd = trim.endMs / 1000;
- if (cursor < trimStart) {
- segments.push({ startSec: cursor, endSec: trimStart });
- }
- cursor = trimEnd;
- }
-
- if (cursor < totalDuration) {
- segments.push({ startSec: cursor, endSec: totalDuration });
- }
-
- return segments;
- }
-
/**
* Effective output duration (seconds) and total frame count for the given trim/speed
* regions at the target frame rate. Requires loadMetadata() first.
@@ -713,8 +682,8 @@ export class StreamingVideoDecoder {
speedRegions?: SpeedRegion[],
): { effectiveDuration: number; totalFrames: number } {
if (!this.metadata) throw new Error("Must call loadMetadata() first");
- const trimSegments = this.computeSegments(this.metadata.duration, trimRegions);
- const segments = this.splitBySpeed(trimSegments, speedRegions);
+ const trimSegments = computeKeepSegments(this.metadata.duration, trimRegions);
+ const segments = splitBySpeed(trimSegments, speedRegions);
return {
effectiveDuration: segments.reduce(
(sum, seg) => sum + (seg.endSec - seg.startSec) / seg.speed,
@@ -727,42 +696,6 @@ export class StreamingVideoDecoder {
};
}
- /**
- * Splits keep-segments by overlapping speed regions, annotating each
- * sub-segment with its playback speed multiplier (defaults to 1×).
- */
- private splitBySpeed(
- segments: Array<{ startSec: number; endSec: number }>,
- speedRegions?: SpeedRegion[],
- ): Array<{ startSec: number; endSec: number; speed: number }> {
- if (!speedRegions || speedRegions.length === 0)
- return segments.map((s) => ({ ...s, speed: 1 }));
-
- const result: Array<{ startSec: number; endSec: number; speed: number }> = [];
- for (const segment of segments) {
- const overlapping = speedRegions
- .filter((sr) => sr.startMs / 1000 < segment.endSec && sr.endMs / 1000 > segment.startSec)
- .sort((a, b) => a.startMs - b.startMs);
-
- if (overlapping.length === 0) {
- result.push({ ...segment, speed: 1 });
- continue;
- }
-
- let cursor = segment.startSec;
- for (const sr of overlapping) {
- const srStart = Math.max(sr.startMs / 1000, segment.startSec);
- const srEnd = Math.min(sr.endMs / 1000, segment.endSec);
- if (cursor < srStart) result.push({ startSec: cursor, endSec: srStart, speed: 1 });
- result.push({ startSec: srStart, endSec: srEnd, speed: sr.speed });
- cursor = srEnd;
- }
- if (cursor < segment.endSec)
- result.push({ startSec: cursor, endSec: segment.endSec, speed: 1 });
- }
- return result.filter((s) => s.endSec - s.startSec > 0.0001);
- }
-
/** Returns the underlying WebDemuxer instance, or null if not yet loaded. */
getDemuxer(): WebDemuxer | null {
return this.demuxer;
diff --git a/src/lib/exporter/timelineSegments.test.ts b/src/lib/exporter/timelineSegments.test.ts
new file mode 100644
index 000000000..be12062ee
--- /dev/null
+++ b/src/lib/exporter/timelineSegments.test.ts
@@ -0,0 +1,113 @@
+import { describe, expect, it } from "vitest";
+import type { SpeedRegion, TrimRegion } from "@/components/video-editor/types";
+import {
+ buildSpeedSegments,
+ computeKeepSegments,
+ maxTimelineSpeed,
+ splitBySpeed,
+} from "./timelineSegments";
+
+function trim(startMs: number, endMs: number): TrimRegion {
+ return { id: `t-${startMs}-${endMs}`, startMs, endMs };
+}
+
+function speed(startMs: number, endMs: number, value: number): SpeedRegion {
+ return { id: `s-${startMs}-${endMs}`, startMs, endMs, speed: value };
+}
+
+describe("computeKeepSegments", () => {
+ it("returns one full-duration segment when there are no trims", () => {
+ expect(computeKeepSegments(10)).toEqual([{ startSec: 0, endSec: 10 }]);
+ expect(computeKeepSegments(10, [])).toEqual([{ startSec: 0, endSec: 10 }]);
+ });
+
+ it("removes a middle trim, keeping the surrounding spans", () => {
+ expect(computeKeepSegments(10, [trim(2000, 4000)])).toEqual([
+ { startSec: 0, endSec: 2 },
+ { startSec: 4, endSec: 10 },
+ ]);
+ });
+
+ it("drops a leading trim", () => {
+ expect(computeKeepSegments(10, [trim(0, 3000)])).toEqual([{ startSec: 3, endSec: 10 }]);
+ });
+
+ it("drops a trailing trim that reaches the end", () => {
+ expect(computeKeepSegments(10, [trim(8000, 10000)])).toEqual([{ startSec: 0, endSec: 8 }]);
+ });
+
+ it("sorts unordered trims before collapsing", () => {
+ expect(computeKeepSegments(10, [trim(6000, 7000), trim(1000, 2000)])).toEqual([
+ { startSec: 0, endSec: 1 },
+ { startSec: 2, endSec: 6 },
+ { startSec: 7, endSec: 10 },
+ ]);
+ });
+});
+
+describe("splitBySpeed", () => {
+ const full: { startSec: number; endSec: number }[] = [{ startSec: 0, endSec: 10 }];
+
+ it("annotates every segment with speed 1 when no speed regions apply", () => {
+ expect(splitBySpeed(full)).toEqual([{ startSec: 0, endSec: 10, speed: 1 }]);
+ expect(splitBySpeed(full, [])).toEqual([{ startSec: 0, endSec: 10, speed: 1 }]);
+ });
+
+ it("carves a mid-segment speed region, leaving 1x gaps on both sides", () => {
+ expect(splitBySpeed(full, [speed(3000, 6000, 4)])).toEqual([
+ { startSec: 0, endSec: 3, speed: 1 },
+ { startSec: 3, endSec: 6, speed: 4 },
+ { startSec: 6, endSec: 10, speed: 1 },
+ ]);
+ });
+
+ it("clips a speed region to the keep-segment bounds", () => {
+ expect(splitBySpeed([{ startSec: 2, endSec: 8 }], [speed(0, 5000, 2)])).toEqual([
+ { startSec: 2, endSec: 5, speed: 2 },
+ { startSec: 5, endSec: 8, speed: 1 },
+ ]);
+ });
+
+ it("passes an extreme 100x speed through unclamped", () => {
+ expect(splitBySpeed(full, [speed(0, 10000, 100)])).toEqual([
+ { startSec: 0, endSec: 10, speed: 100 },
+ ]);
+ });
+
+ it("orders multiple regions and fills the gap between them at 1x", () => {
+ expect(splitBySpeed(full, [speed(6000, 8000, 3), speed(1000, 2000, 20)])).toEqual([
+ { startSec: 0, endSec: 1, speed: 1 },
+ { startSec: 1, endSec: 2, speed: 20 },
+ { startSec: 2, endSec: 6, speed: 1 },
+ { startSec: 6, endSec: 8, speed: 3 },
+ { startSec: 8, endSec: 10, speed: 1 },
+ ]);
+ });
+
+ it("drops sub-segments narrower than the minimum width", () => {
+ // A speed region ending a sliver before the segment end must not emit a 1x crumb.
+ const result = splitBySpeed(full, [speed(0, 9_999.95, 2)]);
+ expect(result).toEqual([{ startSec: 0, endSec: 9.99995, speed: 2 }]);
+ });
+});
+
+describe("buildSpeedSegments", () => {
+ it("composes trim removal and speed splitting", () => {
+ expect(buildSpeedSegments(10, [trim(2000, 4000)], [speed(5000, 7000, 50)])).toEqual([
+ { startSec: 0, endSec: 2, speed: 1 },
+ { startSec: 4, endSec: 5, speed: 1 },
+ { startSec: 5, endSec: 7, speed: 50 },
+ { startSec: 7, endSec: 10, speed: 1 },
+ ]);
+ });
+});
+
+describe("maxTimelineSpeed", () => {
+ it("returns 1 when nothing is sped up", () => {
+ expect(maxTimelineSpeed(buildSpeedSegments(10))).toBe(1);
+ });
+
+ it("reports the fastest segment", () => {
+ expect(maxTimelineSpeed(buildSpeedSegments(10, undefined, [speed(0, 5000, 32)]))).toBe(32);
+ });
+});
diff --git a/src/lib/exporter/timelineSegments.ts b/src/lib/exporter/timelineSegments.ts
new file mode 100644
index 000000000..e032de17b
--- /dev/null
+++ b/src/lib/exporter/timelineSegments.ts
@@ -0,0 +1,102 @@
+import type { SpeedRegion, TrimRegion } from "@/components/video-editor/types";
+
+export interface TimelineSegment {
+ startSec: number;
+ endSec: number;
+}
+
+export interface SpeedTimelineSegment extends TimelineSegment {
+ /** Playback speed multiplier for this span (1 = unchanged). */
+ speed: number;
+}
+
+// Sub-segments shorter than this (in seconds) are dropped after speed splitting so
+// zero-width slivers at region boundaries never reach the decoder/encoder.
+const MIN_SEGMENT_SEC = 0.0001;
+
+/**
+ * Converts trim regions into the source-time spans that should be kept, in order.
+ * Returns a single full-duration segment when no trim regions are present.
+ *
+ * Shared by the video decoder and the offline audio renderer so both derive the
+ * exact same output timeline (any divergence would desync audio from video).
+ */
+export function computeKeepSegments(
+ totalDuration: number,
+ trimRegions?: TrimRegion[],
+): TimelineSegment[] {
+ if (!trimRegions || trimRegions.length === 0) {
+ return [{ startSec: 0, endSec: totalDuration }];
+ }
+
+ const sorted = [...trimRegions].sort((a, b) => a.startMs - b.startMs);
+ const segments: TimelineSegment[] = [];
+ let cursor = 0;
+
+ for (const trim of sorted) {
+ const trimStart = trim.startMs / 1000;
+ const trimEnd = trim.endMs / 1000;
+ if (cursor < trimStart) {
+ segments.push({ startSec: cursor, endSec: trimStart });
+ }
+ cursor = trimEnd;
+ }
+
+ if (cursor < totalDuration) {
+ segments.push({ startSec: cursor, endSec: totalDuration });
+ }
+
+ return segments;
+}
+
+/**
+ * Splits keep-segments by overlapping speed regions, annotating each sub-segment
+ * with its playback speed multiplier (defaults to 1×). Regions are assumed
+ * non-overlapping; when they do overlap the earliest-starting one wins.
+ */
+export function splitBySpeed(
+ segments: TimelineSegment[],
+ speedRegions?: SpeedRegion[],
+): SpeedTimelineSegment[] {
+ if (!speedRegions || speedRegions.length === 0) {
+ return segments.map((s) => ({ ...s, speed: 1 }));
+ }
+
+ const result: SpeedTimelineSegment[] = [];
+ for (const segment of segments) {
+ const overlapping = speedRegions
+ .filter((sr) => sr.startMs / 1000 < segment.endSec && sr.endMs / 1000 > segment.startSec)
+ .sort((a, b) => a.startMs - b.startMs);
+
+ if (overlapping.length === 0) {
+ result.push({ ...segment, speed: 1 });
+ continue;
+ }
+
+ let cursor = segment.startSec;
+ for (const sr of overlapping) {
+ const srStart = Math.max(sr.startMs / 1000, segment.startSec);
+ const srEnd = Math.min(sr.endMs / 1000, segment.endSec);
+ if (cursor < srStart) result.push({ startSec: cursor, endSec: srStart, speed: 1 });
+ result.push({ startSec: srStart, endSec: srEnd, speed: sr.speed });
+ cursor = srEnd;
+ }
+ if (cursor < segment.endSec)
+ result.push({ startSec: cursor, endSec: segment.endSec, speed: 1 });
+ }
+ return result.filter((s) => s.endSec - s.startSec > MIN_SEGMENT_SEC);
+}
+
+/** Convenience: trim then speed-split in one call. */
+export function buildSpeedSegments(
+ totalDuration: number,
+ trimRegions?: TrimRegion[],
+ speedRegions?: SpeedRegion[],
+): SpeedTimelineSegment[] {
+ return splitBySpeed(computeKeepSegments(totalDuration, trimRegions), speedRegions);
+}
+
+/** Largest speed multiplier across the timeline's speed regions (1 when none apply). */
+export function maxTimelineSpeed(segments: SpeedTimelineSegment[]): number {
+ return segments.reduce((max, seg) => Math.max(max, seg.speed), 1);
+}
diff --git a/src/lib/exporter/videoExporter.test.ts b/src/lib/exporter/videoExporter.test.ts
index bd424548b..022766533 100644
--- a/src/lib/exporter/videoExporter.test.ts
+++ b/src/lib/exporter/videoExporter.test.ts
@@ -52,6 +52,16 @@ describe("isSourceCopyFastPathEligible", () => {
videoInfo,
),
).toBe(false);
+ // A 100× region must also block the copy path so its audio is re-rendered
+ // (offline time-stretch) rather than passed through untouched.
+ expect(
+ isSourceCopyFastPathEligible(
+ createConfig({
+ speedRegions: [{ id: "speed", startMs: 100, endMs: 200, speed: 100 }],
+ }),
+ videoInfo,
+ ),
+ ).toBe(false);
expect(
isSourceCopyFastPathEligible(
createConfig({
diff --git a/src/lib/exporter/videoExporter.ts b/src/lib/exporter/videoExporter.ts
index b89dfb74b..a1b67c5ff 100644
--- a/src/lib/exporter/videoExporter.ts
+++ b/src/lib/exporter/videoExporter.ts
@@ -516,6 +516,7 @@ export class VideoExporter {
this.config.speedRegions,
videoInfo.duration,
audioExportCodec,
+ this.config.frameRate,
);
}
}