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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Trim and Ad Multiplier: read only a clip's header for its length, once per clip
Claude45ec5f703f9e
diff --git a/src/components/ads/multiplier.tsx b/src/components/ads/multiplier.tsxindex c090b489..71d5aa08 100644--- a/src/components/ads/multiplier.tsx+++ b/src/components/ads/multiplier.tsx@@ -14,7 +14,7 @@ import { fileToSlot, LibraryGrid, type SlotValue } from "@/components/studio/medimport { VideoTrimmer } from "@/components/studio/video-trimmer";import { initialClip, mentionedImages, MULTIPLIER, MULTIPLIER_MODELS, multiplierResolution, type ClipRange as Range, type MarketingRun, type RunEstimate } from "@/lib/catalog/marketing";import { formatCost } from "@/lib/format";-import { probeMedia } from "@/lib/media-probe";+import { probeBlob, probeUrl } from "@/lib/media-probe";import { cn } from "@/lib/utils";import { addRuns, send, useEstimate, useStatusFlags } from "@/components/marketing/hooks";import type { ModelInfo } from "@/components/marketing/model-info";@@ -199,9 +199,11 @@ export function AdMultiplier({ models }: { models: Record<string, ModelInfo> })const length = cut ? cut.end - cut.start : 0;const ready = !!video && !video.uploading && !!video.ref && duration != null && !!cut;- // Which reference is current (a late answer about an older clip is ignored), and whether its length is known.+ // Which reference is current (a late answer about an older clip is ignored), whether its length is+ // known, and whether its header has been read already (once per clip).const clip = useRef(0);const known = useRef(false);+ const probed = useRef(0);/** A new reference (a library pick, or an upload that reports its preview first, then its server URL). */const startVideo = () => {clip.current += 1;@@ -210,21 +212,22 @@ export function AdMultiplier({ models }: { models: Record<string, ModelInfo> })setRange(null);return clip.current;};- /** The length from the file's own header, for clips this browser can't play (e.g. H.264 without the codec). */+ /**+ * The length from the file's own header, for clips this browser can't play (e.g. H.264 without the+ * codec): the dropped file itself, else the server's copy with Range requests (only its header and+ * moov box are read, never the whole clip). Unknown containers: the player is the only other source.+ */const probe = async (source: Blob | string, token: number) => {- try {- const blob = typeof source === "string" ? await (await fetch(source)).blob() : source;- const d = probeMedia(new Uint8Array(await blob.arrayBuffer()))?.duration;- if (d && token === clip.current && !known.current) onDuration(d);- } catch {- // Unknown container: the player is the only other source of the length.- }+ if (probed.current === token) return;+ probed.current = token;+ const d = (typeof source === "string" ? await probeUrl(source) : await probeBlob(source))?.duration;+ if (d && token === clip.current && !known.current) onDuration(d);};const onFile = (f: File) => {if (!f.type.startsWith("video/") && !/\.(mp4|mov|webm|m4v)$/i.test(f.name)) return void toast("Video only — drop a clip here");const token = startVideo();void fileToSlot(f, setVideo, "video");- if (f.size <= 400 * 1024 * 1024) void probe(f, token);+ void probe(f, token);};const onDuration = (d: number) => {const first = !known.current;diff --git a/src/components/av/media-drop.tsx b/src/components/av/media-drop.tsxindex 2dddbf3e..43d634d3 100644--- a/src/components/av/media-drop.tsx+++ b/src/components/av/media-drop.tsx@@ -21,6 +21,7 @@ export function MediaDrop({hint,onDuration,onUnreadable,+ onFile,className,compact,player,@@ -36,6 +37,8 @@ export function MediaDrop({onDuration?: (seconds: number) => void;/** The browser can't decode the clip (e.g. H.265): tools fall back to typing times. */onUnreadable?: () => void;+ /** The file picked or dropped, before its upload starts (Trim reads its header from it, not from the server). */+ onFile?: (f: File) => void;className?: string;/** A shorter strip once something is attached (editors keep more room for their work). */compact?: boolean;@@ -48,6 +51,7 @@ export function MediaDrop({const take = (f: File | undefined) => {if (!f) return;if (kindOfFile(f) !== kind) return void toast(wrongKindMessage(kind));+ onFile?.(f);void fileToSlot(f, onChange, kind);};const Icon = kind === "video" ? FileVideo : ImagePlus;diff --git a/src/components/av/trim-tool.tsx b/src/components/av/trim-tool.tsxindex f669f96c..d7e9f09d 100644--- a/src/components/av/trim-tool.tsx+++ b/src/components/av/trim-tool.tsx@@ -1,7 +1,7 @@"use client";import { Loader2, Scissors } from "lucide-react";-import { useState } from "react";+import { useRef, useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";import { Feed } from "@/components/studio/feed";@@ -9,7 +9,7 @@ import type { SlotValue } from "@/components/studio/media-slot";import { VideoTrimmer, type TrimRange } from "@/components/studio/video-trimmer";import { useCreateGeneration, useEngine, useGenerations } from "@/lib/api";import { formatCueTime, parseCueTime } from "@/lib/av/cue-edit";-import { probeMedia } from "@/lib/media-probe";+import { probeBlob, probeUrl } from "@/lib/media-probe";import { cn } from "@/lib/utils";import { MediaDrop } from "./media-drop";import { useDraft } from "./use-draft";@@ -18,15 +18,6 @@ import { Panel, ToolHero, ToolShell } from "./tool-shell";export const TRIM_FEATURE = "trim";const MIN_LENGTH = 0.5;-/** The clip's length from its own header (MP4 / MOV), for clips this browser can't play. */-async function headerLength(url: string): Promise<number | null> {- try {- return probeMedia(new Uint8Array(await (await fetch(url)).arrayBuffer()))?.duration ?? null;- } catch {- return null;- }-}-/*** Trim (Video tools → Trim): keep the part between two times, with its sound. fal's trim utility on* the cloud, ComfyUI's core Trim Video on the open engine (CPU). The shared VideoTrimmer picks the@@ -45,19 +36,35 @@ export function TrimTool({ tabs }: { tabs?: React.ReactNode }) {/** The browser can't decode the clip: its length from the header (null: unknown, so the times are typed). */const [unreadable, setUnreadable] = useState<{ clip: number; length: number | null } | null>(null);const unread = unreadable?.clip === clip ? unreadable : null;+ // The file dropped for the current clip (none for a library pick), and which clip's header was read.+ const dropped = useRef<File | null>(null);+ const probed = useRef(-1);+ // The slot as last picked: an upload reports back to the `pick` of the render it started in, whose `video` is stale.+ const current = useRef<SlotValue | null>(null);const pick = (v: SlotValue | null) => {- const finished = !!v && !!video?.uploading && !v.uploading && v.name === video.name;+ const prev = current.current;+ current.current = v;+ const finished = !!v && !!prev?.uploading && !v.uploading && v.name === prev.name;if (!finished) {setClip((c) => c + 1);setRange(null);setLength(0);+ if (!v?.uploading) dropped.current = null;}setVideo(v);};+ /**+ * The clip's length from its own header (MP4 / MOV), for clips this browser can't play: read once+ * per clip (the trimmer says so again when a finished upload moves its preview to the server),+ * from the dropped file itself, else from the server with Range requests (only the header and+ * moov box, never the whole clip).+ */const onUnreadable = () => {- if (!video) return;+ if (!video || probed.current === clip) return;const at = clip;- void headerLength(video.preview).then((d) => setUnreadable({ clip: at, length: d }));+ probed.current = at;+ const file = dropped.current;+ void (file ? probeBlob(file) : probeUrl(video.ref || video.preview)).then((info) => setUnreadable({ clip: at, length: info?.duration ?? null }));};const trim = () => {if (!video) return void toast("Add the video first");@@ -82,7 +89,7 @@ export function TrimTool({ tabs }: { tabs?: React.ReactNode }) {<ToolShell title="Video tools" tabs={tabs}>{!video && <ToolHero title="Keep just the part you need" subtitle="Pick where it starts and ends — the sound comes along. Free on your ComfyUI (CPU), fractions of a cent on the cloud." />}<div className={cn("mx-auto max-w-[820px] space-y-3", video ? "pt-4" : "mt-8")}>- <MediaDrop kind="video" value={video} onChange={pick} preview={false} title="Add a video to trim" hint="MP4, MOV or WebM up to 200 MB" compact />+ <MediaDrop kind="video" value={video} onChange={pick} onFile={(f) => (dropped.current = f)} preview={false} title="Add a video to trim" hint="MP4, MOV or WebM up to 200 MB" compact />{video && (<Panel title="Keep">{typed ? (diff --git a/src/lib/media-probe.ts b/src/lib/media-probe.tsindex 3f8df1fa..5bdaaf08 100644--- a/src/lib/media-probe.ts+++ b/src/lib/media-probe.ts@@ -32,6 +32,77 @@ export function probeMedia(data: Uint8Array): MediaInfo | null {}}+// ---------------------------------------------------------------------------+// Probing a file without reading all of it++/** Reads the bytes [start, end) of a file. */+export type ReadRange = (start: number, end: number) => Promise<Uint8Array>;++const HEAD_BYTES = 256 * 1024;+const MAX_MOOV_BYTES = 64 * 1024 * 1024;+const ISO_TOP = ["ftyp", "moov", "mdat", "free", "wide", "skip"];++/**+ * {@link probeMedia} without reading the whole file: an MP4 / MOV is walked box header by box header+ * to its moov box (at the start, or after the media data like a camera file) and only that is read,+ * so a 200 MB clip costs a few small reads. Other containers are probed when the whole file fits in+ * the first read, else unknown (null).+ */+export async function probeMediaRanges(read: ReadRange, size: number): Promise<MediaInfo | null> {+ try {+ const head = await read(0, Math.min(size, HEAD_BYTES));+ if (head.length < 12) return null;+ if (!ISO_TOP.includes(fourcc(head, 4))) return size <= head.length ? probeMedia(head) : null;+ for (let o = 0; o + 8 <= size; ) {+ const h = o + 16 <= head.length ? head.subarray(o, o + 16) : await read(o, Math.min(size, o + 16));+ if (h.length < 8) return null;+ const d = new DataView(h.buffer, h.byteOffset, h.byteLength);+ let len = d.getUint32(0);+ if (len === 1) {+ if (h.length < 16) return null;+ len = Number(d.getBigUint64(8));+ } else if (len === 0) len = size - o;+ if (len < 8) return null;+ if (fourcc(h, 4) === "moov") {+ if (len > MAX_MOOV_BYTES) return null;+ const end = Math.min(size, o + len);+ return probeMedia(end <= head.length ? head.subarray(o, end) : await read(o, end));+ }+ o += len;+ }+ return null;+ } catch {+ return null;+ }+}++/** Probe a dropped file (a File or Blob) by reading only the parts that say what it is. */+export function probeBlob(blob: Blob): Promise<MediaInfo | null> {+ return probeMediaRanges(async (start, end) => new Uint8Array(await blob.slice(start, end).arrayBuffer()), blob.size);+}++/**+ * Probe a file by URL with Range requests (/api/files answers them), so only its header and moov+ * box are downloaded. A server that ignores Range sends the whole file, which is probed as it is.+ */+export async function probeUrl(url: string): Promise<MediaInfo | null> {+ try {+ const first = await fetch(url, { headers: { Range: `bytes=0-${HEAD_BYTES - 1}` } });+ if (!first.ok) return null;+ const head = new Uint8Array(await first.arrayBuffer());+ const total = first.status === 206 ? Number(/\/(\d+)\s*$/.exec(first.headers.get("content-range") ?? "")?.[1]) : head.length;+ if (first.status !== 206 || !Number.isFinite(total) || total <= head.length) return probeMedia(head);+ return probeMediaRanges(async (start, end) => {+ if (end <= head.length) return head.subarray(start, end);+ const res = await fetch(url, { headers: { Range: `bytes=${start}-${end - 1}` } });+ if (res.status !== 206) throw new Error("no ranges");+ return new Uint8Array(await res.arrayBuffer());+ }, total);+ } catch {+ return null;+ }+}+// ---------------------------------------------------------------------------// ISO-BMFF (mp4, mov, m4a)diff --git a/tests/media-probe.test.ts b/tests/media-probe.test.tsindex 6e551bd5..be84a331 100644--- a/tests/media-probe.test.ts+++ b/tests/media-probe.test.ts@@ -1,5 +1,5 @@-import { describe, expect, it } from "vitest";-import { probeMedia } from "@/lib/media-probe";+import { afterEach, describe, expect, it, vi } from "vitest";+import { probeBlob, probeMedia, probeMediaRanges, probeUrl } from "@/lib/media-probe";const u32 = (...v: number[]) =>Buffer.concat(@@ -95,3 +95,77 @@ describe("media probe", () => {expect(probeMedia(Buffer.alloc(4))).toBeNull();});});++describe("probing without reading the whole file (Trim, the Ad Multiplier)", () => {+ afterEach(() => vi.unstubAllGlobals());++ /** A camera-style file: 4 MB of media data with the moov box after it (or before: faststart), optionally a 64-bit mdat size. */+ function big({ faststart = false, large = false } = {}): Buffer {+ const whole = mp4();+ const ftyp = whole.subarray(0, 16);+ const moov = whole.subarray(16 + 72);+ const media = Buffer.alloc(4 * 1024 * 1024);+ const mdat = large ? Buffer.concat([u32(1), Buffer.from("mdat"), u32(0, 16 + media.length), media]) : box("mdat", media);+ return Buffer.concat(faststart ? [ftyp, moov, mdat] : [ftyp, mdat, moov]);+ }+ const reader = (buf: Buffer) => {+ const reads: [number, number][] = [];+ const read = async (start: number, end: number) => (reads.push([start, end]), new Uint8Array(buf.subarray(start, end)));+ return { read, reads, bytes: () => reads.reduce((n, [a, b]) => n + (b - a), 0) };+ };+ const expected = probeMedia(mp4());++ it("finds the moov box by its box headers and reads only that, wherever it sits", async () => {+ for (const opts of [{}, { faststart: true }, { large: true }]) {+ const buf = big(opts);+ const r = reader(buf);+ expect(await probeMediaRanges(r.read, buf.length), JSON.stringify(opts)).toEqual(expected);+ expect(r.bytes()).toBeLessThan(300 * 1024);+ }+ });++ it("reads a dropped File in slices", async () => {+ const buf = big();+ const blob = new Blob([new Uint8Array(buf)]);+ const slice = vi.spyOn(blob, "slice");+ expect(await probeBlob(blob)).toEqual(expected);+ expect(slice.mock.calls.every(([a, b]) => (b ?? 0) - (a ?? 0) <= 256 * 1024)).toBe(true);+ });++ it("asks the server for byte ranges, and copes with one that sends the whole file", async () => {+ const buf = big();+ let sent = 0;+ const serve = (ranges: boolean) =>+ vi.fn(async (_url: string, init?: RequestInit) => {+ const m = /bytes=(\d+)-(\d+)/.exec(new Headers(init?.headers).get("range") ?? "");+ if (!ranges || !m) return (sent += buf.length), new Response(new Uint8Array(buf), { status: 200 });+ const end = Math.min(Number(m[2]), buf.length - 1);+ const part = buf.subarray(Number(m[1]), end + 1);+ sent += part.length;+ return new Response(new Uint8Array(part), { status: 206, headers: { "Content-Range": `bytes ${m[1]}-${end}/${buf.length}` } });+ });+ vi.stubGlobal("fetch", serve(true));+ expect(await probeUrl("/api/files/clip.mp4")).toEqual(expected);+ expect(sent).toBeLessThan(300 * 1024);+ vi.stubGlobal("fetch", serve(false));+ expect(await probeUrl("/api/files/clip.mp4")).toEqual(expected);+ vi.stubGlobal("fetch", vi.fn(async () => new Response("Not found", { status: 404 })));+ expect(await probeUrl("/api/files/gone.mp4")).toBeNull();+ });++ it("probes other containers only when the whole file fits in the first read", async () => {+ const wav = Buffer.alloc(44);+ wav.write("RIFF", 0);+ wav.write("WAVEfmt ", 8);+ wav.writeUInt32LE(16, 16);+ wav.writeUInt32LE(4, 28);+ wav.write("data", 36);+ wav.writeUInt32LE(0, 40);+ const small = reader(Buffer.concat([wav, Buffer.alloc(400)]));+ expect((await probeMediaRanges(small.read, 444))?.container).toBe("wav");+ const webm = Buffer.concat([Buffer.from("\x1aE\xdf\xa3 webm header....."), Buffer.alloc(1024 * 1024)]);+ const r = reader(webm);+ expect(await probeMediaRanges(r.read, webm.length)).toBeNull();+ expect(r.reads).toHaveLength(1);+ });+});