Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Uploads: a trim picker with a waveform, handles and playback

Adarshd339e8cc8a7a
diff --git a/src/components/av/filmstrip.ts b/src/components/av/filmstrip.ts
new file mode 100644
index 00000000..2d988d8d
--- /dev/null
+++ b/src/components/av/filmstrip.ts
@@ -0,0 +1,61 @@
+"use client";
+
+/**
+ * Stills from a clip for a trim picker's strip: `count` frames spread over its length (or over `range`), read in this browser by seeking a
+ * hidden video (nothing is sent anywhere). Frames that can't be read (a format this browser can't show) are left out:
+ * an empty list means none could be.
+ */
+export async function filmstrip(src: string, seconds: number, count: number, height = 96, signal?: AbortSignal, range?: { from: number; to: number }): Promise<string[]> {
+ if (typeof document === "undefined" || !(seconds > 0)) return [];
+ const v = document.createElement("video");
+ v.muted = true;
+ v.preload = "auto";
+ v.playsInline = true;
+ v.crossOrigin = "anonymous";
+ const once = (ev: string, ms: number) =>
+ new Promise<boolean>((resolve) => {
+ const done = (ok: boolean) => {
+ clearTimeout(t);
+ v.removeEventListener(ev, onOk);
+ v.removeEventListener("error", onErr);
+ resolve(ok);
+ };
+ const onOk = () => done(true);
+ const onErr = () => done(false);
+ const t = setTimeout(() => done(false), ms);
+ v.addEventListener(ev, onOk);
+ v.addEventListener("error", onErr);
+ });
+ try {
+ const loaded = once("loadeddata", 15_000);
+ v.src = src;
+ if (!(await loaded) || !v.videoWidth) return [];
+ const h = height;
+ const w = Math.max(1, Math.round((v.videoWidth / v.videoHeight) * h));
+ const canvas = document.createElement("canvas");
+ canvas.width = w;
+ canvas.height = h;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return [];
+ const out: string[] = [];
+ for (let i = 0; i < count; i++) {
+ if (signal?.aborted) break;
+ const from = range?.from ?? 0;
+ const span = (range?.to ?? seconds) - from;
+ const at = Math.min(seconds - 0.05, from + ((i + 0.5) / count) * span);
+ const seeked = once("seeked", 5_000);
+ v.currentTime = Math.max(0, at);
+ if (!(await seeked)) continue;
+ try {
+ ctx.drawImage(v, 0, 0, w, h);
+ out.push(canvas.toDataURL("image/jpeg", 0.7));
+ } catch {
+ return out;
+ }
+ }
+ return out;
+ } finally {
+ v.removeAttribute("src");
+ v.load();
+ }
+}
diff --git a/src/components/av/fit-audio.ts b/src/components/av/fit-audio.ts
index c3db4ee5..d630d0f1 100644
--- a/src/components/av/fit-audio.ts
+++ b/src/components/av/fit-audio.ts
@@ -71,6 +71,60 @@ async function decode(data: ArrayBuffer): Promise<AudioBuffer> {
}
}
+/**
+ * The last file decoded, kept while its part is picked (the waveform) so the cut that follows doesn't decode it again.
+ * One at a time: a phone holds one decoded sound.
+ */
+let decoded: { src: Blob; audio: Promise<AudioBuffer> } | null = null;
+
+async function decodeBlob(src: Blob): Promise<AudioBuffer> {
+ if (decoded?.src !== src) {
+ decoded = null;
+ const audio = src.arrayBuffer().then(decode);
+ decoded = { src, audio };
+ audio.catch(() => {
+ if (decoded?.audio === audio) decoded = null;
+ });
+ }
+ return decoded.audio;
+}
+
+/** Forget the decoded sound (the picker closed). */
+export function forgetDecoded(src?: Blob) {
+ if (!src || decoded?.src === src) decoded = null;
+}
+
+/**
+ * The sound's loudness in `bars` steps (0 to 1, the loudest 1) for a waveform. Throws in plain words when the browser
+ * can't read it.
+ */
+export async function soundPeaks(src: Blob, bars: number): Promise<number[]> {
+ if (src.size > FIT_SOURCE_MAX_BYTES) throw unreadable();
+ const audio = await decodeBlob(src);
+ const data = Array.from({ length: Math.min(2, audio.numberOfChannels) }, (_, c) => audio.getChannelData(c));
+ const step = audio.length / bars;
+ const out: number[] = [];
+ for (let b = 0; b < bars; b++) {
+ const from = Math.floor(b * step);
+ const to = Math.min(audio.length, Math.floor((b + 1) * step));
+ // Loudness (RMS) from every few samples: enough for a bar's height.
+ const stride = Math.max(1, Math.floor((to - from) / 2000));
+ let sum = 0;
+ let count = 0;
+ for (const ch of data) {
+ for (let i = from; i < to; i += stride) {
+ sum += ch[i] * ch[i];
+ count++;
+ }
+ }
+ out.push(Math.sqrt(sum / Math.max(1, count)));
+ }
+ // Scaled to the loud parts (not the one loudest moment), so a quiet stretch reads as quiet.
+ const sorted = [...out].sort((a, b) => a - b);
+ const top = Math.max(sorted[Math.floor(sorted.length * 0.98)] ?? 0, 1e-4);
+ return out.map((x) => Math.min(1, x / top));
+}
+
/** The encoder: a worker when one starts, else the main thread (yielding between blocks). */
interface Encoder {
push(block: Float32Array[]): Promise<void>;
@@ -150,7 +204,7 @@ function mainEncoder(channels: number, kbps: number): Encoder {
*/
export async function toMp3(src: Blob, opts: { kbps: number; name?: string; from?: number; to?: number; signal?: AbortSignal }): Promise<File> {
if (src.size > FIT_SOURCE_MAX_BYTES) throw new Error(`The largest file this takes is ${Math.round(FIT_SOURCE_MAX_BYTES / 1024 / 1024)} MB. Use a shorter clip`);
- const audio = await decode(await src.arrayBuffer());
+ const audio = await decodeBlob(src);
stopIfAsked(opts.signal);
if (audio.duration > FIT_READ_MAX_SECONDS + 1) throw new Error("This file is too long to cut here: use a shorter clip");
const a = Math.max(0, Math.round((opts.from ?? 0) * audio.sampleRate));
@@ -169,5 +223,6 @@ export async function toMp3(src: Blob, opts: { kbps: number; name?: string; from
return new File(parts as BlobPart[], mp3Name(opts.name), { type: "audio/mpeg" });
} finally {
enc.close();
+ forgetDecoded(src);
}
}
diff --git a/src/components/av/fit-upload.tsx b/src/components/av/fit-upload.tsx
index 33ce3094..db271c46 100644
--- a/src/components/av/fit-upload.tsx
+++ b/src/components/av/fit-upload.tsx
@@ -1,15 +1,16 @@
"use client";
-import { Loader2, Scissors, X } from "lucide-react";
+import { Loader2 } from "lucide-react";
import { nanoid } from "nanoid";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { SlotValue } from "@/components/studio/media-slot";
import { useAskBeforeUpload, useIsGuest } from "@/lib/api";
-import { clock, convertedLine, fitSourceKind, FIT_SOURCE_MAX_BYTES, mp3Kbps, planAudioFit, type AudioFitRule, type FitPlan } from "@/lib/av/fit-upload";
+import { convertedLine, fitSourceKind, FIT_SOURCE_MAX_BYTES, mp3Kbps, planAudioFit, type AudioFitRule, type FitPlan } from "@/lib/av/fit-upload";
import { songFormat } from "@/lib/lyrics";
import { postFile } from "@/lib/upload";
import { cn } from "@/lib/utils";
-import { readSeconds, toMp3 } from "./fit-audio";
+import { forgetDecoded, readSeconds, toMp3 } from "./fit-audio";
+import { TrimPicker } from "./trim-picker";
import { useUploadSwitches } from "./use-upload-switches";
/**
@@ -23,7 +24,7 @@ import { useUploadSwitches } from "./use-upload-switches";
* its id).
*/
-type Offer = { source: Blob | string; name?: string; seconds: number; max: number; line: string; stored?: SlotValue };
+type Offer = { source: Blob | string; name?: string; seconds: number; max: number; min?: number; line: string; stored?: SlotValue };
/** A part a hair shorter than the tool's limit, so the file's own header never reads a frame over it. */
const MARGIN = 0.5;
@@ -59,7 +60,6 @@ export function useFitUpload({
const [busy, setBusy] = useState(false);
const [error, setError] = useState<{ line: string; at: string | null } | null>(null);
const [offer, setOffer] = useState<Offer | null>(null);
- const [start, setStart] = useState(0);
const [made, setMade] = useState<Set<string>>(() => new Set());
const failed = useRef(new Set<string>());
const latest = useRef(value);
@@ -176,8 +176,7 @@ export function useFitUpload({
if (plan.kind === "trim") {
if (stored) offered.current.add(stored.ref);
else cb.current.setValue(null);
- setStart(0);
- return setOffer({ source, name, seconds: plan.seconds, max: plan.max, line: plan.line, stored });
+ return setOffer({ source, name, seconds: plan.seconds, max: plan.max, min: r.minSeconds, line: plan.line, stored });
}
if (stored) convertStored(stored, { kbps: plan.kbps });
else convertFile(source as Blob, name, { kbps: plan.kbps });
@@ -188,7 +187,7 @@ export function useFitUpload({
/** True when this step takes the file: any sound file while a rule is on, and a video file (its sound) while converting is. */
const wants = useCallback((f: File) => {
const kind = fitSourceKind(f);
- return !!rule && (kind === "audio" || (kind === "video" && rule.convert !== false));
+ return !!rule && (kind === "audio" || (kind === "video" && rule.convert !== false && rule.fromVideo !== false));
}, [rule]);
/** A file picked, dropped or pasted: its length read from its header first (nothing else is read), then fitted. */
@@ -248,15 +247,23 @@ export function useFitUpload({
if (offerGone) setOffer(null);
}
- const usePart = useCallback(() => {
- const r = cb.current.rule;
- if (!offer || !r || askFirst()) return;
- const from = Math.min(start, Math.max(0, offer.seconds - offer.max));
- const opts = { kbps: mp3Kbps(offer.max, r.outMaxBytes) ?? 96, from, to: from + offer.max - MARGIN };
+ const usePart = useCallback(
+ (from: number, to: number) => {
+ const r = cb.current.rule;
+ if (!offer || !r || askFirst()) return;
+ const end = Math.min(to, from + offer.max - MARGIN);
+ const opts = { kbps: mp3Kbps(end - from, r.outMaxBytes) ?? 96, from, to: end };
+ setOffer(null);
+ if (offer.stored) convertStored(offer.stored, opts);
+ else convertFile(offer.source as Blob, offer.name, opts);
+ },
+ [offer, askFirst, convertFile, convertStored],
+ );
+
+ const cancelOffer = useCallback((o: Offer) => {
+ if (o.source instanceof Blob) forgetDecoded(o.source);
setOffer(null);
- if (offer.stored) convertStored(offer.stored, opts);
- else convertFile(offer.source as Blob, offer.name, opts);
- }, [offer, start, askFirst, convertFile, convertStored]);
+ }, []);
// A file refused before it landed is said while the slot stays empty; a stored one's while it is in the slot.
const shownError = error && (error.at === null ? !value : error.at === landed) ? error.line : null;
@@ -266,12 +273,12 @@ export function useFitUpload({
on: !!rule,
wants,
/** The slot's file picker while the step is on: sound, and video while converting is on. */
- accept: rule ? (rule.convert !== false ? "audio/*,video/*" : "audio/*") : undefined,
+ accept: rule ? (rule.convert !== false && rule.fromVideo !== false ? "audio/*,video/*" : "audio/*") : undefined,
take,
busy,
line,
failedNow: !!shownError && !busy,
- offer: offer && !offerGone ? { ...offer, start, setStart, use: usePart, cancel: () => setOffer(null) } : null,
+ offer: offer && !offerGone ? { ...offer, use: usePart, cancel: () => cancelOffer(offer) } : null,
};
}
@@ -279,7 +286,6 @@ export function useFitUpload({
export function FitUploadNote({ fit, className }: { fit: ReturnType<typeof useFitUpload>; className?: string }) {
const o = fit.offer;
if (!fit.line && !o) return null;
- const last = o ? Math.max(0, Math.floor(o.seconds - o.max)) : 0;
return (
<div className={cn("space-y-1.5 pb-2 text-xs text-muted-foreground", className)}>
{fit.line && (
@@ -288,29 +294,7 @@ export function FitUploadNote({ fit, className }: { fit: ReturnType<typeof useFi
{fit.line}
</p>
)}
- {o && (
- <div className="space-y-1.5 rounded-xl border bg-muted/40 p-2.5">
- <p className="text-foreground">{o.line}</p>
- {last > 0 && (
- <label className="flex items-center gap-2">
- <span className="w-24 shrink-0 tabular-nums">
- {clock(Math.min(o.start, last))}–{clock(Math.min(o.start, last) + o.max)}
- </span>
- <input type="range" min={0} max={last} step={1} value={Math.min(o.start, last)} onChange={(e) => o.setStart(Number(e.target.value))} aria-label="Where the part starts" className="h-9 min-w-0 flex-1 accent-primary" />
- </label>
- )}
- <div className="flex flex-wrap gap-2">
- <button type="button" onClick={o.use} className="inline-flex min-h-9 items-center gap-1.5 rounded-full bg-foreground px-3.5 font-medium text-background">
- <Scissors className="size-3.5" />
- Use this part
- </button>
- <button type="button" onClick={o.cancel} className="inline-flex min-h-9 items-center gap-1.5 rounded-full border px-3.5 font-medium text-foreground hover:bg-accent">
- <X className="size-3.5" />
- Cancel
- </button>
- </div>
- </div>
- )}
+ {o && <TrimPicker source={o.source} kind="audio" seconds={o.seconds} max={o.max} min={o.min} line={o.line} onUse={o.use} onCancel={o.cancel} />}
</div>
);
}
diff --git a/src/components/av/trim-picker.tsx b/src/components/av/trim-picker.tsx
new file mode 100644
index 00000000..7641e05c
--- /dev/null
+++ b/src/components/av/trim-picker.tsx
@@ -0,0 +1,467 @@
+"use client";
+
+import { Loader2, Pause, Play, Scissors, X } from "lucide-react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { keyframeAtOrBefore } from "@/lib/av/mp4-cut";
+import { cn } from "@/lib/utils";
+import { filmstrip } from "./filmstrip";
+import { soundPeaks } from "./fit-audio";
+
+/**
+ * Pick the part of a sound or a clip to use, when it is longer than a tool takes. Phones first:
+ * - a waveform (a sound) or a strip of stills (a clip), with a window of the allowed length to drag, and big handles at
+ * both ends to make it shorter (never longer than the tool takes, never shorter than it needs);
+ * - a long file shows the stretch around the window, with a bar under it for the whole file (tap it to go there);
+ * - Play plays just the chosen part (a clip's in the preview above);
+ * - the start and end times, and the part's length;
+ * - "Use this part" and "Cancel".
+ * A clip's part starts on a key frame (`keyframes`): the start snaps to the one at or before it when it is let go.
+ * Arrow keys move each handle and the window by a second (Shift: ten).
+ */
+
+export interface TrimPickerProps {
+ /** The file: one in this browser, or a stored file's address. */
+ source: Blob | string;
+ kind: "audio" | "video";
+ /** Its whole length, in seconds. */
+ seconds: number;
+ /** The longest part the tool takes, and the shortest it needs. */
+ max: number;
+ min?: number;
+ /** What is asked, in a line ("This one is 4:12. Remix takes up to 3:00: pick the part to use"). */
+ line: string;
+ /** Where a part can start (a clip's key frames), in seconds. */
+ keyframes?: number[];
+ /** The button's words ("Use this part"). */
+ useLabel?: string;
+ busy?: boolean;
+ onUse: (from: number, to: number) => void;
+ onCancel: () => void;
+ className?: string;
+}
+
+/** Bars over the whole file (a long one shows a stretch of them). */
+const BARS = 1200;
+/** The track shows at most this many window lengths, so the window is never a sliver. */
+const ZOOM = 4;
+
+/** "75.3" -> "1:15" (or "1:15.3" when tenths matter). */
+export function stamp(t: number, tenths = false): string {
+ const s = Math.max(0, t);
+ const m = Math.floor(s / 60);
+ const rest = s - m * 60;
+ const sec = tenths ? rest.toFixed(1).padStart(4, "0") : String(Math.floor(rest + 1e-6)).padStart(2, "0");
+ return `${m}:${sec}`;
+}
+
+/** "30 s", "2 min 05 s". */
+function lengthWords(t: number, tenths: boolean): string {
+ if (t < 60) return `${tenths ? t.toFixed(1) : Math.round(t)} s`;
+ const m = Math.floor(t / 60);
+ return `${m} min ${String(Math.round(t - m * 60)).padStart(2, "0")} s`;
+}
+
+type Drag = { mode: "start" | "end" | "move"; grab: number } | null;
+
+export function TrimPicker({ source, kind, seconds, max, min = 0, line, keyframes, useLabel = "Use this part", busy, onUse, onCancel, className }: TrimPickerProps) {
+ const longest = Math.min(max, seconds);
+ const shortest = Math.min(Math.max(0.5, min), longest);
+ const [start, setStart] = useState(0);
+ const [len, setLen] = useState(longest);
+ const end = start + len;
+ const tenths = longest < 60;
+ // The stretch the track shows: all of a short file, a few window lengths of a long one.
+ const span = seconds <= longest * ZOOM ? seconds : longest * ZOOM;
+ const zoomed = span < seconds;
+ const [view, setView] = useState(0);
+ // Keep the window in view.
+ const shownFrom = Math.min(Math.max(view, end - span), start, Math.max(0, seconds - span));
+ const viewFrom = Math.max(0, shownFrom);
+ if (viewFrom !== view) setView(viewFrom);
+ const viewTo = viewFrom + span;
+
+ // The file's address for the players (a file in this browser gets one of its own while the picker is open).
+ const [url, setUrl] = useState<string | null>(typeof source === "string" ? source : null);
+ useEffect(() => {
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- a file in this browser gets an address while the picker is open
+ if (typeof source === "string") return setUrl(source);
+ const u = URL.createObjectURL(source);
+ setUrl(u);
+ return () => URL.revokeObjectURL(u);
+ }, [source]);
+
+ // A sound's waveform.
+ const [peaks, setPeaks] = useState<number[] | null>(null);
+ const [peaksFailed, setPeaksFailed] = useState(false);
+ useEffect(() => {
+ if (kind !== "audio") return;
+ let gone = false;
+ void (async () => {
+ try {
+ const blob = typeof source === "string" ? await (await fetch(source)).blob() : source;
+ const p = await soundPeaks(blob, BARS);
+ if (!gone) setPeaks(p);
+ } catch {
+ if (!gone) setPeaksFailed(true);
+ }
+ })();
+ return () => {
+ gone = true;
+ };
+ }, [kind, source]);
+
+ // A clip's stills, for the stretch shown (again once a long one's stretch settles).
+ const [frames, setFrames] = useState<string[] | null>(null);
+ const [framesFor, setFramesFor] = useState<string | null>(null);
+ const stripKey = `${Math.round(viewFrom * 10)}`;
+ useEffect(() => {
+ if (kind !== "video" || !url) return;
+ const c = new AbortController();
+ const t = setTimeout(async () => {
+ const shots = await filmstrip(url, seconds, 8, 96, c.signal, zoomed ? { from: viewFrom, to: viewFrom + span } : undefined);
+ if (!c.signal.aborted) {
+ setFrames(shots);
+ setFramesFor(stripKey);
+ }
+ }, zoomed && framesFor !== null ? 350 : 0);
+ return () => {
+ clearTimeout(t);
+ c.abort();
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [kind, url, seconds, stripKey]);
+
+ // Playing the part.
+ const media = useRef<HTMLAudioElement & HTMLVideoElement>(null);
+ const [playing, setPlaying] = useState(false);
+ const [head, setHead] = useState<number | null>(null);
+ const raf = useRef(0);
+ const stop = useCallback(() => {
+ cancelAnimationFrame(raf.current);
+ media.current?.pause();
+ setPlaying(false);
+ setHead(null);
+ }, []);
+ useEffect(() => () => cancelAnimationFrame(raf.current), []);
+ const range = useRef({ start, end });
+ useEffect(() => {
+ range.current = { start, end };
+ }, [start, end]);
+ const play = useCallback(async () => {
+ const el = media.current;
+ if (!el) return;
+ if (playing) return stop();
+ el.currentTime = range.current.start;
+ try {
+ await el.play();
+ } catch {
+ return;
+ }
+ setPlaying(true);
+ const tick = () => {
+ const now = el.currentTime;
+ if (now >= range.current.end || el.paused || el.ended) {
+ el.pause();
+ el.currentTime = range.current.start;
+ setPlaying(false);
+ setHead(null);
+ return;
+ }
+ setHead(now);
+ raf.current = requestAnimationFrame(tick);
+ };
+ raf.current = requestAnimationFrame(tick);
+ }, [playing, stop]);
+ // A clip's preview shows the part's first frame while it isn't playing.
+ useEffect(() => {
+ const el = media.current;
+ if (kind !== "video" || !el || playing) return;
+ const t = setTimeout(() => {
+ if (el.readyState >= 1) el.currentTime = start + 0.01;
+ }, 60);
+ return () => clearTimeout(t);
+ }, [kind, start, playing, url]);
+
+ // Moving the window and its ends.
+ const set = useCallback(
+ (s: number, l: number) => {
+ // Whole seconds (tenths for a short part), as the times say them.
+ const q = tenths ? 10 : 1;
+ const L = Math.min(longest, Math.max(shortest, Math.round(l * q) / q));
+ setLen(L);
+ setStart(Math.min(Math.max(0, Math.round(s * q) / q), Math.max(0, seconds - L)));
+ },
+ [longest, shortest, seconds, tenths],
+ );
+ const snap = useCallback(() => {
+ if (!keyframes?.length) return;
+ setStart((s) => {
+ const k = keyframeAtOrBefore({ keyframes }, s + 1e-3);
+ return k;
+ });
+ }, [keyframes]);
+
+ const track = useRef<HTMLDivElement>(null);
+ const drag = useRef<Drag>(null);
+ const timeAt = (clientX: number) => {
+ const r = track.current!.getBoundingClientRect();
+ return viewFrom + ((clientX - r.left) / Math.max(1, r.width)) * span;
+ };
+ const onDown = (mode: "start" | "end" | "move" | "track", e: React.PointerEvent) => {
+ if (busy) return;
+ e.preventDefault();
+ e.stopPropagation();
+ stop();
+ const t = timeAt(e.clientX);
+ if (mode === "track") {
+ // A tap beside the window brings it there (centred), and the drag goes on from there.
+ const s = Math.min(Math.max(0, t - len / 2), seconds - len);
+ set(s, len);
+ drag.current = { mode: "move", grab: t - s };
+ } else drag.current = { mode, grab: mode === "move" ? t - start : 0 };
+ track.current?.setPointerCapture(e.pointerId);
+ };
+ const onMove = (e: React.PointerEvent) => {
+ const d = drag.current;
+ if (!d) return;
+ const t = timeAt(e.clientX);
+ if (d.mode === "move") set(t - d.grab, len);
+ else if (d.mode === "start") {
+ const s = Math.min(Math.max(t, end - longest, 0), end - shortest);
+ set(s, end - s);
+ } else {
+ const e2 = Math.min(Math.max(t, start + shortest), start + longest, seconds);
+ set(start, e2 - start);
+ }
+ };
+ const onUp = (e: React.PointerEvent) => {
+ if (!drag.current) return;
+ drag.current = null;
+ track.current?.releasePointerCapture?.(e.pointerId);
+ snap();
+ };
+ const keys = (mode: "start" | "end" | "move", e: React.KeyboardEvent) => {
+ const step = (e.shiftKey ? 10 : 1) * (e.key === "ArrowLeft" || e.key === "ArrowDown" ? -1 : e.key === "ArrowRight" || e.key === "ArrowUp" ? 1 : 0);
+ const edge = e.key === "Home" ? -Infinity : e.key === "End" ? Infinity : 0;
+ if (!step && !edge) return;
+ e.preventDefault();
+ stop();
+ const by = edge || step;
+ if (mode === "move") set(start + by, len);
+ else if (mode === "start") {
+ const s = Math.min(Math.max(start + by, end - longest, 0), end - shortest);
+ set(s, end - s);
+ } else {
+ const e2 = Math.min(Math.max(end + by, start + shortest), start + longest, seconds);
+ set(start, e2 - start);
+ }
+ if (mode !== "end") requestAnimationFrame(snap);
+ };
+
+ // Where things sit on the track, in %.
+ const pct = (t: number) => ((t - viewFrom) / span) * 100;
+ const left = pct(start);
+ const right = 100 - pct(end);
+ const shownBars = useMemo(() => {
+ if (!peaks) return null;
+ const a = Math.floor((viewFrom / seconds) * peaks.length);
+ const b = Math.ceil((viewTo / seconds) * peaks.length);
+ const slice = peaks.slice(a, b);
+ // About 70 bars across, whatever the stretch.
+ const every = Math.max(1, Math.round(slice.length / 70));
+ const out: number[] = [];
+ for (let i = 0; i < slice.length; i += every) out.push(Math.max(...slice.slice(i, i + every)));
+ return out;
+ }, [peaks, viewFrom, viewTo, seconds]);
+
+ const loading = kind === "audio" ? !peaks && !peaksFailed : frames === null;
+ const playLabel = playing ? "Stop" : "Play this part";
+
+ return (
+ <div className={cn("space-y-3 rounded-2xl border bg-card p-3 text-foreground shadow-sm sm:p-4", className)} data-trim-picker>
+ <p className="text-[13px] leading-snug text-foreground">{line}</p>
+
+ {kind === "video" && url && (
+ <div className="relative overflow-hidden rounded-xl bg-black">
+ <video ref={media} src={url} playsInline preload="auto" className="mx-auto block max-h-[38vh] w-full object-contain" onEnded={stop} />
+ </div>
+ )}
+ {kind === "audio" && url && <audio ref={media} src={url} preload="auto" onEnded={stop} className="hidden" />}
+
+ <div className="space-y-2">
+ <div
+ ref={track}
+ className="relative h-16 touch-none rounded-xl bg-muted select-none"
+ onPointerDown={(e) => onDown("track", e)}
+ onPointerMove={onMove}
+ onPointerUp={onUp}
+ onPointerCancel={onUp}
+ >
+ {/* The file: its waveform, or a strip of stills. */}
+ <div className="absolute inset-0 overflow-hidden rounded-xl">
+ {kind === "audio" && shownBars && <Bars bars={shownBars} className="text-muted-foreground/40" />}
+ {/* The part's own tint. */}
+ <div className="pointer-events-none absolute inset-y-0 bg-primary/10" style={{ left: `${left}%`, right: `${right}%` }} />
+ {kind === "audio" && shownBars && <Bars bars={shownBars} className="text-primary" style={{ clipPath: `inset(0 ${right}% 0 ${left}%)` }} />}
+ {kind === "video" && frames && frames.length > 0 && (
+ <div className="flex h-full">
+ {frames.map((f, i) => (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img key={i} src={f} alt="" draggable={false} className="h-full min-w-0 flex-1 object-cover" />
+ ))}
+ </div>
+ )}
+ {loading && <div className="absolute inset-0 animate-pulse bg-gradient-to-r from-muted via-muted-foreground/10 to-muted" />}
+ {/* Outside the part: dimmed. */}
+ <div className="pointer-events-none absolute inset-y-0 left-0 bg-background/65" style={{ width: `${Math.max(0, left)}%` }} />
+ <div className="pointer-events-none absolute inset-y-0 right-0 bg-background/65" style={{ width: `${Math.max(0, right)}%` }} />
+ </div>
+
+ {/* The part: drag it, or its ends. */}
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label="Move the part"
+ aria-valuemin={0}
+ aria-valuemax={Math.max(0, Math.round(seconds - len))}
+ aria-valuenow={Math.round(start)}
+ aria-valuetext={`${stamp(start, tenths)} to ${stamp(end, tenths)}`}
+ className="absolute inset-y-0 cursor-grab rounded-xl border-[3px] border-primary outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 active:cursor-grabbing"
+ style={{ left: `${left}%`, right: `${right}%` }}
+ onPointerDown={(e) => onDown("move", e)}
+ onKeyDown={(e) => keys("move", e)}
+ >
+ {head !== null && <span className="pointer-events-none absolute inset-y-1 w-0.5 rounded-full bg-foreground" style={{ left: `${((head - start) / Math.max(0.01, len)) * 100}%` }} />}
+ </div>
+ <Handle side="start" at={left} label="Start of the part" value={start} text={stamp(start, tenths)} onPointerDown={(e) => onDown("start", e)} onKeyDown={(e) => keys("start", e)} max={seconds} />
+ <Handle side="end" at={100 - right} label="End of the part" value={end} text={stamp(end, tenths)} onPointerDown={(e) => onDown("end", e)} onKeyDown={(e) => keys("end", e)} max={seconds} />
+ </div>
+
+ {zoomed && (
+ <div
+ className="relative h-2.5 touch-none rounded-full bg-muted"
+ aria-hidden
+ onPointerDown={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ const t = ((e.clientX - r.left) / r.width) * seconds;
+ stop();
+ set(t - len / 2, len);
+ requestAnimationFrame(snap);
+ }}
+ >
+ <span className="absolute inset-y-0 rounded-full bg-muted-foreground/25" style={{ left: `${(viewFrom / seconds) * 100}%`, width: `${(span / seconds) * 100}%` }} />
+ <span className="absolute inset-y-0 rounded-full bg-primary" style={{ left: `${(start / seconds) * 100}%`, width: `${Math.max(1.5, (len / seconds) * 100)}%` }} />
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-3">
+ <button
+ type="button"
+ onClick={() => void play()}
+ disabled={busy || !url}
+ aria-label={playLabel}
+ title={playLabel}
+ className="inline-flex size-11 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground shadow-sm transition-transform active:scale-95 disabled:opacity-50"
+ >
+ {playing ? <Pause className="size-4.5 fill-current" /> : <Play className="ml-0.5 size-4.5 fill-current" />}
+ </button>
+ <div className="min-w-0 flex-1 leading-tight">
+ <p className="text-[15px] font-medium tabular-nums" aria-live="polite">
+ {stamp(start, tenths)} – {stamp(end, tenths)}
+ </p>
+ <p className="text-[12px] text-muted-foreground tabular-nums">
+ {lengthWords(len, tenths)} of {stamp(seconds)}
+ {keyframes?.length ? " · starts on a key frame" : ""}
+ </p>
+ </div>
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ <button
+ type="button"
+ onClick={() => {
+ stop();
+ onUse(start, end);
+ }}
+ disabled={busy}
+ className="inline-flex min-h-11 flex-1 items-center justify-center gap-1.5 rounded-full bg-foreground px-4 text-[14px] font-medium text-background disabled:opacity-60 sm:flex-none"
+ >
+ {busy ? <Loader2 className="size-4 animate-spin" /> : <Scissors className="size-4" />}
+ {useLabel}
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ stop();
+ onCancel();
+ }}
+ className="inline-flex min-h-11 items-center justify-center gap-1.5 rounded-full border px-4 text-[14px] font-medium text-foreground hover:bg-accent"
+ >
+ <X className="size-4" />
+ Cancel
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function Bars({ bars, className, style }: { bars: number[]; className?: string; style?: React.CSSProperties }) {
+ return (
+ <svg viewBox={`0 0 ${bars.length} 100`} preserveAspectRatio="none" className={cn("pointer-events-none absolute inset-x-2 inset-y-0 h-full w-[calc(100%-1rem)]", className)} style={style} aria-hidden>
+ {bars.map((p, i) => {
+ const h = 8 + p * 76;
+ return <rect key={i} x={i + 0.28} width={0.44} y={50 - h / 2} height={h} rx={0.22} fill="currentColor" />;
+ })}
+ </svg>
+ );
+}
+
+function Handle({
+ side,
+ at,
+ label,
+ value,
+ text,
+ max,
+ onPointerDown,
+ onKeyDown,
+}: {
+ side: "start" | "end";
+ at: number;
+ label: string;
+ value: number;
+ text: string;
+ max: number;
+ onPointerDown: (e: React.PointerEvent) => void;
+ onKeyDown: (e: React.KeyboardEvent) => void;
+}) {
+ return (
+ <div
+ role="slider"
+ tabIndex={0}
+ aria-label={label}
+ aria-valuemin={0}
+ aria-valuemax={Math.round(max)}
+ aria-valuenow={Math.round(value)}
+ aria-valuetext={text}
+ onPointerDown={onPointerDown}
+ onKeyDown={onKeyDown}
+ // A 44 px target, centred on the window's edge; the bar it shows sits inside the window.
+ className={cn(
+ "group absolute inset-y-[-6px] z-10 flex w-11 cursor-ew-resize items-center outline-none",
+ side === "start" ? "-translate-x-[14px] justify-start pl-[11px]" : "-translate-x-[30px] justify-end pr-[11px]",
+ )}
+ style={{ left: `${at}%` }}
+ >
+ <span
+ className={cn(
+ "flex h-full w-[14px] items-center justify-center bg-primary shadow-md group-focus-visible:ring-2 group-focus-visible:ring-ring",
+ side === "start" ? "rounded-l-xl" : "rounded-r-xl",
+ )}
+ >
+ <span className="h-6 w-[3px] rounded-full bg-primary-foreground/90" />
+ </span>
+ </div>
+ );
+}
diff --git a/src/lib/av/fit-upload.ts b/src/lib/av/fit-upload.ts
index fc630751..631867b9 100644
--- a/src/lib/av/fit-upload.ts
+++ b/src/lib/av/fit-upload.ts
@@ -36,6 +36,8 @@ export interface AudioFitRule {
*/
convert?: boolean;
trim?: boolean;
+ /** False: a video file is not this slot's (its sound isn't taken from it). */
+ fromVideo?: boolean;
}
/** The largest file read in the browser to fit it: the app's own upload limit (MAX_MB in media-slot.tsx, /api/uploads). */
@@ -113,7 +115,7 @@ export function planAudioFit(rule: AudioFitRule, file: { format?: string; bytes?
function planAll(rule: AudioFitRule, file: { format?: string; bytes?: number; seconds?: number; video?: boolean }): FitPlan {
const tooLong = !!rule.maxSeconds && !!file.seconds && file.seconds > rule.maxSeconds;
- const needs = !!file.video || (!!file.format && !rule.formats.includes(file.format)) || (!!rule.maxBytes && !!file.bytes && file.bytes > rule.maxBytes);
+ const needs = !!file.video || (!!file.format && !rule.formats.includes(file.format) && !rule.formats.includes("*")) || (!!rule.maxBytes && !!file.bytes && file.bytes > rule.maxBytes);
if (!needs && !tooLong) return { kind: "keep" };
if (file.bytes && file.bytes > FIT_SOURCE_MAX_BYTES) {
return { kind: "refuse", line: `The largest file this takes is ${Math.round(FIT_SOURCE_MAX_BYTES / 1024 / 1024)} MB. Use a shorter clip` };
diff --git a/src/lib/av/mp4-cut.ts b/src/lib/av/mp4-cut.ts
new file mode 100644
index 00000000..45e5bb6e
--- /dev/null
+++ b/src/lib/av/mp4-cut.ts
@@ -0,0 +1,473 @@
+/**
+ * A part of an MP4 or MOV clip, cut without encoding it again: the samples from a key frame on are copied as they are,
+ * with new sample tables, so the picture and the sound keep their quality and the cut takes a moment. It starts on the
+ * key frame at or before the time asked for (a clip can only start on one), and keeps the length asked for from there.
+ *
+ * Reads only the file's header boxes (`read`), and says which byte ranges of the original make the new file's sound and
+ * picture, so a browser builds it from slices of the file it has (a Blob) without holding the clip in memory.
+ *
+ * Takes a plain (not fragmented) ISO-BMFF file with a picture or sound track. Anything else (WebM, a fragmented MP4, a
+ * QuickTime file with raw PCM sound) gives null, and the caller says so in words.
+ */
+
+export type ReadRange = (start: number, end: number) => Promise<Uint8Array>;
+
+/** A piece of the new file: bytes made here, or a range of the original. */
+export type CutPart = Uint8Array | { start: number; end: number };
+
+interface Track {
+ /** The trak box's children, kept to copy (tkhd, mdia's hdlr, minf's own boxes). */
+ tkhd: Uint8Array;
+ mdhd: Uint8Array;
+ hdlr: Uint8Array;
+ /** minf's children other than stbl (vmhd/smhd, dinf), as they are. */
+ minfRest: Uint8Array[];
+ stsd: Uint8Array;
+ handler: string;
+ timescale: number;
+ /** The track's edit: the delay before it (movie timescale) and where in its media it starts (media timescale). */
+ edit: { delay: number; mediaTime: number } | null;
+ sizes: Uint32Array;
+ offsets: Float64Array;
+ dts: Float64Array;
+ durs: Uint32Array;
+ /** Composition offsets, when the track has them. */
+ ctts: Int32Array | null;
+ cttsVersion: number;
+ /** Key frames (sample indexes), when the track lists them (null: every sample is one). */
+ sync: Uint8Array | null;
+ sdi: Uint32Array;
+}
+
+export interface Mp4Index {
+ /** The clip's length in seconds. */
+ seconds: number;
+ /** Where its key frames are, in seconds (where a part can start). */
+ keyframes: number[];
+ hasVideo: boolean;
+ hasAudio: boolean;
+ /** @internal */
+ ftyp: Uint8Array | null;
+ /** @internal moov's own boxes to copy (udta, meta) */
+ moovRest: Uint8Array[];
+ /** @internal */
+ mvhd: Uint8Array;
+ /** @internal */
+ movieTimescale: number;
+ /** @internal */
+ tracks: Track[];
+}
+
+/** The most samples a track may list: past it (raw PCM sound in a MOV lists one per sound frame), no cut here. */
+const MAX_SAMPLES = 2_000_000;
+/** The largest header (moov) read: a clip of up to 200 MB has one of a few MB. */
+const MAX_MOOV = 64 * 1024 * 1024;
+
+const fourcc = (b: Uint8Array, o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]);
+const view = (b: Uint8Array) => new DataView(b.buffer, b.byteOffset, b.byteLength);
+
+/** The boxes inside `b` (from `from`), each with its type and its bytes (header included). */
+function children(b: Uint8Array, from = 0): { type: string; box: Uint8Array; body: Uint8Array }[] {
+ const out: { type: string; box: Uint8Array; body: Uint8Array }[] = [];
+ const v = view(b);
+ let at = from;
+ while (at + 8 <= b.length) {
+ let size = v.getUint32(at);
+ const type = fourcc(b, at + 4);
+ let head = 8;
+ if (size === 1) {
+ if (at + 16 > b.length) break;
+ size = Number(v.getBigUint64(at + 8));
+ head = 16;
+ } else if (size === 0) size = b.length - at;
+ if (size < head || at + size > b.length) throw new Error("bad box");
+ out.push({ type, box: b.subarray(at, at + size), body: b.subarray(at + head, at + size) });
+ at += size;
+ }
+ return out;
+}
+
+const child = (b: Uint8Array, type: string) => children(b).find((c) => c.type === type);
+
+/** A full box's version, and its body after version and flags. */
+const full = (body: Uint8Array) => ({ version: body[0], rest: body.subarray(4), v: view(body.subarray(4)) });
+
+function parseTrack(trak: Uint8Array, movieTimescale: number): Track | null {
+ const tkhd = child(trak, "tkhd");
+ const mdia = child(trak, "mdia");
+ if (!tkhd || !mdia) return null;
+ const mdhd = child(mdia.body, "mdhd");
+ const hdlr = child(mdia.body, "hdlr");
+ const minf = child(mdia.body, "minf");
+ if (!mdhd || !hdlr || !minf) return null;
+ const handler = fourcc(hdlr.body, 8);
+ if (handler !== "vide" && handler !== "soun") return null;
+ const m = full(mdhd.body);
+ const timescale = m.version === 1 ? m.v.getUint32(16) : m.v.getUint32(8);
+ const minfKids = children(minf.body);
+ const stbl = minfKids.find((c) => c.type === "stbl");
+ if (!stbl || !timescale) return null;
+ const s = children(stbl.body);
+ const get = (t: string) => s.find((c) => c.type === t);
+ const stsd = get("stsd");
+ const stts = get("stts");
+ const stsc = get("stsc");
+ const stsz = get("stsz");
+ const stco = get("stco") ?? get("co64");
+ if (!stsd || !stts || !stsc || !stsz || !stco) return null;
+
+ // Sizes.
+ const z = full(stsz.body);
+ const fixed = z.v.getUint32(0);
+ const n = z.v.getUint32(4);
+ if (!n || n > MAX_SAMPLES) return null;
+ const sizes = new Uint32Array(n);
+ for (let i = 0; i < n; i++) sizes[i] = fixed || z.v.getUint32(8 + i * 4);
+
+ // Decode times and durations.
+ const dts = new Float64Array(n);
+ const durs = new Uint32Array(n);
+ {
+ const t = full(stts.body);
+ const entries = t.v.getUint32(0);
+ let i = 0;
+ let time = 0;
+ for (let e = 0; e < entries && i < n; e++) {
+ const count = t.v.getUint32(4 + e * 8);
+ const delta = t.v.getUint32(8 + e * 8);
+ for (let k = 0; k < count && i < n; k++, i++) {
+ dts[i] = time;
+ durs[i] = delta;
+ time += delta;
+ }
+ }
+ if (i < n) return null;
+ }
+
+ // Composition offsets.
+ let ctts: Int32Array | null = null;
+ let cttsVersion = 0;
+ const cttsBox = get("ctts");
+ if (cttsBox) {
+ const c = full(cttsBox.body);
+ cttsVersion = c.version;
+ ctts = new Int32Array(n);
+ const entries = c.v.getUint32(0);
+ let i = 0;
+ for (let e = 0; e < entries && i < n; e++) {
+ const count = c.v.getUint32(4 + e * 8);
+ const off = c.v.getInt32(8 + e * 8);
+ for (let k = 0; k < count && i < n; k++, i++) ctts[i] = off;
+ }
+ }
+
+ // Key frames.
+ let sync: Uint8Array | null = null;
+ const stss = get("stss");
+ if (stss) {
+ const k = full(stss.body);
+ sync = new Uint8Array(n);
+ const entries = k.v.getUint32(0);
+ for (let e = 0; e < entries; e++) {
+ const at = k.v.getUint32(4 + e * 4) - 1;
+ if (at >= 0 && at < n) sync[at] = 1;
+ }
+ }
+
+ // Chunks: each sample's offset and description.
+ const co = full(stco.body);
+ const chunks = co.v.getUint32(0);
+ const chunkAt = (c: number) => (stco.type === "co64" ? Number(co.v.getBigUint64(4 + c * 8)) : co.v.getUint32(4 + c * 4));
+ const sc = full(stsc.body);
+ const scEntries = sc.v.getUint32(0);
+ const offsets = new Float64Array(n);
+ const sdi = new Uint32Array(n);
+ let i = 0;
+ for (let e = 0; e < scEntries && i < n; e++) {
+ const first = sc.v.getUint32(4 + e * 12) - 1;
+ const per = sc.v.getUint32(8 + e * 12);
+ const desc = sc.v.getUint32(12 + e * 12);
+ const last = e + 1 < scEntries ? sc.v.getUint32(4 + (e + 1) * 12) - 1 : chunks;
+ for (let c = first; c < last && i < n; c++) {
+ let at = chunkAt(c);
+ for (let k = 0; k < per && i < n; k++, i++) {
+ offsets[i] = at;
+ sdi[i] = desc;
+ at += sizes[i];
+ }
+ }
+ }
+ if (i < n) return null;
+
+ // The edit: an empty first edit is a delay; the next one says where the media starts.
+ let edit: Track["edit"] = null;
+ const elst = child(trak, "edts") && child(child(trak, "edts")!.body, "elst");
+ if (elst) {
+ const l = full(elst.body);
+ const entries = l.v.getUint32(0);
+ const wide = l.version === 1;
+ const step = wide ? 20 : 12;
+ let delay = 0;
+ for (let e = 0; e < entries; e++) {
+ const o = 4 + e * step;
+ const segment = wide ? Number(l.v.getBigUint64(o)) : l.v.getUint32(o);
+ const media = wide ? Number(l.v.getBigInt64(o + 8)) : l.v.getInt32(o + 4);
+ if (media === -1) {
+ delay += segment;
+ continue;
+ }
+ edit = { delay, mediaTime: media };
+ break;
+ }
+ }
+ void movieTimescale;
+ return {
+ tkhd: tkhd.box,
+ mdhd: mdhd.box,
+ hdlr: hdlr.box,
+ minfRest: minfKids.filter((c) => c.type !== "stbl").map((c) => c.box),
+ stsd: stsd.box,
+ handler,
+ timescale,
+ edit,
+ sizes,
+ offsets,
+ dts,
+ durs,
+ ctts,
+ cttsVersion,
+ sync,
+ sdi,
+ };
+}
+
+/** A clip's index from its header boxes, or null when it can't be cut here (see the file's comment). */
+export async function readMp4Index(read: ReadRange, size: number): Promise<Mp4Index | null> {
+ try {
+ let at = 0;
+ let ftyp: Uint8Array | null = null;
+ let moov: Uint8Array | null = null;
+ while (at + 8 <= size) {
+ const head = await read(at, Math.min(size, at + 16));
+ const v = view(head);
+ let boxSize = v.getUint32(0);
+ const type = fourcc(head, 4);
+ if (boxSize === 1) boxSize = Number(v.getBigUint64(8));
+ else if (boxSize === 0) boxSize = size - at;
+ if (boxSize < 8) return null;
+ if (type === "moof" || type === "sidx" || type === "styp") return null;
+ if (type === "ftyp") ftyp = await read(at, at + boxSize);
+ if (type === "moov") {
+ if (boxSize > MAX_MOOV) return null;
+ moov = await read(at, at + boxSize);
+ }
+ at += boxSize;
+ }
+ if (!moov) return null;
+ const kids = children(moov, 8);
+ if (kids.some((k) => k.type === "mvex")) return null;
+ const mvhd = kids.find((k) => k.type === "mvhd");
+ if (!mvhd) return null;
+ const mv = full(mvhd.body);
+ const movieTimescale = mv.version === 1 ? mv.v.getUint32(16) : mv.v.getUint32(8);
+ if (!movieTimescale) return null;
+ const tracks = kids
+ .filter((k) => k.type === "trak")
+ .map((k) => parseTrack(k.body, movieTimescale))
+ .filter((t): t is Track => !!t);
+ if (!tracks.length) return null;
+ const ref = tracks.find((t) => t.handler === "vide") ?? tracks[0];
+ const end = (t: Track) => (t.dts[t.dts.length - 1] + t.durs[t.durs.length - 1]) / t.timescale;
+ const keyframes: number[] = [];
+ for (let i = 0; i < ref.dts.length; i++) if (!ref.sync || ref.sync[i]) keyframes.push(ref.dts[i] / ref.timescale);
+ return {
+ seconds: Math.max(...tracks.map(end)),
+ keyframes,
+ hasVideo: tracks.some((t) => t.handler === "vide"),
+ hasAudio: tracks.some((t) => t.handler === "soun"),
+ ftyp,
+ moovRest: kids.filter((k) => k.type === "udta" || k.type === "meta").map((k) => k.box),
+ mvhd: mvhd.box,
+ movieTimescale,
+ tracks,
+ };
+ } catch {
+ return null;
+ }
+}
+
+/** The key frame a part asked to start at `from` really starts on (the one at or before it). */
+export function keyframeAtOrBefore(index: Pick<Mp4Index, "keyframes">, from: number): number {
+ let best = index.keyframes[0] ?? 0;
+ for (const k of index.keyframes) {
+ if (k <= from + 1e-6) best = k;
+ else break;
+ }
+ return best;
+}
+
+// ---------------------------------------------------------------------------
+// Writing
+
+function box(type: string, ...parts: Uint8Array[]): Uint8Array {
+ const size = 8 + parts.reduce((s, p) => s + p.length, 0);
+ const out = new Uint8Array(size);
+ const v = view(out);
+ v.setUint32(0, size);
+ for (let i = 0; i < 4; i++) out[4 + i] = type.charCodeAt(i);
+ let at = 8;
+ for (const p of parts) {
+ out.set(p, at);
+ at += p.length;
+ }
+ return out;
+}
+
+function fullBox(type: string, version: number, flags: number, body: Uint8Array): Uint8Array {
+ const head = new Uint8Array(4);
+ head[0] = version;
+ head[1] = (flags >> 16) & 255;
+ head[2] = (flags >> 8) & 255;
+ head[3] = flags & 255;
+ return box(type, head, body);
+}
+
+function u32s(values: number[]): Uint8Array {
+ const out = new Uint8Array(values.length * 4);
+ const v = view(out);
+ values.forEach((x, i) => v.setUint32(i * 4, x >>> 0));
+ return out;
+}
+
+/** A copy of a header box (mvhd, tkhd or mdhd) with its duration set (its own version's width). */
+function withDuration(src: Uint8Array, kind: "mvhd" | "tkhd" | "mdhd", duration: number): Uint8Array {
+ const out = src.slice();
+ const v = view(out);
+ const version = out[8];
+ // Offsets from the box's start: 8 header + 4 version and flags, then the times.
+ const at = version === 1 ? (kind === "tkhd" ? 12 + 8 + 8 + 4 + 4 : 12 + 8 + 8 + 4) : kind === "tkhd" ? 12 + 4 + 4 + 4 + 4 : 12 + 4 + 4 + 4;
+ if (version === 1) v.setBigUint64(at, BigInt(Math.round(duration)));
+ else v.setUint32(at, Math.min(0xffffffff, Math.round(duration)));
+ return out;
+}
+
+/** Run-length entries of a sequence. */
+function runs(values: ArrayLike<number>): [count: number, value: number][] {
+ const out: [number, number][] = [];
+ for (let i = 0; i < values.length; i++) {
+ const last = out[out.length - 1];
+ if (last && last[1] === values[i]) last[0]++;
+ else out.push([1, values[i]]);
+ }
+ return out;
+}
+
+export interface Mp4Cut {
+ /** The new file, in order. */
+ parts: CutPart[];
+ /** Its size in bytes. */
+ bytes: number;
+ /** Where in the original it starts (the key frame), and how long it is, in seconds. */
+ from: number;
+ seconds: number;
+}
+
+/**
+ * The part of `seconds` from the key frame at or before `from`, as the new file's parts: its header boxes (made here) and
+ * the original's byte ranges for its sound and picture. Null when nothing would be left.
+ */
+export function cutMp4(index: Mp4Index, from: number, seconds: number): Mp4Cut | null {
+ const start = keyframeAtOrBefore(index, from);
+ const end = Math.min(index.seconds, start + seconds);
+ if (end - start <= 0) return null;
+
+ type Sel = { t: Track; idx: number[]; duration: number };
+ const sel: Sel[] = [];
+ for (const t of index.tracks) {
+ const a = start * t.timescale;
+ const b = end * t.timescale;
+ const idx: number[] = [];
+ for (let i = 0; i < t.dts.length; i++) if (t.dts[i] >= a - 0.5 && t.dts[i] < b - 0.5) idx.push(i);
+ // A picture track starts on its key frame (its index starts there: the key frame's time is `start`).
+ if (!idx.length) continue;
+ const duration = idx.reduce((s, i) => s + t.durs[i], 0);
+ sel.push({ t, idx, duration });
+ }
+ if (!sel.length) return null;
+
+ // The sound and picture in the original's order (they stay interleaved as they were), and each sample's new offset.
+ const order: { s: number; i: number; off: number; size: number }[] = [];
+ sel.forEach((x, s) => x.idx.forEach((i) => order.push({ s, i, off: x.t.offsets[i], size: x.t.sizes[i] })));
+ order.sort((p, q) => p.off - q.off);
+ const newOffset = sel.map((x) => new Float64Array(x.idx.length));
+ const position = sel.map((x) => new Map(x.idx.map((i, k) => [i, k])));
+ let payload = 0;
+ const ranges: { start: number; end: number }[] = [];
+ for (const o of order) {
+ newOffset[o.s][position[o.s].get(o.i)!] = payload;
+ payload += o.size;
+ const last = ranges[ranges.length - 1];
+ if (last && last.end === o.off) last.end += o.size;
+ else ranges.push({ start: o.off, end: o.off + o.size });
+ }
+
+ const movieTs = index.movieTimescale;
+ const trackBoxes = (base: number) =>
+ sel.map(({ t, idx, duration }) => {
+ const k = sel.findIndex((x) => x.t === t);
+ const offs = newOffset[k];
+ const n = idx.length;
+ const stts = runs(idx.map((i) => t.durs[i]));
+ const parts: Uint8Array[] = [t.stsd];
+ parts.push(fullBox("stts", 0, 0, u32s([stts.length, ...stts.flat()])));
+ if (t.ctts) {
+ const c = runs(idx.map((i) => t.ctts![i]));
+ parts.push(fullBox("ctts", t.cttsVersion, 0, u32s([c.length, ...c.flat()])));
+ }
+ if (t.sync) {
+ const keys: number[] = [];
+ idx.forEach((i, j) => t.sync![i] && keys.push(j + 1));
+ parts.push(fullBox("stss", 0, 0, u32s([keys.length, ...keys])));
+ }
+ // One sample per chunk, a new entry where the description changes.
+ const sc: number[] = [];
+ idx.forEach((i, j) => {
+ if (j === 0 || t.sdi[i] !== t.sdi[idx[j - 1]]) sc.push(j + 1, 1, t.sdi[i]);
+ });
+ parts.push(fullBox("stsc", 0, 0, u32s([sc.length / 3, ...sc])));
+ parts.push(fullBox("stsz", 0, 0, u32s([0, n, ...idx.map((i) => t.sizes[i])])));
+ parts.push(fullBox("stco", 0, 0, u32s([n, ...Array.from(offs, (o) => base + o)])));
+ const stbl = box("stbl", ...parts);
+ const minf = box("minf", ...t.minfRest, stbl);
+ const mdia = box("mdia", withDuration(t.mdhd, "mdhd", duration), t.hdlr, minf);
+ const movieDuration = (duration / t.timescale) * movieTs;
+ const edits: Uint8Array[] = [];
+ if (t.edit) {
+ const entries: number[] = [];
+ if (t.edit.delay > 0) entries.push(Math.round(t.edit.delay), 0xffffffff, 0x00010000);
+ entries.push(Math.round(movieDuration), t.edit.mediaTime >>> 0, 0x00010000);
+ edits.push(box("edts", fullBox("elst", 0, 0, u32s([entries.length / 3, ...entries]))));
+ }
+ return { trak: box("trak", withDuration(t.tkhd, "tkhd", movieDuration + (t.edit?.delay ?? 0)), ...edits, mdia), movieDuration: movieDuration + (t.edit?.delay ?? 0) };
+ });
+
+ const ftyp = index.ftyp ?? box("ftyp", new Uint8Array([105, 115, 111, 109, 0, 0, 2, 0, 105, 115, 111, 109, 105, 115, 111, 50, 109, 112, 52, 49]));
+ const build = (base: number) => {
+ const traks = trackBoxes(base);
+ const mvhd = withDuration(index.mvhd, "mvhd", Math.max(...traks.map((x) => x.movieDuration)));
+ return box("moov", mvhd, ...traks.map((x) => x.trak), ...index.moovRest);
+ };
+ // The header's size doesn't depend on the offsets in it (32-bit each): measured once, then made with them.
+ const wide = payload + 8 > 0xffffffff;
+ const mdatHead = new Uint8Array(wide ? 16 : 8);
+ const mv = view(mdatHead);
+ if (wide) {
+ mv.setUint32(0, 1);
+ mv.setBigUint64(8, BigInt(payload + 16));
+ } else mv.setUint32(0, payload + 8);
+ mdatHead.set([109, 100, 97, 116], 4);
+ const size = build(0).length;
+ const moov = build(ftyp.length + size + mdatHead.length);
+ const parts: CutPart[] = [ftyp, moov, mdatHead, ...ranges];
+ return { parts, bytes: ftyp.length + moov.length + mdatHead.length + payload, from: start, seconds: end - start };
+}
diff --git a/tests/mp4-cut.test.ts b/tests/mp4-cut.test.ts
new file mode 100644
index 00000000..b3c65f81
--- /dev/null
+++ b/tests/mp4-cut.test.ts
@@ -0,0 +1,105 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { cutMp4, keyframeAtOrBefore, readMp4Index, type CutPart } from "@/lib/av/mp4-cut";
+import { probeMedia } from "@/lib/media-probe";
+import { tempDir } from "./helpers/temp-dir";
+
+const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0 && spawnSync("ffprobe", ["-version"]).status === 0;
+const dir = tempDir("fuobe-mp4-cut-");
+
+const reader = (buf: Uint8Array) => async (a: number, b: number) => buf.subarray(a, b);
+const join = (src: Uint8Array, parts: CutPart[]) => Buffer.concat(parts.map((p) => (p instanceof Uint8Array ? p : src.subarray(p.start, p.end))));
+const probe = (file: string) =>
+ JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_entries", "format=duration:stream=codec_type,duration,nb_frames", "-of", "json", file]).toString()) as {
+ format: { duration: string };
+ streams: { codec_type: string; duration?: string; nb_frames?: string }[];
+ };
+
+function clip(name: string, args: string[]): string {
+ const out = path.join(dir, name);
+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=160x90:rate=24", "-f", "lavfi", "-i", "sine=frequency=330:sample_rate=48000", "-t", "6", ...args, out]);
+ return out;
+}
+
+describe("mp4 cut: what it refuses", () => {
+ it("gives null for a file that isn't a plain MP4 or MOV", async () => {
+ const webm = new Uint8Array([0x1a, 0x45, 0xdf, 0xa3, 0, 0, 0, 0, 0, 0, 0, 0x1f, 0x42, 0x86, 0x81, 0x01]);
+ expect(await readMp4Index(reader(webm), webm.length)).toBeNull();
+ const junk = new Uint8Array(64).fill(7);
+ expect(await readMp4Index(reader(junk), junk.length)).toBeNull();
+ });
+
+ it("starts a part on the key frame at or before the time asked", () => {
+ const index = { keyframes: [0, 0.5, 1, 1.5, 2] };
+ expect(keyframeAtOrBefore(index, 1.3)).toBe(1);
+ expect(keyframeAtOrBefore(index, 1.5)).toBe(1.5);
+ expect(keyframeAtOrBefore(index, 9)).toBe(2);
+ expect(keyframeAtOrBefore(index, 0)).toBe(0);
+ });
+});
+
+describe.skipIf(!hasFfmpeg)("mp4 cut: real clips", () => {
+ const cases = [
+ { name: "h264-aac.mp4", args: ["-c:v", "libx264", "-g", "12", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "96k"] },
+ { name: "h264-aac-faststart.mp4", args: ["-c:v", "libx264", "-g", "12", "-bf", "0", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "+faststart"] },
+ { name: "h264-aac.mov", args: ["-c:v", "libx264", "-g", "12", "-pix_fmt", "yuv420p", "-c:a", "aac"] },
+ ];
+ for (const c of cases) {
+ it(`cuts ${c.name} from a key frame, keeping both tracks and their length`, async () => {
+ const file = clip(c.name, c.args);
+ const src = new Uint8Array(fs.readFileSync(file));
+ const index = await readMp4Index(reader(src), src.length);
+ expect(index).not.toBeNull();
+ expect(index!.hasVideo && index!.hasAudio).toBe(true);
+ expect(index!.seconds).toBeCloseTo(6, 0);
+ expect(index!.keyframes.slice(0, 3)).toEqual([0, 0.5, 1]);
+
+ const cut = cutMp4(index!, 2.3, 2)!;
+ expect(cut.from).toBe(2);
+ expect(cut.seconds).toBe(2);
+ const out = path.join(dir, `cut-${c.name}`);
+ const bytes = join(src, cut.parts);
+ expect(bytes.length).toBe(cut.bytes);
+ fs.writeFileSync(out, bytes);
+ // Decodes without an error, and is the part asked for.
+ const decode = spawnSync("ffmpeg", ["-v", "error", "-i", out, "-f", "null", "-"]);
+ expect(decode.stderr.toString()).toBe("");
+ const p = probe(out);
+ expect(Number(p.format.duration)).toBeGreaterThan(1.9);
+ expect(Number(p.format.duration)).toBeLessThan(2.15);
+ const video = p.streams.find((s) => s.codec_type === "video")!;
+ const audio = p.streams.find((s) => s.codec_type === "audio")!;
+ expect(Number(video.nb_frames)).toBe(48);
+ expect(Number(audio.duration)).toBeGreaterThan(1.9);
+ // Our own reader agrees, and the first frame is the source's frame at 2 s (testsrc draws its clock).
+ expect(probeMedia(new Uint8Array(bytes))?.duration).toBeGreaterThan(1.9);
+ const frameAt = (f: string, ss?: string) =>
+ execFileSync("ffmpeg", ["-v", "error", ...(ss ? ["-ss", ss] : []), "-i", f, "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "gray", "-"]);
+ const a = frameAt(out);
+ const b = frameAt(file, "2");
+ let diff = 0;
+ for (let i = 0; i < a.length; i++) diff += Math.abs(a[i] - b[i]);
+ expect(diff / a.length).toBeLessThan(2);
+ });
+ }
+
+ it("keeps a part at the end of the clip to what is left", async () => {
+ const file = clip("end.mp4", ["-c:v", "libx264", "-g", "12", "-pix_fmt", "yuv420p", "-c:a", "aac"]);
+ const src = new Uint8Array(fs.readFileSync(file));
+ const index = (await readMp4Index(reader(src), src.length))!;
+ const cut = cutMp4(index, 5, 4)!;
+ expect(cut.from).toBe(5);
+ expect(cut.seconds).toBeCloseTo(1, 1);
+ const out = path.join(dir, "cut-end.mp4");
+ fs.writeFileSync(out, join(src, cut.parts));
+ expect(spawnSync("ffmpeg", ["-v", "error", "-i", out, "-f", "null", "-"]).stderr.toString()).toBe("");
+ });
+
+ it("gives null for a fragmented MP4", async () => {
+ const file = clip("frag.mp4", ["-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-movflags", "frag_keyframe+empty_moov"]);
+ const src = new Uint8Array(fs.readFileSync(file));
+ expect(await readMp4Index(reader(src), src.length)).toBeNull();
+ });
+});