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 use the shared VideoTrimmer instead of their simple in/out pickers
Claude46e0887bd934
diff --git a/src/components/ads/clip-range.tsx b/src/components/ads/clip-range.tsxdeleted file mode 100644index 7bd83e60..00000000--- a/src/components/ads/clip-range.tsx+++ /dev/null@@ -1,142 +0,0 @@-"use client";--import { Play, Scissors } from "lucide-react";-import { useEffect, useRef, useState } from "react";-import { clampClip, commitClipTime, initialClip, MULTIPLIER, parseClipTime, type ClipRange as Range } from "@/lib/catalog/marketing";-import { cn } from "@/lib/utils";--const r1 = (n: number) => Math.round(n * 10) / 10;-const fmt = (s: number) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, "0")}`;--/**- * An in/out time: what's typed stays as typed until Enter or leaving the field (then the range is- * clamped), so "20" isn't cut to the 4 s minimum at its first digit. Arrow keys step 0.1 s at once;- * Escape goes back to the current value.- */-function TimeField({ label, value, max, onCommit }: { label: string; value: number; max: number; onCommit: (text: string) => void }) {- const [text, setText] = useState<string | null>(null);- const invalid = text != null && parseClipTime(text) == null;- const commit = () => {- if (text == null) return;- setText(null);- onCommit(text);- };- return (- <label className="block">- <span className="mb-1 block text-[11px] font-medium text-muted-foreground">{label}</span>- <input- type="text"- inputMode="decimal"- value={text ?? String(value)}- onChange={(e) => setText(e.target.value)}- onBlur={commit}- onKeyDown={(e) => {- if (e.key === "Enter") {- e.preventDefault();- commit();- } else if (e.key === "Escape" && text != null) {- e.preventDefault();- setText(null);- } else if (e.key === "ArrowUp" || e.key === "ArrowDown") {- e.preventDefault();- const base = parseClipTime(text ?? String(value)) ?? value;- setText(null);- onCommit(String(Math.min(max, Math.max(0, r1(base + (e.key === "ArrowUp" ? 0.1 : -0.1))))));- }- }}- aria-invalid={invalid || undefined}- className={cn("h-8 w-20 rounded-lg border bg-background px-2 font-mono text-[13px] tabular-nums outline-none focus:border-primary", invalid && "border-destructive")}- />- </label>- );-}--/**- * A plain in/out picker for the reference ad: the player, a bar showing the kept part, two time- * fields and "set from the playhead" buttons. (A drop-in for a fuller trimmer later.)- */-export function ClipRange({ src, duration, value, onChange, onDuration, onUnplayable, className }: { src: string; duration: number | null; value: Range | null; onChange: (r: Range) => void; onDuration: (d: number) => void; onUnplayable?: () => void; className?: string }) {- const video = useRef<HTMLVideoElement>(null);- const [failed, setFailed] = useState<string | null>(null);- const unplayable = failed === src;- const stopAt = useRef<number | null>(null);- useEffect(() => {- const v = video.current;- if (!v) return;- const tick = () => {- if (stopAt.current != null && v.currentTime >= stopAt.current) {- v.pause();- stopAt.current = null;- }- };- v.addEventListener("timeupdate", tick);- return () => v.removeEventListener("timeupdate", tick);- }, []);- const d = duration ?? 0;- const range = value ?? (d ? initialClip(d) : null);- const length = range ? range.end - range.start : 0;- const outside = !!range && (length < MULTIPLIER.minSeconds - 0.05 || length > MULTIPLIER.maxSeconds + 0.05);- const set = (k: "start" | "end", n: number) => range && d && onChange(clampClip({ ...range, [k]: n }, d, k));- const here = (k: "start" | "end") => video.current && set(k, video.current.currentTime);- const preview = () => {- const v = video.current;- if (!v || !range) return;- v.currentTime = range.start;- stopAt.current = range.end;- void v.play();- };- return (- <div className={cn("min-w-0", className)}>- <video- ref={video}- src={src}- controls- playsInline- preload="metadata"- onLoadedMetadata={(e) => Number.isFinite(e.currentTarget.duration) && onDuration(e.currentTarget.duration)}- onError={() => {- setFailed(src);- onUnplayable?.();- }}- className={cn("mx-auto max-h-[46vh] w-full rounded-xl bg-black object-contain", unplayable && "hidden")}- aria-label="Reference ad"- />- {unplayable && (- <div className="grid aspect-video place-items-center rounded-xl bg-muted px-6 text-center text-[13px] text-muted-foreground">- This browser can't play this clip's format, so there's no preview here. It's still used as it is — set the in and out points by time.- </div>- )}- {range && d > 0 && (- <div className="mt-3 space-y-2.5">- <div className="relative h-2 rounded-full bg-muted" aria-hidden>- <div className={cn("absolute inset-y-0 rounded-full", outside ? "bg-destructive/60" : "bg-primary")} style={{ left: `${(range.start / d) * 100}%`, width: `${(length / d) * 100}%` }} />- </div>- <div className="flex flex-wrap items-end gap-2">- {(["start", "end"] as const).map((k) => (- <div key={k} className="flex items-end gap-1">- <TimeField- label={k === "start" ? "In (s)" : "Out (s)"}- value={range[k]}- max={r1(d)}- onCommit={(text) => {- const next = commitClipTime(text, range, d, k);- if (next) onChange(next);- }}- />- <button type="button" onClick={() => here(k)} className="inline-flex h-8 items-center gap-1 rounded-lg bg-secondary px-2 text-[12px] font-medium hover:bg-accent" title={`Set the ${k === "start" ? "in" : "out"} point at the playhead`}>- <Scissors className="size-3" /> {k === "start" ? "Set in here" : "Set out here"}- </button>- </div>- ))}- <button type="button" onClick={preview} className="inline-flex h-8 items-center gap-1 rounded-lg px-2 text-[12px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground">- <Play className="size-3" /> Play the cut- </button>- </div>- <p className={cn("text-[12px]", outside ? "text-destructive" : "text-muted-foreground")} role={outside ? "alert" : undefined}>- {fmt(range.start)} – {fmt(range.end)} · {length.toFixed(1)} s of {d.toFixed(1)} s{outside ? ` — the reference must be ${MULTIPLIER.minSeconds}–${MULTIPLIER.maxSeconds} s` : ""}- </p>- </div>- )}- </div>- );-}diff --git a/src/components/ads/multiplier.tsx b/src/components/ads/multiplier.tsxindex 049273f4..c090b489 100644--- a/src/components/ads/multiplier.tsx+++ b/src/components/ads/multiplier.tsx@@ -11,6 +11,7 @@ import { Switch } from "@/components/ui/switch";import { areaCls } from "@/components/brand/fields";import { uploadImages } from "@/components/brand/image-list";import { fileToSlot, LibraryGrid, type SlotValue } from "@/components/studio/media-slot";+import { 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";@@ -19,7 +20,6 @@ import { addRuns, send, useEstimate, useStatusFlags } from "@/components/marketiimport type { ModelInfo } from "@/components/marketing/model-info";import { RunsList } from "@/components/marketing/runs";import { EmptyIcon, MarketingHeader, useMarketingEngine } from "@/components/marketing/shell";-import { ClipRange } from "./clip-range";import { uploadFrame } from "./frames";type Quality = (typeof MULTIPLIER.qualities)[number];@@ -232,7 +232,7 @@ export function AdMultiplier({ models }: { models: Record<string, ModelInfo> })setDuration(d);setRange((r) => r ?? initialClip(d));if (!first) return;- if (d > MULTIPLIER.maxSeconds + 0.05) toast(`Using the first ${MULTIPLIER.maxSeconds} s — move the in and out points to pick another part`, { id: "mult-trim" });+ if (d > MULTIPLIER.maxSeconds + 0.05) toast(`Using the first ${MULTIPLIER.maxSeconds} s — slide the selection to pick another part`, { id: "mult-trim" });if (d < MULTIPLIER.minSeconds - 0.05) toast.error(`That clip is ${d.toFixed(1)} s — the reference needs ${MULTIPLIER.minSeconds}–${MULTIPLIER.maxSeconds} s`, { id: "mult-trim" });};@@ -319,8 +319,18 @@ export function AdMultiplier({ models }: { models: Record<string, ModelInfo> })<ReferenceDrop onFile={onFile} onPick={(v) => (startVideo(), setVideo(v))} />) : (<div className="relative">- <ClipRange src={video.preview} duration={duration} value={range} onChange={setRange} onDuration={onDuration} onUnplayable={() => {- if (!video.uploading && video.ref && !known.current) void probe(video.ref, clip.current);+ {/* A new reference mounts a new trimmer (Replace goes back to the drop zone); a finished upload only moves its preview to the server. */}+ <VideoTrimmer+ src={video.preview}+ value={range && { startTime: range.start, endTime: range.end }}+ onChange={(r) => setRange({ start: r.startTime, end: r.endTime })}+ min={MULTIPLIER.minSeconds}+ max={MULTIPLIER.maxSeconds}+ duration={duration ?? undefined}+ label="Part of the reference ad"+ onMeta={(m) => m.duration > 0 && onDuration(m.duration)}+ onUnreadable={() => {+ if (!known.current) void probe(video.ref || video.preview, clip.current);}}/>{video.uploading && (diff --git a/src/components/av/media-drop.tsx b/src/components/av/media-drop.tsxindex e8e57b5c..2dddbf3e 100644--- a/src/components/av/media-drop.tsx+++ b/src/components/av/media-drop.tsx@@ -24,6 +24,7 @@ export function MediaDrop({className,compact,player,+ preview = true,}: {/** The preview <video>, for tools that drive it (Trim plays the selection in it). */player?: React.Ref<HTMLVideoElement>;@@ -38,6 +39,8 @@ export function MediaDrop({className?: string;/** A shorter strip once something is attached (editors keep more room for their work). */compact?: boolean;+ /** false: once something is attached, just its name with Replace / Remove (the tool shows it itself: Trim's trimmer). */+ preview?: boolean;}) {const input = useRef<HTMLInputElement>(null);const [over, setOver] = useState(false);@@ -85,38 +88,46 @@ export function MediaDrop({if (value) {return (<div className={cn("overflow-hidden rounded-2xl border bg-background shadow-soft", className)}>- <div className={cn("relative grid place-items-center bg-media", compact ? "max-h-[38vh]" : "max-h-[52vh]")}>- {kind === "video" ? (- <video- key={value.preview}- ref={player}- src={value.preview}- controls- playsInline- preload="metadata"- onLoadedMetadata={(e) => {- const el = e.currentTarget;- if (Number.isFinite(el.duration) && el.duration > 0) return onDuration?.(el.duration);- // A recording with no length in its header (MediaRecorder WebM): find it, else fall back to typed times.- void realDuration(el).then((d) => (d ? onDuration?.(d) : onUnreadable?.()));- }}- onError={() => !value.uploading && onUnreadable?.()}- className={cn("w-full object-contain", compact ? "max-h-[38vh]" : "max-h-[52vh]")}- />- ) : (- // eslint-disable-next-line @next/next/no-img-element- <img src={value.preview} alt={value.name ?? title} className={cn("w-full object-contain", compact ? "max-h-[38vh]" : "max-h-[52vh]")} />- )}- {value.uploading && (- <div className="absolute inset-0 grid place-items-center bg-background/50" role="status" aria-label="Uploading">- <span className="inline-flex items-center gap-2 rounded-full bg-background px-3 py-1.5 text-[13px] font-medium shadow-soft">- <Loader2 className="size-3.5 animate-spin" /> Uploading…- </span>- </div>- )}- </div>+ {preview && (+ <div className={cn("relative grid place-items-center bg-media", compact ? "max-h-[38vh]" : "max-h-[52vh]")}>+ {kind === "video" ? (+ <video+ key={value.preview}+ ref={player}+ src={value.preview}+ controls+ playsInline+ preload="metadata"+ onLoadedMetadata={(e) => {+ const el = e.currentTarget;+ if (Number.isFinite(el.duration) && el.duration > 0) return onDuration?.(el.duration);+ // A recording with no length in its header (MediaRecorder WebM): find it, else fall back to typed times.+ void realDuration(el).then((d) => (d ? onDuration?.(d) : onUnreadable?.()));+ }}+ onError={() => !value.uploading && onUnreadable?.()}+ className={cn("w-full object-contain", compact ? "max-h-[38vh]" : "max-h-[52vh]")}+ />+ ) : (+ // eslint-disable-next-line @next/next/no-img-element+ <img src={value.preview} alt={value.name ?? title} className={cn("w-full object-contain", compact ? "max-h-[38vh]" : "max-h-[52vh]")} />+ )}+ {value.uploading && (+ <div className="absolute inset-0 grid place-items-center bg-background/50" role="status" aria-label="Uploading">+ <span className="inline-flex items-center gap-2 rounded-full bg-background px-3 py-1.5 text-[13px] font-medium shadow-soft">+ <Loader2 className="size-3.5 animate-spin" /> Uploading…+ </span>+ </div>+ )}+ </div>+ )}<div className="flex min-w-0 items-center gap-1 px-3 py-2">+ {!preview && <Icon className="size-4 shrink-0 text-muted-foreground" />}<p className="min-w-0 flex-1 truncate text-[13px] text-muted-foreground">{value.name ?? title}</p>+ {!preview && value.uploading && (+ <span className="inline-flex shrink-0 items-center gap-1.5 text-[12px] text-muted-foreground" role="status">+ <Loader2 className="size-3 animate-spin" /> Uploading…+ </span>+ )}<Button variant="ghost" size="sm" className="rounded-full" onClick={() => input.current?.click()}><RefreshCw className="size-3.5" /> Replace</Button>diff --git a/src/components/av/trim-tool.tsx b/src/components/av/trim-tool.tsxindex 91498b01..89345c31 100644--- a/src/components/av/trim-tool.tsx+++ b/src/components/av/trim-tool.tsx@@ -1,16 +1,16 @@"use client";-import { Loader2, Pause, Play, Scissors } from "lucide-react";-import { useEffect, useRef, useState } from "react";+import { Loader2, Scissors } from "lucide-react";+import { useState } from "react";import { toast } from "sonner";import { Button } from "@/components/ui/button";-import { Slider } from "@/components/ui/slider";import { Feed } from "@/components/studio/feed";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 { cn } from "@/lib/utils";-import { sampleFrames, spacedTimes } from "./frame-sampler";import { MediaDrop } from "./media-drop";import { useDraft } from "./use-draft";import { Panel, ToolHero, ToolShell } from "./tool-shell";@@ -18,67 +18,101 @@ 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). A minimal in/out picker; Shorts- * Studio's video trimmer can replace VideoRange when it lands.+ * the cloud, ComfyUI's core Trim Video on the open engine (CPU). The shared VideoTrimmer picks the+ * part (filmstrip, handles, play the selection, typed times); a clip the browser can't decode is+ * trimmed by typed times, with its length read from the file when it says.*/export function TrimTool({ tabs }: { tabs?: React.ReactNode }) {const [engine] = useEngine();const create = useCreateGeneration();const results = useGenerations({ features: [TRIM_FEATURE], limit: 24 });const [video, setVideo] = useState<SlotValue | null>(null);- const [duration, setDuration] = useState(0);- const [unreadable, setUnreadable] = useState(false);- const [range, setRange] = useState<[number, number]>([0, 0]);- // The preview above plays the selection.- const preview = useRef<HTMLVideoElement>(null);+ const [range, setRange] = useState<TrimRange | null>(null);+ const [length, setLength] = useState(0);+ // Which clip is current: an upload that finishes is the same clip (its preview moves to the server URL).+ const [clip, setClip] = useState(0);+ /** 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;+ const pick = (v: SlotValue | null) => {+ const finished = !!v && !!video?.uploading && !v.uploading && v.name === video.name;+ if (!finished) {+ setClip((c) => c + 1);+ setRange(null);+ setLength(0);+ }+ setVideo(v);+ };+ const onUnreadable = () => {+ if (!video) return;+ const at = clip;+ void headerLength(video.preview).then((d) => setUnreadable({ clip: at, length: d }));+ };const trim = () => {if (!video || video.uploading) return void toast("Add the video first");- if (range[1] - range[0] < MIN_LENGTH) return void toast(`Keep at least ${MIN_LENGTH} s`);+ if (!range) return void toast("Pick the part to keep");+ if (range.endTime - range.startTime < MIN_LENGTH) return void toast(`Keep at least ${MIN_LENGTH} s`);create.mutate({feature: TRIM_FEATURE,modelId: engine === "open" ? "oss-trim" : "trim-video",op: "trim",inputs: { video: video.ref },- params: { startTime: Math.round(range[0] * 100) / 100, endTime: Math.round(range[1] * 100) / 100 },- title: `Trim · ${formatCueTime(range[0])}–${formatCueTime(range[1])}`,+ params: { startTime: Math.round(range.startTime * 100) / 100, endTime: Math.round(range.endTime * 100) / 100 },+ title: `Trim · ${formatCueTime(range.startTime)}–${formatCueTime(range.endTime)}`,},{ onSuccess: () => toast.success("Trimming"), onError: (e) => toast.error((e as Error).message) },);};+ const typed = !!unread && unread.length == null;+ const total = unread?.length ?? length;return (<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"- player={preview}- value={video}- onChange={(v) => {- setVideo(v);- setUnreadable(false);- if (!v) setDuration(0);- }}- onDuration={(d) => {- setDuration(d);- setRange([0, d]);- }}- onUnreadable={() => setUnreadable(true)}- title="Add a video to trim"- hint="MP4, MOV or WebM up to 200 MB"- compact- />- {video && !video.uploading && (duration > 0 || unreadable) && (+ <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 />+ {video && (<Panel title="Keep">- {duration > 0 ? <VideoRange src={video.ref} duration={duration} value={range} onChange={setRange} player={preview} /> : <ManualRange value={range} onChange={setRange} />}+ {typed ? (+ <ManualRange value={range} onChange={setRange} />+ ) : (+ <VideoTrimmer+ key={clip}+ src={video.preview}+ value={range}+ onChange={setRange}+ min={MIN_LENGTH}+ duration={unread?.length ?? undefined}+ label="Part to keep"+ onMeta={(m) => m.duration > 0 && setLength(m.duration)}+ onUnreadable={onUnreadable}+ />+ )}<div className="mt-4 flex flex-wrap items-center gap-2"><p className="flex-1 text-[13px] text-muted-foreground">- Keeps <span className="font-mono text-foreground">{formatCueTime(Math.max(0, range[1] - range[0]))}</span>- {duration > 0 && ` of ${formatCueTime(duration)}`}+ {range ? (+ <>+ Keeps <span className="font-mono text-foreground">{formatCueTime(Math.max(0, range.endTime - range.startTime))}</span>+ {total > 0 && ` of ${formatCueTime(total)}`}+ </>+ ) : typed ? (+ "Type where it starts and ends"+ ) : (+ "Reading the clip…"+ )}</p>- <Button className="rounded-full" onClick={trim} disabled={create.isPending}>+ <Button className="rounded-full" onClick={trim} disabled={create.isPending || !range}>{create.isPending ? <Loader2 className="size-4 animate-spin" /> : <Scissors className="size-4" />} Trim</Button></div>@@ -97,116 +131,20 @@ export function TrimTool({ tabs }: { tabs?: React.ReactNode }) {);}-/**- * Filmstrip + two-handle range + exact times + play the selection — in the visible preview passed as- * `player`, else in a hidden one of its own (sound only).- */-export function VideoRange({- src,- duration,- value,- onChange,- player: shown,-}: {- src: string;- duration: number;- value: [number, number];- onChange: (v: [number, number]) => void;- player?: React.RefObject<HTMLVideoElement | null>;-}) {- const [thumbs, setThumbs] = useState<string[]>([]);- const own = useRef<HTMLVideoElement>(null);- const player = shown ?? own;- const [playing, setPlaying] = useState(false);- useEffect(() => {- const ctl = new AbortController();- sampleFrames(src, spacedTimes(duration, 10), { width: 96, jpeg: true, signal: ctl.signal })- .then((f) => !ctl.signal.aborted && setThumbs(f.map((x) => x.url!)))- .catch(() => {});- return () => ctl.abort();- }, [src, duration]);- // Playing the selection stops at the out point (or when the player's own controls pause it).- useEffect(() => {- const v = player.current;- if (!v || !playing) return;- const tick = () => {- if (v.currentTime >= value[1]) {- v.pause();- setPlaying(false);- }- };- const paused = () => setPlaying(false);- v.addEventListener("timeupdate", tick);- v.addEventListener("pause", paused);- return () => {- v.removeEventListener("timeupdate", tick);- v.removeEventListener("pause", paused);- };- }, [player, playing, value]);- const play = () => {- const v = player.current;- if (!v) return;- if (playing) {- v.pause();- return setPlaying(false);- }- v.currentTime = value[0];- void v.play().then(() => setPlaying(true)).catch(() => toast("This browser can't play the clip — the trim still works"));- };- const set = (i: 0 | 1, raw: string) => {- const t = parseCueTime(raw);- if (t === null) return;- const next: [number, number] = i === 0 ? [Math.min(t, value[1] - MIN_LENGTH), value[1]] : [value[0], Math.max(t, value[0] + MIN_LENGTH)];- onChange([Math.max(0, next[0]), Math.min(duration, next[1])]);- };- return (- <div className="space-y-3">- {!shown && <video ref={own} src={src} playsInline preload="metadata" className="hidden" />}- <div className="relative h-12 overflow-hidden rounded-lg bg-muted" aria-hidden>- <div className="flex h-full">- {thumbs.map((u, i) => (- // eslint-disable-next-line @next/next/no-img-element- <img key={i} src={u} alt="" className="h-full min-w-0 flex-1 object-cover" />- ))}- </div>- <div className="absolute inset-y-0 left-0 bg-background/70" style={{ width: `${(value[0] / duration) * 100}%` }} />- <div className="absolute inset-y-0 right-0 bg-background/70" style={{ width: `${100 - (value[1] / duration) * 100}%` }} />- <div className="absolute inset-y-0 rounded-lg border-2 border-primary" style={{ left: `${(value[0] / duration) * 100}%`, right: `${100 - (value[1] / duration) * 100}%` }} />- </div>- <Slider- min={0}- max={duration}- step={0.05}- minStepsBetweenThumbs={Math.round(MIN_LENGTH / 0.05)}- value={value}- onValueChange={(v) => onChange([v[0], v[1]])}- aria-label="Part to keep"- thumbLabels={["Start", "End"]}- />- <div className="flex flex-wrap items-center gap-2">- <TimeField label="Start" value={value[0]} onCommit={(s) => set(0, s)} />- <TimeField label="End" value={value[1]} onCommit={(s) => set(1, s)} />- <Button variant="outline" size="sm" className="ml-auto rounded-full" onClick={play}>- {playing ? <Pause className="size-3.5" /> : <Play className="size-3.5" />} {playing ? "Pause" : "Play selection"}- </Button>- </div>- </div>- );-}--/** When the browser can't decode the clip: type the times (the server still trims it). */-function ManualRange({ value, onChange }: { value: [number, number]; onChange: (v: [number, number]) => void }) {- const set = (i: 0 | 1, raw: string) => {+/** When the browser can't decode the clip and its header has no length: type the times (the server still trims it). */+function ManualRange({ value, onChange }: { value: TrimRange | null; onChange: (v: TrimRange) => void }) {+ const r = value ?? { startTime: 0, endTime: 0 };+ const set = (edge: "start" | "end", raw: string) => {const t = parseCueTime(raw);if (t === null) return;- onChange(i === 0 ? [t, Math.max(value[1], t + MIN_LENGTH)] : [value[0], Math.max(t, value[0] + MIN_LENGTH)]);+ onChange(edge === "start" ? { startTime: t, endTime: Math.max(r.endTime, t + MIN_LENGTH) } : { startTime: r.startTime, endTime: Math.max(t, r.startTime + MIN_LENGTH) });};return (<div className="space-y-2"><p className="text-[13px] text-muted-foreground">This browser can't preview the clip, but it can still be trimmed — type the times (e.g. 0:03.5).</p><div className="flex flex-wrap items-center gap-2">- <TimeField label="Start" value={value[0]} onCommit={(s) => set(0, s)} />- <TimeField label="End" value={value[1]} onCommit={(s) => set(1, s)} />+ <TimeField label="Start" value={r.startTime} onCommit={(s) => set("start", s)} />+ <TimeField label="End" value={r.endTime} onCommit={(s) => set("end", s)} /></div></div>);diff --git a/src/components/studio/video-trimmer.tsx b/src/components/studio/video-trimmer.tsxindex 78e39285..18689a4c 100644--- a/src/components/studio/video-trimmer.tsx+++ b/src/components/studio/video-trimmer.tsx@@ -2,6 +2,7 @@import { Pause, Play, Volume2, VolumeX } from "lucide-react";import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";+import { realDuration } from "@/components/av/frame-sampler";import { clampRange, clock, initialRange, moveRange, parseTime, setEdge, thumbTimes, trimHint, trimKey, type TrimLimits, type TrimRange } from "@/lib/trim-range";import { cn } from "@/lib/utils";@@ -11,8 +12,8 @@ export type { TrimRange } from "@/lib/trim-range";* Pick a part of a clip: a filmstrip of frames grabbed in the browser, a draggable window with two* handles (min/max length enforced), "play the selection", and typed start/end times. Keyboard: the* handles and the window are sliders (arrows 0.1 s, Shift ×10, Page Up/Down 5 s, Home/End).- * Used by Shorts Studio and Mixed Media; reusable anywhere a clip needs trimming (Ad Multiplier,- * Motion control).+ * Used by Shorts Studio, Mixed Media, Video tools → Trim and the Ad Multiplier; reusable anywhere a+ * clip needs trimming (Motion control).*/export interface VideoTrimmerHandle {@@ -35,6 +36,11 @@ export interface VideoTrimmerProps {/** Overrides the "Select a 10-second segment" line. */hint?: string;onMeta?: (m: { duration: number; width: number; height: number }) => void;+ /**+ * This browser can't decode the clip (no frames, no length: e.g. H.265 without the codec). The+ * caller can pass the length from the file's header as `duration` (the times still work), or offer typed times.+ */+ onUnreadable?: () => void;/** Hide the clip preview above the filmstrip. */noPreview?: boolean;className?: string;@@ -106,7 +112,7 @@ function makeVideo(src: string): HTMLVideoElement {const STEP = 0.1;export const VideoTrimmer = forwardRef<VideoTrimmerHandle, VideoTrimmerProps>(function VideoTrimmer(- { src, value, onChange, min, max, duration: knownDuration, label = "Part of the clip", hint, onMeta, noPreview, className },+ { src, value, onChange, min, max, duration: knownDuration, label = "Part of the clip", hint, onMeta, onUnreadable, noPreview, className },ref,) {const video = useRef<HTMLVideoElement>(null);@@ -154,13 +160,17 @@ export const VideoTrimmer = forwardRef<VideoTrimmerHandle, VideoTrimmerProps>(fu(async () => {const ok = await loaded(v);if (cancelled) return;- const len = Number.isFinite(v.duration) && v.duration > 0 ? v.duration : (knownDuration ?? 0);+ const headerLength = Number.isFinite(v.duration) && v.duration > 0;+ // A recording with no length in its header (MediaRecorder WebM): the browser finds it at the end.+ const len = (headerLength ? v.duration : ok && v.videoWidth ? await realDuration(v) : null) || (knownDuration ?? 0);+ if (cancelled) return;if (!ok || !v.videoWidth || !len) {setUnsupported(true);+ onUnreadable?.();return;}- // Without the preview, this copy is where the length and shape come from.- if (noPreview) {+ // Without the preview (or when its header has no length), this copy is where the length and shape come from.+ if (noPreview || !headerLength) {setDuration((cur) => cur ?? len);onMeta?.({ duration: len, width: v.videoWidth, height: v.videoHeight });}diff --git a/src/lib/catalog/marketing.ts b/src/lib/catalog/marketing.tsindex 98880d94..142dea32 100644--- a/src/lib/catalog/marketing.ts+++ b/src/lib/catalog/marketing.ts@@ -676,45 +676,6 @@ const tenth = (n: number) => Math.round(n * 10) / 10;/** The first usable part of a fresh clip: all of it, or its first 30 s. */export const initialClip = (duration: number): ClipRange => ({ start: 0, end: tenth(Math.min(duration, MULTIPLIER.maxSeconds)) });-/**- * Keep an in/out range inside the clip and within 4–30 s where the clip allows: the point that- * moved stays put and the other one follows (a clip shorter than 4 s stays as it is).- */-export function clampClip(r: ClipRange, duration: number, moved: "start" | "end"): ClipRange {- const { minSeconds: min, maxSeconds: max } = MULTIPLIER;- let start = Math.min(Math.max(0, r.start), duration);- let end = Math.min(Math.max(0, r.end), duration);- if (moved === "start") {- if (end - start > max) end = Math.min(duration, start + max);- if (end - start < min) end = Math.min(duration, start + min);- if (end - start < min) start = Math.max(0, end - min);- } else {- if (end - start > max) start = Math.max(0, end - max);- if (end - start < min) start = Math.max(0, end - min);- if (end - start < min) end = Math.min(duration, start + min);- }- return { start: tenth(start), end: tenth(end) };-}--/** A time typed into an in/out field: "12", "12.5", "12,5", "0:12.5" or "1:02" (seconds); null when it isn't one. */-export function parseClipTime(text: string): number | null {- const t = text.trim().replace(",", ".");- const m = /^(?:(\d+):)?(\d+(?:\.\d*)?|\.\d+)$/.exec(t);- if (!m) return null;- const s = (m[1] ? Number(m[1]) * 60 : 0) + Number(m[2]);- return Number.isFinite(s) ? s : null;-}--/**- * The range after the user finishes typing an in or out time (blur or Enter): the typed time is kept- * and the other point follows (clampClip). Keystrokes before that don't move anything, so "20" isn't- * clamped at its first digit.- */-export function commitClipTime(text: string, range: ClipRange, duration: number, moved: "start" | "end"): ClipRange | null {- const n = parseClipTime(text);- return n == null ? null : clampClip({ ...range, [moved]: n }, duration, moved);-}-export interface MultiplierParts {mode: "prompt" | "sections";prompt?: string;diff --git a/tests/marketing-client.test.ts b/tests/marketing-client.test.tsindex 39a55583..9fecc804 100644--- a/tests/marketing-client.test.ts+++ b/tests/marketing-client.test.ts@@ -1,7 +1,8 @@import zlib from "node:zlib";import { describe, expect, it } from "vitest";import { crc32, uniqueNames, zipFiles } from "@/components/ads/zip";-import { clampClip, initialClip, MULTIPLIER } from "@/lib/catalog/marketing";+import { initialClip, MULTIPLIER } from "@/lib/catalog/marketing";+import { clampRange, setEdge } from "@/lib/trim-range";/** Read a stored zip back: every entry's name and bytes, from the central directory. */function readZip(zip: Uint8Array): { name: string; data: Uint8Array; crc: number }[] {@@ -63,16 +64,17 @@ describe("Ad Multiplier in/out points", () => {expect(initialClip(95)).toEqual({ start: 0, end: MULTIPLIER.maxSeconds });});- it("keeps the range 4–30 s inside the clip, moving the other point", () => {- // Out point dragged far: the in point follows to keep 30 s.- expect(clampClip({ start: 0, end: 50 }, 60, "end")).toEqual({ start: 20, end: 50 });- // In point dragged past the out point: the out point moves to keep 4 s.- expect(clampClip({ start: 20, end: 21 }, 60, "start")).toEqual({ start: 20, end: 24 });- // Near the end of the clip the in point gives way instead.- expect(clampClip({ start: 58, end: 60 }, 60, "start")).toEqual({ start: 56, end: 60 });+ it("keeps the selection 4–30 s inside the clip (the shared trimmer with the multiplier's limits)", () => {+ const L = { duration: 60, min: MULTIPLIER.minSeconds, max: MULTIPLIER.maxSeconds };+ const r = (startTime: number, endTime: number) => ({ startTime, endTime });+ // The out point dragged far: it stops 30 s after the in point.+ expect(clampRange(r(0, 50), L, "end")).toEqual(r(0, 30));+ // A typed out time past the limit keeps the in point too; the window slides to pick another part.+ expect(setEdge(r(12, 16), "end", 20, L)).toEqual(r(12, 20));+ expect(clampRange(r(20, 21), L, "start")).toEqual(r(17, 21));// Out of bounds values are pulled back in.- expect(clampClip({ start: -3, end: 70 }, 60, "start")).toEqual({ start: 0, end: 30 });- // A clip under 4 s can't be fixed by trimming; it stays whole (the form says why).- expect(clampClip({ start: 0, end: 3 }, 3, "end")).toEqual({ start: 0, end: 3 });+ expect(clampRange(r(-3, 70), L, "move")).toEqual(r(0, 30));+ // A clip under 4 s can't be fixed by trimming: it stays whole (the form says why).+ expect(clampRange(r(0, 3), { ...L, duration: 3 }, "end")).toEqual(r(0, 3));});});diff --git a/tests/marketing-fixes.test.ts b/tests/marketing-fixes.test.tsindex 84975778..6416d059 100644--- a/tests/marketing-fixes.test.ts+++ b/tests/marketing-fixes.test.ts@@ -328,23 +328,6 @@ describe("@product mentions in the chat box", () => {});});-describe("in/out times in the Ad Multiplier", () => {- it("don't move while typed; the range is clamped once the time is committed", () => {- const range = { start: 12, end: 16 };- // Typing "20" into Out: nothing is applied per keystroke, then 12–20 on Enter / blur.- expect(cat.commitClipTime("20", range, 60, "end")).toEqual({ start: 12, end: 20 });- expect(cat.commitClipTime("35", range, 60, "end")).toEqual({ start: 12, end: 35 });- // Past the 30 s limit, the other point follows.- expect(cat.commitClipTime("50", range, 60, "end")).toEqual({ start: 20, end: 50 });- expect(cat.commitClipTime("0:45.5", { start: 20, end: 30 }, 60, "end")).toEqual({ start: 20, end: 45.5 });- expect(cat.commitClipTime("abc", range, 60, "end")).toBeNull();- expect(cat.parseClipTime("1:02")).toBe(62);- expect(cat.parseClipTime("12,5")).toBe(12.5);- expect(cat.parseClipTime(".5")).toBe(0.5);- expect(cat.parseClipTime("")).toBeNull();- });-});-describe("composer details", () => {it("a template opens in its own shape, else the format's when the format changes", () => {// Hero Headline (Ads) after a 3:4 product shot opens 4:5, the Ads default.