Open source CapCut alternative.
TypeScript
fix(cut): export with source settings and reuse encoded media [rebuild]
David Le2a6f4588886d
diff --git a/docs/guides/cut/README.md b/docs/guides/cut/README.mdindex 32f4bd9b..a63c594b 100644--- a/docs/guides/cut/README.md+++ b/docs/guides/cut/README.md@@ -52,7 +52,7 @@ Guides draw over the preview from the button beside the timeline zoom: thirds, c## The export-Exports use the preview's compositor and mixer. Best matches source dimensions, frame rate and video/audio bitrates, including low-resolution footage; project aspect and edits still apply. Named resolutions reach down to 240p. Explicit resolution, bitrate and ProRes choices control delivery. Extra soundtrack audio keeps the delivery audio budget. The dialog exports the whole timeline or a selection, names the file, and saves captions as SRT. Master uses ProRes 4444 to preserve graphics' color detail. Smooth slow motion estimates intermediate frames; browsers without WebGPU blend them. Files land in the project's home: browser storage, the Mac project folder, or cloud storage. A browser without the required encoder hands rendering to the project's machine. The [local-compute guide](local-compute.md) covers that boundary.+Best uses original resolution, cadence, supported H.264/HEVC codec and audio settings. Whole files and trims copy compressed streams; compatible sequences copy video and encode joined audio. Interior joins need matching codec configurations and keyframes. Effects and incompatible joins render at source settings. Browser, Mac and cloud share packet copying; audio joins use FFmpeg on the project’s machine. Files land in project storage. The [local-compute guide](local-compute.md) covers browser handoff.## Sharingdiff --git a/site/src/cut/components/ExportDialog.tsx b/site/src/cut/components/ExportDialog.tsxindex fbbd0ada..7cf5d427 100644--- a/site/src/cut/components/ExportDialog.tsx+++ b/site/src/cut/components/ExportDialog.tsx@@ -81,8 +81,8 @@ export function ExportDialog() {[clips, audioClips, overlays]);const resolutions = useMemo(- () => resolutionOptions(aspect, clips, assets),- [aspect, clips, assets]+ () => resolutionOptions(aspect, clips, assets, { audioClips, overlays, subtitles }),+ [aspect, clips, assets, audioClips, overlays, subtitles]);// The size rungs in slider order, smallest on the left, largest on the right.const rungs = useMemo(() => [...resolutions].reverse(), [resolutions]);@@ -134,7 +134,7 @@ export function ExportDialog() {const settings = useMemo<ExportSettings>(() => ({...choiceSettings(choice, resolutions, sourceFps ?? DEFAULT_EXPORT_FPS,- !probing && probe ? { ...probe, ...(audioClips.length > 0 ? { audioBitrate: undefined } : {}) } : undefined),+ !probing && probe ? { ...probe, ...(audioClips.length > 0 ? { audioBitrate: undefined, audioSampleRate: undefined, audioChannels: undefined } : {}) } : undefined),...(typedName ? { name: baseName } : {}),...(range ? { range } : {}),}),@@ -306,7 +306,7 @@ export function ExportDialog() {</SelectTrigger><SelectContent align="end"><SelectItem value="source" title="The rate the footage plays at">- {probing ? "Source · reading…" : `Source · ${sourceFps ?? DEFAULT_EXPORT_FPS} fps`}+ {probing ? "Source · reading…" : `Source · ${Number((sourceFps ?? DEFAULT_EXPORT_FPS).toFixed(3))} fps`}</SelectItem>{EXPORT_FRAME_RATES.map((f) => (<SelectItem key={f} value={String(f)}>@@ -326,6 +326,7 @@ export function ExportDialog() {set({container: f.container,codec: f.codec,+ sourceCodec: false,...(fixedRate(f.codec) ? { bitrateMbps: undefined } : {}),// MP4 cannot carry PCM either; picking it turns the audio to AAC....(f.container === "mp4" && choice.audioCodec === "pcm" ? { audioCodec: "aac" } : {}),diff --git a/site/src/cut/components/Timeline.tsx b/site/src/cut/components/Timeline.tsxindex 635b581c..65f5668c 100644--- a/site/src/cut/components/Timeline.tsx+++ b/site/src/cut/components/Timeline.tsx@@ -4135,7 +4135,7 @@ function ClipMaskKeyStrip({}/** Render just this timeline item through the normal export pipeline: a- * one-clip cut at the project aspect, trimmed and paced like the segment on+ * one-clip cut using source settings, trimmed and paced like the segment on* the timeline, landing in the project's exports folder and the dock like any* full export. */function exportSegment(asset: MediaAsset, clip: VideoClip | AudioClip) {@@ -4160,7 +4160,7 @@ function exportSegment(asset: MediaAsset, clip: VideoClip | AudioClip) {overlays: [],subtitles: emptySubtitles(),};- const settings = originalSettings(s.aspect, doc.clips, doc.assets);+ const settings = originalSettings(s.aspect, doc.clips, doc.assets, doc);void useExports.getState().start(s.projectId, doc, settings, s.projectName);}diff --git a/site/src/cut/components/TopBar.tools.ts b/site/src/cut/components/TopBar.tools.tsindex 025a778f..dca9b86d 100644--- a/site/src/cut/components/TopBar.tools.ts+++ b/site/src/cut/components/TopBar.tools.ts@@ -48,7 +48,7 @@ export const TOP_BAR_TOOLS = [{name: "open_export",description:- `Open the export dialog: Best defaults to source resolution and video/audio bitrates, including sources below 720p. Other presets are Share, Social 4K, Small and Master. Controls include file name, whole video or selection range, MP4/MOV, H.264/HEVC/ProRes, resolution (${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}, Source), frame rate, quality or custom bitrate, AAC/PCM, and an SRT captions file. Exporting itself stays a user action.`,+ `Open the export dialog: Best uses original resolution, frame rate, supported H.264/HEVC codec and audio settings. Whole files, trims and compatible sequences copy compressed video; joined audio is encoded at source settings. Effects or incompatible joins render with source settings. Other presets are Share, Social 4K, Small and Master. Controls include file name, whole video or selection range, MP4/MOV, H.264/HEVC/ProRes, resolution (${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}, Source), frame rate, quality or custom bitrate, AAC/PCM, and an SRT captions file. Exporting itself stays a user action.`,inputSchema: obj({}),},] as const satisfies readonly AiToolDef[];diff --git a/site/src/cut/lib/exportClient.ts b/site/src/cut/lib/exportClient.tsindex 65f48b4f..51e0d834 100644--- a/site/src/cut/lib/exportClient.ts+++ b/site/src/cut/lib/exportClient.ts@@ -1,6 +1,7 @@"use client";import { captureRenderSnapshot, renderDoc, type ExportDoc, type RenderSnapshot } from "./renderSnapshot";+import { sourceExportPlan, sourceSequence } from "@/cut/lib/sourceExportPlan";import { DELIVERY_DEFAULTS, EXPORT_PRESETS, EXPORT_RESOLUTIONS } from "./exportPresets";import { operationFailure, type OperationFailure } from "./operationFailure";import { projectOperation } from "./projectOperation";@@ -17,7 +18,7 @@ import { exportsDir, projectDir, writeFileAt, readFileAt, saveExport } from "./bimport { holdRegistered, registerBlobFile, releaseRegistered, resolveRegisteredBlob } from "./backend/browser/registry";import { captureCloudBackend } from "./backend/cloud";import { downloadFile, downloadFromUrl } from "./download";-import { bitrateFor, canRenderInBrowser, renderProjectToMp4 } from "./exportRender";+import { bitrateFor, canRenderInBrowser, renderProjectToMp4, type SourceExportProfile } from "./exportRender";import { putSigned } from "./media";import { renderRemovalPieces } from "./removalVideo";import { drawBlock } from "./blockSource";@@ -57,6 +58,10 @@ export { deliveryCodec, EXPORT_CODECS, EXPORT_CONTAINERS, fixedRate };export type { ExportAudioCodec, ExportCodec, ExportContainer, ExportRange };export interface ExportSettings {+ /** Resolve the original media settings before starting an export. */+ matchSource?: boolean;+ /** Source delivery can preserve compatible encoded packets. */+ copySource?: boolean;width: number;height: number;fps: number;@@ -71,6 +76,8 @@ export interface ExportSettings {bitrate?: number;/** AAC bitrate in bits per second; omitted uses the delivery default. */audioBitrate?: number;+ audioSampleRate?: number;+ audioChannels?: number;/** The file's name without its extension, as typed; absent = the project's* name. Sanitized by `exportBaseName` wherever a file is named. */name?: string;@@ -110,6 +117,7 @@ export type ExportQualityId = (typeof EXPORT_QUALITIES)[number]["id"];/** The user's whole choice, as the dialog holds it. */export interface ExportChoice {+ sourceCodec?: boolean;/** A `resolutionOptions` id; one the project lacks falls back to "source". */resolution: string;/** A fixed rate, or "source" for the rate the footage plays at. */@@ -137,9 +145,9 @@ export const EXPORT_QUICK_PRESETS = [{id: "best",label: "Best",- detail: "source size · H.264",+ detail: "original file settings",short: "Source",- choice: { resolution: "source", fps: "source", quality: "high", ...DELIVERY_DEFAULTS },+ choice: { resolution: "source", fps: "source", quality: "high", sourceCodec: true, ...DELIVERY_DEFAULTS },},{id: "social4k",@@ -167,7 +175,7 @@ export const EXPORT_QUICK_PRESETS = [/** The quick preset a choice is, when it is one. */export function quickPresetOf(choice: ExportChoice, options: ResolutionOption[]): string | null {const key = (c: ExportChoice) =>- [resolveResolution(options, c.resolution).id, c.fps, c.quality, c.codec, c.container, c.audioCodec, c.bitrateMbps ?? ""].join("|");+ [resolveResolution(options, c.resolution).id, c.fps, c.quality, c.codec, c.container, c.audioCodec, c.bitrateMbps ?? "", c.sourceCodec ?? false].join("|");const k = key(choice);return EXPORT_QUICK_PRESETS.find((p) => key(p.choice) === k)?.id ?? null;}@@ -189,17 +197,18 @@ export function choiceSettings(choice: ExportChoice,options: ResolutionOption[],sourceFps: number = DEFAULT_EXPORT_FPS,- sourceRates?: { videoBitrate?: number; audioBitrate?: number }+ sourceRates?: Partial<SourceExportProfile>): ExportSettings {const q = EXPORT_QUALITIES.find((x) => x.id === choice.quality) ?? EXPORT_QUALITIES[0];const r = resolveResolution(options, choice.resolution);const settings = fitContainer({+ copySource: choice.resolution === "source" && choice.fps === "source" && choice.quality === "high" && !choice.bitrateMbps,width: r.width,height: r.height,fps: choice.fps === "source" ? sourceFps : choice.fps,crf: q.crf,preset: q.preset,- codec: choice.codec,+ codec: choice.sourceCodec ? sourceRates?.codec ?? choice.codec : choice.codec,container: choice.container,audioCodec: choice.audioCodec,// A fixed-rate codec has one rate per profile; a typed bitrate is for@@ -216,18 +225,25 @@ export function choiceSettings(/** Source-size delivery keeps the source's compression budget. */export function matchSourceBitrates(settings: ExportSettings,- source?: { videoBitrate?: number; audioBitrate?: number }+ source?: Partial<SourceExportProfile>): ExportSettings {if (fixedRate(settings.codec)) return settings;return {...settings,+ ...(source?.audioSampleRate ? { audioSampleRate: source.audioSampleRate } : {}),+ ...(source?.audioChannels ? { audioChannels: source.audioChannels } : {}),...(source?.videoBitrate && Number.isFinite(source.videoBitrate) && source.videoBitrate > 0- ? { bitrate: Math.round(Math.min(bitrateFor(settings), source.videoBitrate)) } : {}),+ ? { bitrate: Math.round(settings.copySource ? source.videoBitrate : Math.min(bitrateFor(settings), source.videoBitrate)) } : {}),...(settings.audioCodec === "aac" && source?.audioBitrate && Number.isFinite(source.audioBitrate) && source.audioBitrate > 0- ? { audioBitrate: Math.round(Math.min(audioBitrate(settings), source.audioBitrate)) } : {}),+ ? { audioBitrate: Math.round(settings.copySource ? source.audioBitrate : Math.min(audioBitrate(settings), source.audioBitrate)) } : {}),};}+/** Apply a probed source profile to an original-settings export. */+export function matchSourceSettings(settings: ExportSettings, source: SourceExportProfile): ExportSettings {+ return matchSourceBitrates({ ...settings, matchSource: false, fps: source.fps ?? settings.fps, codec: source.codec ?? settings.codec }, source);+}+/** A size the dialog offers: the source's own frame, or a named rung above* or below it. */export interface ResolutionOption {@@ -253,9 +269,10 @@ export interface ResolutionOption {export function resolutionOptions(aspect: Aspect,clips: VideoClip[],- assets: MediaAsset[]+ assets: MediaAsset[],+ composition?: Pick<ExportDoc, "audioClips" | "overlays" | "subtitles">): ResolutionOption[] {- const src = sourceFrame(aspect, clips, assets);+ const src = sourceFrame(aspect, clips, assets, composition);const srcShort = Math.min(src.width, src.height);const rung = (r: (typeof EXPORT_RESOLUTIONS)[number]): ResolutionOption => ({id: r.id,@@ -323,23 +340,28 @@ export function presetSettings(}/**- * Source dimensions fitted to the project aspect, capped at 4K.+ * Plain source sequences keep their original frame. Compositions fit the+ * project aspect, capped at 4K.* Projects with no measured source dimensions use the base frame.*/export function originalSettings(aspect: Aspect,clips: VideoClip[],- assets: MediaAsset[]+ assets: MediaAsset[],+ composition?: Pick<ExportDoc, "audioClips" | "overlays" | "subtitles">): ExportSettings {- return { ...sourceFrame(aspect, clips, assets), fps: 30, crf: 19, preset: "medium", ...DELIVERY_DEFAULTS };+ return { ...sourceFrame(aspect, clips, assets, composition), copySource: true, matchSource: true, fps: 30, crf: 19, preset: "medium", ...DELIVERY_DEFAULTS };}/** The frame `originalSettings` renders at — see its note for the rules. */export function sourceFrame(aspect: Aspect,clips: VideoClip[],- assets: MediaAsset[]+ assets: MediaAsset[],+ composition?: Pick<ExportDoc, "audioClips" | "overlays" | "subtitles">): { width: number; height: number } {+ const source = composition && sourceSequence({ aspect, clips, assets, ...composition })?.[0];+ if (source) return { width: source.asset.width!, height: source.asset.height! };const base = frameOf(aspect);const longBase = Math.max(base.w, base.h);const sourceScale = Math.max(@@ -365,8 +387,8 @@ export function estimateExportBytes(settings: ExportSettings, durationSec: numbe}/** AAC follows its source budget or uses 192 kbps; PCM is 48 kHz stereo 16-bit. */-export function audioBitrate(settings: Pick<ExportSettings, "audioCodec" | "audioBitrate">): number {- return settings.audioCodec === "pcm" ? 48_000 * 16 * 2 : settings.audioBitrate ?? 192_000;+export function audioBitrate(settings: Pick<ExportSettings, "audioCodec" | "audioBitrate" | "audioSampleRate" | "audioChannels">): number {+ return settings.audioCodec === "pcm" ? (settings.audioSampleRate ?? 48_000) * 16 * (settings.audioChannels ?? 2) : settings.audioBitrate ?? 192_000;}/** Human-readable size estimate matching the finished-export MB display. */@@ -1310,6 +1332,7 @@ export async function buildExportPayload(projectId,target,...settings,+ ...(target === "export" ? { sourceSegments: sourceExportPlan(doc, settings) ?? undefined } : {}),duration,background: projectBackground(doc.background),clips,diff --git a/site/src/cut/lib/exportRender.ts b/site/src/cut/lib/exportRender.tsindex 2552079d..21198ed7 100644--- a/site/src/cut/lib/exportRender.ts+++ b/site/src/cut/lib/exportRender.ts@@ -34,7 +34,7 @@ import { audioFxSpans } from "./audioEffects";import { renderMix, type MixClip, type MixItem, type MixSpec } from "./audioMix";import { FrameCompositor, MISSING_FRAME, type Frame } from "./composite";import { overlayPlan, trackZeroPlan } from "./framePlan";-import { audioTrackOf, frameSink, keyframeTimeAt, openMedia, videoTrackOf } from "./mediaRead";+import { frameSink, keyframeTimeAt, openMedia, videoTrackOf } from "./mediaRead";import type { InputVideoTrack, WrappedCanvas } from "mediabunny";import { allowance, canvasBytes, holdMemory } from "./memoryBudget";import { getClipSpans, overlayLayers, projectDuration, spanSequence } from "./store";@@ -49,6 +49,8 @@ import { assetIsSilent, behindSubjectOverlay, clipCovers, frameOf, frontSubjectOimport type { ClipAnim, ClipSpan, EffectOverlay, MediaAsset, Overlay, StickerOverlay } from "./types";import type { ExportDoc } from "./renderSnapshot";import type { ExportSettings } from "./exportClient";+import { sourceExportPlan } from "@/cut/lib/sourceExportPlan";+import { prepareSourceRemux } from "@/cut/lib/sourceRemux";import { deliverySpan, KEYFRAME_INTERVAL_S, videoBitrateFor } from "./exportDelivery";/** Audio is written at the rate and width a delivery file wants, rather than@@ -160,9 +162,8 @@ function sliceAudio(mix: AudioBuffer, from: number, to: number): AudioBuffer {return out;}-/** The frame rates a delivered file is written at. A source's measured rate- * snaps to the nearest: 23.976 reads as 24, 29.97 as 30, 59.94 as 60. */-const DELIVERY_RATES = [24, 25, 30, 48, 50, 60];+/** Standard cadences retain their fractional rates; unusual rates keep the measured value. */+const DELIVERY_RATES = [24000 / 1001, 24, 25, 30000 / 1001, 30, 48, 50, 60000 / 1001, 60];/** Sources the probe reads for a rate: the ones with the most time on the* timeline, so a cut of many files still answers quickly. */@@ -191,7 +192,7 @@ function rateSources(doc: Pick<ExportDoc, "clips" | "assets">): [string, number].slice(0, RATE_PROBE_SOURCES);}-export type SourceExportProfile = { fps: number | null; videoBitrate?: number; audioBitrate?: number };+export type SourceExportProfile = { fps: number | null; videoBitrate?: number; audioBitrate?: number; codec?: "h264" | "hevc"; audioSampleRate?: number; audioChannels?: number };/** Read cadence and compression budgets from the dominant video sources.* The largest source bitrate preserves detail across the sampled footage;@@ -205,6 +206,7 @@ export async function sourceExportProfile(const seconds = new Map<number, number>();let videoBitrate = 0;let audioBitrate = 0;+ const profiles = new Map<string, Partial<SourceExportProfile>>();await Promise.all(rateSources(doc).map(async ([id, len]) => {if (opts.signal?.aborted) return;@@ -216,10 +218,10 @@ export async function sourceExportProfile(const deadline = setTimeout(close, RATE_PROBE_TIMEOUT_MS);opts.signal?.addEventListener("abort", close, { once: true });try {- const track = await videoTrackOf(input);+ const track = await input.getPrimaryVideoTrack();if (!track) return;const stats = await track.computePacketStats(120);- const audio = await audioTrackOf(input);+ const audio = await input.getPrimaryAudioTrack();const audioStats = audio ? await audio.computePacketStats(120) : null;const sizeBytes = asset.sizeBytes ?? await input.source.getSizeOrNull();const sourceAudio = audioStats?.averageBitrate ?? 0;@@ -227,12 +229,18 @@ export async function sourceExportProfile(const sourceVideo = totalBitrate > sourceAudio ? totalBitrate - sourceAudio : stats.averageBitrate;if (Number.isFinite(sourceVideo)) videoBitrate = Math.max(videoBitrate, sourceVideo);if (Number.isFinite(sourceAudio)) audioBitrate = Math.max(audioBitrate, sourceAudio);+ const codec = await track.getCodec();+ profiles.set(id, {+ ...(codec === "avc" || codec === "hevc" ? { codec: codec === "avc" ? "h264" : "hevc" } : {}),+ ...(audio ? { audioSampleRate: await audio.getSampleRate(), audioChannels: await audio.getNumberOfChannels() } : {}),+ });const rate = stats.averagePacketRate;if (!(rate > 0) || opts.signal?.aborted) return;const snapped = DELIVERY_RATES.reduce((best, r) =>Math.abs(r - rate) < Math.abs(best - rate) ? r : best);- seconds.set(snapped, (seconds.get(snapped) ?? 0) + len);+ const cadence = Math.abs(snapped - rate) / rate < 0.0001 ? snapped : rate;+ seconds.set(cadence, (seconds.get(cadence) ?? 0) + len);} catch {// A source the probe cannot read casts no vote.} finally {@@ -247,7 +255,9 @@ export async function sourceExportProfile(for (const [rate, len] of seconds) {if (pick === null || len > seconds.get(pick)! || (len === seconds.get(pick) && rate > pick)) pick = rate;}- return { fps: pick, ...(videoBitrate > 0 ? { videoBitrate } : {}), ...(audioBitrate > 0 ? { audioBitrate } : {}) };+ const primary = rateSources(doc).map(([id]) => profiles.get(id)).find(Boolean);+ const audioChannels = Math.max(0, ...[...profiles.values()].map((p) => p.audioChannels ?? 0));+ return { ...primary, ...(audioChannels ? { audioChannels } : {}), fps: pick, ...(videoBitrate > 0 ? { videoBitrate } : {}), ...(audioBitrate > 0 ? { audioBitrate } : {}) };}/** The frame reader for one open video source. */@@ -929,6 +939,34 @@ export async function renderProjectToMp4(opts: RenderOptions): Promise<RenderedExport> {const { resolve, onProgress, signal } = opts;+ const trim = sourceExportPlan(doc, settings);+ if (trim && (settings.codec === "h264" || settings.codec === "hevc")) {+ const inputs = new Map<string, ReturnType<typeof openMedia>>();+ try {+ for (const segment of trim) if (!inputs.has(segment.file)) inputs.set(segment.file, openMedia(resolve(doc.assets.find((a) => a.fileName === segment.file)!)));+ const copy = await prepareSourceRemux(inputs, trim, settings.codec);+ if (copy) {+ const dir = await scratchDir();+ void sweepScratch(dir);+ const name = `source-${crypto.randomUUID()}.mp4`;+ const handle = await dir.getFileHandle(name, { create: true });+ const writable = await handle.createWritable();+ const discard = async () => { await dir.removeEntry(name).catch(() => {}); };+ try {+ await copy({+ write: (data, position) => writable.write({ type: "write", position, data: new Uint8Array(data) }),+ truncate: (size) => writable.truncate(size),+ }, (ratio) => onProgress?.({ ratio, stage: "video" }), () => signal?.throwIfAborted());+ await writable.close();+ return { file: await handle.getFile(), discard };+ } catch (error) {+ await writable.abort().catch(() => {});+ await discard();+ throw error;+ }+ }+ } finally { for (const input of inputs.values()) input.dispose(); }+ }const duration = projectDuration(doc);if (!(duration > 0)) throw new Error("There is nothing to export yet.");// The window of the timeline the file carries: a range when the settings@@ -956,8 +994,8 @@ export async function renderProjectToMp4(onProgress?.({ ratio: 0, stage: "audio" });const whole = await renderMix(mixSpecFor(doc, resolve), {- sampleRate: AUDIO_RATE,- channels: AUDIO_CHANNELS,+ sampleRate: settings.audioSampleRate ?? AUDIO_RATE,+ channels: settings.audioChannels ?? AUDIO_CHANNELS,resolve: (file) => file, // mixSpecFor already resolved each asset to a URL});const mix = whole && settings.range ? sliceAudio(whole, from, from + span) : whole;@@ -1007,8 +1045,8 @@ export async function renderProjectToMp4(// and a cut with sound keeps it: an Opus stand-in plays nowhere the// user is taking the file, so a browser without AAC hands the render on.const audioCodec = await getFirstEncodableAudioCodec([deliveryAudioCodec(settings)], {- numberOfChannels: AUDIO_CHANNELS,- sampleRate: AUDIO_RATE,+ numberOfChannels: settings.audioChannels ?? AUDIO_CHANNELS,+ sampleRate: settings.audioSampleRate ?? AUDIO_RATE,});if (!audioCodec) throw new Error("This browser can't encode AAC audio.");audio = new AudioBufferSource({@@ -1556,6 +1594,14 @@ export async function canRenderInBrowser(return false;}try {+ const trim = sourceExportPlan(doc, settings);+ if (trim && (settings.codec === "h264" || settings.codec === "hevc")) {+ const inputs = new Map<string, ReturnType<typeof openMedia>>();+ try {+ for (const segment of trim) if (!inputs.has(segment.file)) inputs.set(segment.file, openMedia(doc.assets.find((a) => a.fileName === segment.file)!.url));+ return !!await prepareSourceRemux(inputs, trim, settings.codec); }+ finally { for (const input of inputs.values()) input.dispose(); }+ }const wanted = deliveryVideoCodec(settings);if (!wanted) return false;const video = await getFirstEncodableVideoCodec([wanted], {@@ -1568,8 +1614,8 @@ export async function canRenderInBrowser(// muxer, or hand back a video whose sound went missing.if (!mixHasSound(mixSpecFor(doc, (a) => a.url))) return true;return !!(await getFirstEncodableAudioCodec([deliveryAudioCodec(settings)], {- numberOfChannels: AUDIO_CHANNELS,- sampleRate: AUDIO_RATE,+ numberOfChannels: settings.audioChannels ?? AUDIO_CHANNELS,+ sampleRate: settings.audioSampleRate ?? AUDIO_RATE,}));} catch {return false;diff --git a/site/src/cut/lib/exportSettings.test.ts b/site/src/cut/lib/exportSettings.test.tsindex cce93114..8c7892fd 100644--- a/site/src/cut/lib/exportSettings.test.ts+++ b/site/src/cut/lib/exportSettings.test.ts@@ -46,3 +46,18 @@ test("custom bitrate and explicit upscale presets keep their chosen budgets", ()expect(choiceSettings(EXPORT_QUICK_PRESETS[2].choice, options, 30, source).bitrate).toBeUndefined();expect(choiceSettings(EXPORT_QUICK_PRESETS[4].choice, options, 30, source).audioBitrate).toBeUndefined();});++test("Best uses the source codec, fractional cadence and audio format", () => {+ const options = resolutionOptions("4:3", [clip], [asset]);+ const profile = { codec: "hevc" as const, videoBitrate: 150_000, audioBitrate: 48_000, audioSampleRate: 44_100, audioChannels: 1 };+ const settings = choiceSettings(best, options, 30000 / 1001, profile);+ expect(settings).toMatchObject({ codec: "hevc", fps: 30000 / 1001, audioSampleRate: 44_100, audioChannels: 1, bitrate: 150_000, audioBitrate: 48_000, copySource: true });+ expect(choiceSettings({ ...best, codec: "h264", sourceCodec: false }, options, 30, profile).codec).toBe("h264");+});+++test("original settings preserve source bitrates above the normal delivery budget", () => {+ const settings = choiceSettings(best, resolutionOptions("4:3", [clip], [asset]), 30, { videoBitrate: 10_000_000, audioBitrate: 256_000 });+ expect(settings.bitrate).toBe(10_000_000);+ expect(settings.audioBitrate).toBe(256_000);+});diff --git a/site/src/cut/lib/exportStore.ts b/site/src/cut/lib/exportStore.tsindex 4f2c69ff..686a051a 100644--- a/site/src/cut/lib/exportStore.ts+++ b/site/src/cut/lib/exportStore.ts@@ -8,6 +8,7 @@ import { browserBackend } from "./backend/browser";import { cloudBackend } from "./backend/cloud";import { localBackend } from "./backend/local";import {+ matchSourceSettings,cancelExportJob,createExportJob,ExportRefusedError,@@ -16,7 +17,7 @@ import {type ExportSettings,} from "./exportClient";import type { ExportDoc } from "./renderSnapshot";-import { canRenderInBrowser } from "./exportRender";+import { canRenderInBrowser, sourceExportProfile } from "./exportRender";import { useGenNotify } from "./genNotify";import { STORAGE_FULL } from "./operationFailure";import { emitStorageQuota } from "./storageQuota";@@ -111,6 +112,10 @@ export const useExports = create<ExportsState>((set, get) => ({start: async (projectId, doc, settings, projectName) => {const localId = `local-${crypto.randomUUID().slice(0, 8)}`;const backend = getBackend();+ if (settings.matchSource) {+ const source = await sourceExportProfile(doc, (asset) => asset.url);+ settings = matchSourceSettings(settings, { ...source, ...(doc.audioClips.length ? { audioBitrate: undefined, audioSampleRate: undefined, audioChannels: undefined } : {}) });+ }// Every project renders in the tab: the file matches the preview because// the compositor that drew the stage and the graph that played the sound// draw and mix the file. A browser that can't carry the render — nodiff --git a/site/src/cut/lib/headless/docExport.ts b/site/src/cut/lib/headless/docExport.tsindex bd68b4b2..ecd8d335 100644--- a/site/src/cut/lib/headless/docExport.ts+++ b/site/src/cut/lib/headless/docExport.ts@@ -4,7 +4,7 @@ import {buildExportPayload,EXPORT_PRESETS,originalSettings,- matchSourceBitrates,+ matchSourceSettings,presetSettings,previewSettings,type ExportSettings,@@ -26,8 +26,8 @@ async function settingsFor(preset: DocExportPreset, doc: ExportDoc): Promise<Expconst fixed = EXPORT_PRESETS.find((p) => p.id === preset);if (fixed) return presetSettings(fixed, doc.aspect);const source = await sourceExportProfile(doc, (asset) => asset.url);- return matchSourceBitrates({ ...originalSettings(doc.aspect, doc.clips, doc.assets), fps: source.fps ?? 30 },- { ...source, ...(doc.audioClips.length > 0 ? { audioBitrate: undefined } : {}) });+ return matchSourceSettings(originalSettings(doc.aspect, doc.clips, doc.assets, doc),+ { ...source, ...(doc.audioClips.length > 0 ? { audioBitrate: undefined, audioSampleRate: undefined, audioChannels: undefined } : {}) });}/**diff --git a/site/src/cut/lib/sourceExportPlan.test.ts b/site/src/cut/lib/sourceExportPlan.test.tsnew file mode 100644index 00000000..9a81e5af--- /dev/null+++ b/site/src/cut/lib/sourceExportPlan.test.ts@@ -0,0 +1,57 @@+import { expect, test } from "bun:test";+import { choiceSettings, EXPORT_QUICK_PRESETS, originalSettings, resolutionOptions, buildExportPayload } from "@/cut/lib/exportClient";+import { sourceExportPlan, sourceSequence } from "@/cut/lib/sourceExportPlan";+import type { ExportDoc } from "@/cut/lib/renderSnapshot";+import type { VideoClip } from "@/cut/lib/types";++const doc: ExportDoc = {+ aspect: "16:9", assets: [{ id: "source", fileName: "source.mp4", name: "Source", type: "video", duration: 904, width: 320, height: 240, url: "" }],+ clips: [{ id: "clip", assetId: "source", track: 0, start: 0, in: 15.137, out: 870.437, muted: false }],+ audioClips: [], overlays: [], subtitles: { cues: [], showOnVideo: false, showOnTimeline: false },+};+const settings = originalSettings(doc.aspect, doc.clips, doc.assets, doc);++test("a plain trim preserves the source frame and exact source window", async () => {+ expect(settings).toMatchObject({ width: 320, height: 240, copySource: true });+ expect(sourceExportPlan(doc, settings)).toEqual([{ file: "source.mp4", from: 15.137, to: 870.437 }]);+ const payload = await buildExportPayload("project", doc, settings, "export");+ expect(payload.spec).toMatchObject({ sourceSegments: [{ file: "source.mp4", from: 15.137, to: 870.437 }] });+ expect("sourceSegments" in (await buildExportPayload("project", doc, settings, "preview")).spec).toBe(false);+});++test("selection ranges resolve inside the original trim", () => {+ expect(sourceExportPlan(doc, { ...settings, range: { start: 3, end: 8 } }))+ .toEqual([{ file: "source.mp4", from: 18.137, to: 23.137 }]);+ expect(sourceExportPlan(doc, { ...settings, range: { start: 900, end: 950 } })).toBeNull();+});++test("explicit delivery choices keep rendering", () => {+ const options = resolutionOptions(doc.aspect, doc.clips, doc.assets, doc);+ const best = EXPORT_QUICK_PRESETS[1].choice;+ expect(sourceExportPlan(doc, choiceSettings(best, options))).not.toBeNull();+ for (const choice of [{ ...best, fps: 24 }, { ...best, bitrateMbps: 1 }, { ...best, quality: "small" as const }, EXPORT_QUICK_PRESETS[0].choice, EXPORT_QUICK_PRESETS[4].choice]) {+ expect(sourceExportPlan(doc, choiceSettings(choice, options))).toBeNull();+ }+});++test("picture, timing and audio treatments require the compositor", () => {+ const changes: Partial<VideoClip>[] = [+ { start: 1 }, { muted: true }, { volume: 0.5 }, { fit: "fill" }, { zoom: 1.1 },+ { rotation: 90 }, { flipH: true }, { speed: 2 }, { reverse: true }, { hidden: true },+ { opacity: 0.5 }, { transition: 1 }, { frame: { x: 0, y: 0, w: 0.5, h: 1 } },+ { grade: { exposure: 1 } }, { kf: [] },+ ];+ for (const change of changes) expect(sourceSequence({ ...doc, clips: [{ ...doc.clips[0], ...change }] })).toBeNull();+ expect(sourceSequence({ ...doc, clips: [...doc.clips, doc.clips[0]] })).toBeNull();+ expect(sourceSequence({ ...doc, audioClips: [{ id: "a", assetId: "source", start: 0, in: 0, out: 3, volume: 1 }] })).toBeNull();+});++test("whole files, contiguous splits and reordered sequences produce source plans", () => {+ const clip = { ...doc.clips[0], in: 0, out: 10 };+ expect(sourceExportPlan({ ...doc, clips: [clip] }, settings)).toEqual([{ file: "source.mp4", from: 0, to: 10 }]);+ const split = { ...doc, clips: [{ ...clip, out: 3.137 }, { ...clip, id: "split", in: 3.137, start: 3.137 }] };+ expect(sourceExportPlan(split, settings)).toEqual([{ file: "source.mp4", from: 0, to: 10 }]);+ const sequence = { ...doc, clips: [{ ...clip, in: 4, out: 8 }, { ...clip, id: "second", start: 4, out: 2 }] };+ expect(sourceExportPlan(sequence, settings)).toEqual([{ file: "source.mp4", from: 4, to: 8 }, { file: "source.mp4", from: 0, to: 2 }]);+ expect(sourceExportPlan(sequence, { ...settings, range: { start: 2, end: 5 } })).toEqual([{ file: "source.mp4", from: 6, to: 8 }, { file: "source.mp4", from: 0, to: 1 }]);+});diff --git a/site/src/cut/lib/sourceExportPlan.ts b/site/src/cut/lib/sourceExportPlan.tsnew file mode 100644index 00000000..164b7933--- /dev/null+++ b/site/src/cut/lib/sourceExportPlan.ts@@ -0,0 +1,53 @@+import type { ExportDoc } from "@/cut/lib/renderSnapshot";+import type { ExportSettings } from "@/cut/lib/exportClient";+import type { VideoClip } from "@/cut/lib/types";++export type SourceSegment = { file: string; from: number; to: number };++/** Plain sequential clips can reuse their source tracks. */+export function sourceSequence(doc: ExportDoc) {+ if (!doc.clips.length || doc.audioClips.length || doc.overlays.length ||+ (doc.subtitles.showOnVideo && doc.subtitles.cues.length)) return null;+ const clips = [...doc.clips].sort((a, b) => a.start - b.start);+ const segments: { asset: ExportDoc["assets"][number]; from: number; to: number }[] = [];+ let end = 0;+ const neutral: Partial<Record<keyof VideoClip, unknown>> = {+ track: 0, muted: false, volume: 1, fit: "fit", zoom: 1,+ panX: 0, panY: 0, flipH: false, flipV: false, rotation: 0, opacity: 1,+ speed: 1, reverse: false, smoothSlow: false, transition: 0, hidden: false,+ };+ const metadata = new Set(["id", "assetId", "name", "groupId", "in", "out", "start"]);+ for (const clip of clips) {+ if (Math.abs(clip.start - end) > 0.000001) return null;+ for (const [key, value] of Object.entries(clip)) {+ if (metadata.has(key) || value === undefined) continue;+ if (!(key in neutral) || value !== neutral[key as keyof VideoClip]) return null;+ }+ const asset = doc.assets.find((a) => a.id === clip.assetId);+ if (!asset || asset.type !== "video" || asset.block || !asset.width || !asset.height ||+ !Number.isFinite(clip.in) || !Number.isFinite(clip.out) || clip.in < 0 || clip.out <= clip.in || clip.out > asset.duration + 0.000001) return null;+ if (segments.length && (asset.width !== segments[0].asset.width || asset.height !== segments[0].asset.height)) return null;+ const previous = segments.at(-1);+ if (previous?.asset.id === asset.id && Math.abs(previous.to - clip.in) < 0.000001) previous.to = clip.out;+ else segments.push({ asset, from: clip.in, to: clip.out });+ end += clip.out - clip.in;+ }+ return segments;+}++export function sourceExportPlan(doc: ExportDoc, settings: ExportSettings): SourceSegment[] | null {+ if (!settings.copySource || settings.container !== "mp4" || settings.audioCodec !== "aac") return null;+ const sources = sourceSequence(doc);+ if (!sources || settings.width !== sources[0].asset.width || settings.height !== sources[0].asset.height) return null;+ const from = Math.max(0, settings.range?.start ?? 0);+ const to = settings.range?.end ?? Infinity;+ let start = 0;+ const result: SourceSegment[] = [];+ for (const source of sources) {+ const end = start + source.to - source.from;+ const a = Math.max(from, start), b = Math.min(to, end);+ if (b > a) result.push({ file: source.asset.fileName, from: source.from + a - start, to: b === end ? source.to : source.from + b - start });+ start = end;+ }+ return result.length ? result : null;+}diff --git a/site/src/cut/lib/sourceRemux.ts b/site/src/cut/lib/sourceRemux.tsnew file mode 100644index 00000000..a5166832--- /dev/null+++ b/site/src/cut/lib/sourceRemux.ts@@ -0,0 +1,232 @@+import {+ EncodedAudioPacketSource, EncodedPacketSink, EncodedVideoPacketSource,+ Mp4OutputFormat, Output, StreamTarget, type Input, type EncodedPacket, type InputVideoTrack, type InputAudioTrack, type Rotation,+} from "mediabunny";+import type { SourceSegment } from "@/cut/lib/sourceExportPlan";++// MP4 edits express the playback window while keeping the dependency frames+// around each cut. The mdat stays on disk; only the movie index is rewritten.+type Box = { type: string; bytes: Uint8Array };+function boxes(bytes: Uint8Array, start = 8): Box[] {+ const result: Box[] = [];+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ for (let at = start; at < bytes.length;) {+ const size = view.getUint32(at);+ if (size < 8 || at + size > bytes.length) throw new Error("Invalid MP4 movie index.");+ result.push({ type: String.fromCharCode(...bytes.subarray(at + 4, at + 8)), bytes: bytes.slice(at, at + size) });+ at += size;+ }+ return result;+}+function box(type: string, children: Uint8Array[]): Uint8Array {+ const bytes = new Uint8Array(8 + children.reduce((n, b) => n + b.length, 0));+ new DataView(bytes.buffer).setUint32(0, bytes.length);+ bytes.set(new TextEncoder().encode(type), 4);+ let at = 8;+ for (const child of children) { bytes.set(child, at); at += child.length; }+ return bytes;+}+function timeScale(bytes: Uint8Array): number {+ return new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getUint32(bytes[8] === 1 ? 28 : 20);+}+function setDuration(bytes: Uint8Array, ticks: number, track = false) {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ const offset = bytes[8] === 1 ? (track ? 36 : 32) : (track ? 28 : 24);+ if (bytes[8] === 1) view.setBigUint64(offset, BigInt(Math.round(ticks)));+ else view.setUint32(offset, Math.round(ticks));+}++/** Rebuild the terminal moov; all media offsets remain unchanged. */+export function trimMovieIndex(bytes: Uint8Array, offsets: number[], duration: number): Uint8Array {+ const children = boxes(bytes);+ const header = children.find((b) => b.type === "mvhd");+ if (!header) throw new Error("MP4 has no movie header.");+ const movieScale = timeScale(header.bytes);+ setDuration(header.bytes, duration * movieScale);+ let index = 0;+ return box("moov", children.map((child) => {+ if (child.type !== "trak") return child.bytes;+ const offset = offsets[index++];+ const track = boxes(child.bytes).filter((b) => b.type !== "edts");+ const tkhd = track.find((b) => b.type === "tkhd");+ const mdia = track.find((b) => b.type === "mdia");+ const mdhd = mdia && boxes(mdia.bytes).find((b) => b.type === "mdhd");+ if (!tkhd || !mdhd || offset === undefined) throw new Error("Invalid MP4 trim track.");+ setDuration(tkhd.bytes, duration * movieScale, true);+ // Version 1 stores both the segment duration and media time in 64 bits.+ const edit = new Uint8Array(28);+ const view = new DataView(edit.buffer);+ edit[0] = 1;+ view.setUint32(4, 1);+ view.setBigUint64(8, BigInt(Math.round(duration * movieScale)));+ view.setBigInt64(16, BigInt(Math.round(offset * timeScale(mdhd.bytes))));+ view.setUint16(24, 1);+ return box("trak", [...track.map((b) => b.bytes), box("edts", [box("elst", [edit])])]);+ }));+}++export type SourceWriter = {+ write(data: Uint8Array, position: number): Promise<void>;+ truncate(size: number): Promise<void>;+};++/** A codec-compatible copy needs neither a decoder nor an encoder. */+export async function prepareTrimRemux(input: Input, trim: SourceSegment, codec: "h264" | "hevc", audioInput: Input = input) {+ if (!Number.isFinite(trim.from) || !Number.isFinite(trim.to) || trim.from < 0 || trim.to <= trim.from) {+ throw new Error("Invalid source trim range.");+ }+ const video = await input.getPrimaryVideoTrack();+ const audio = await audioInput.getPrimaryAudioTrack();+ if (!video || await video.getCodec() !== (codec === "h264" ? "avc" : "hevc") ||+ (audio && await audio.getCodec() !== "aac")) return null;+ const videoSink = new EncodedPacketSink(video);+ const firstVideo = await videoSink.getKeyPacket(trim.from, { verifyKeyPackets: true });+ if (!firstVideo) return null;+ const audioSink = audio && new EncodedPacketSink(audio);+ const audioAtStart = audioSink && await audioSink.getPacket(trim.from);+ // AAC overlap needs the preceding packets to reconstruct the first samples.+ const audioPreroll = audioAtStart ? audioAtStart.timestamp - 2 * audioAtStart.duration : 0;+ const firstAudio = audioSink && (audioPreroll > 0+ ? await audioSink.getPacket(audioPreroll)+ : await audioSink.getFirstPacket());+ // Delayed audio needs an empty edit; let the compositor handle that case.+ if (audio && (!firstAudio || firstAudio.timestamp > trim.from)) return null;+ const videoConfig = await video.getDecoderConfig();+ const audioConfig = audio && await audio.getDecoderConfig();+ if (!videoConfig || (audio && !audioConfig)) return null;+ const rotation = await video.getRotation();+ return async (writer: SourceWriter, progress: (ratio: number) => void, stop: () => void) => {+ let movie: { bytes: Uint8Array; position: number } | undefined;+ const output = new Output({+ format: new Mp4OutputFormat({ fastStart: false, onMoov: (bytes, position) => { movie = { bytes, position }; } }),+ target: new StreamTarget(new WritableStream({ write: ({ data, position }) => writer.write(data, position) }), { chunked: true }),+ });+ const videoOut = new EncodedVideoPacketSource(codec === "h264" ? "avc" : "hevc");+ output.addVideoTrack(videoOut, { rotation });+ const audioOut = audio && firstAudio ? new EncodedAudioPacketSource("aac") : null;+ if (audioOut) output.addAudioTrack(audioOut);+ const offsets = [trim.from - firstVideo.timestamp];+ if (firstAudio && audioOut) offsets.push(trim.from - firstAudio.timestamp);+ const videos = videoSink.packets(firstVideo, undefined, { verifyKeyPackets: true });+ const audios = audioSink && firstAudio ? audioSink.packets(firstAudio) : null;+ try {+ stop();+ await output.start();+ let v = await videos.next();+ let a = audios ? await audios.next() : null;+ while (!v.done || (a && !a.done)) {+ stop();+ // The final GOP includes references needed by reordered B-frames.+ if (!v.done && v.value.type === "key" && v.value.timestamp >= trim.to) {+ await videos.return();+ v = { done: true, value: undefined };+ }+ if (a && !a.done && a.value.timestamp >= trim.to) {+ await audios!.return();+ a = null;+ }+ // Interleave reads as well as writes, keeping only one packet per track.+ if (!v.done && (!a || a.done || v.value.timestamp <= a.value.timestamp)) {+ const packet = v.value;+ // Reference frames beyond the playback end retain their bytes with+ // zero presentation duration. Packet-based readers then see the same+ // end as players honoring the edit list.+ await videoOut.add(packet.clone({ timestamp: Math.min(packet.timestamp, trim.to) - firstVideo.timestamp, duration: Math.max(0, Math.min(packet.duration, trim.to - packet.timestamp)) }), { decoderConfig: videoConfig });+ progress(Math.max(0, Math.min(0.99, (packet.timestamp - trim.from) / (trim.to - trim.from))));+ v = await videos.next();+ } else if (a && !a.done && audioOut && audioConfig && firstAudio) {+ await audioOut.add(a.value.clone({ timestamp: a.value.timestamp - firstAudio.timestamp, duration: Math.min(a.value.duration, trim.to - a.value.timestamp) }), { decoderConfig: audioConfig });+ a = await audios!.next();+ }+ }+ videoOut.close();+ audioOut?.close();+ stop();+ await output.finalize();+ if (!movie) throw new Error("Trim export produced no movie index.");+ const edited = trimMovieIndex(movie.bytes, offsets, trim.to - trim.from);+ await writer.write(edited, movie.position);+ await writer.truncate(movie.position + edited.length);+ progress(1);+ } catch (error) {+ await output.cancel().catch(() => {});+ throw error;+ } finally {+ await videos.return();+ await audios?.return();+ }+ };+}++/** Copy compatible picture sequences; joins encode sound independently. */+export async function prepareSourceRemux(inputs: Map<string, Input>, segments: SourceSegment[], codec: "h264" | "hevc", omitAudio = false) {+ if (segments.length === 1) return prepareTrimRemux(inputs.get(segments[0].file)!, segments[0], codec);+ if (!segments.length) return null;+ const tracks: { segment: SourceSegment; video: InputVideoTrack; audio: InputAudioTrack | null; sink: EncodedPacketSink; first: EncodedPacket; config: VideoDecoderConfig; rotation: Rotation; signature: string }[] = [];+ for (const segment of segments) {+ if (!(segment.from >= 0 && segment.to > segment.from && Number.isFinite(segment.to))) throw new Error("Invalid source export range.");+ const input = inputs.get(segment.file)!;+ const video = await input.getPrimaryVideoTrack();+ const audio = await input.getPrimaryAudioTrack();+ if (!video || await video.getCodec() !== (codec === "h264" ? "avc" : "hevc")) return null;+ const sink = new EncodedPacketSink(video);+ const first = await sink.getKeyPacket(segment.from, { verifyKeyPackets: true });+ const config = await video.getDecoderConfig();+ if (!first || !config) return null;+ const rotation = await video.getRotation();+ const bytes = config.description;+ const description = bytes ? Array.from(new Uint8Array(ArrayBuffer.isView(bytes) ? bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) : bytes)) : [];+ const signature = JSON.stringify({ ...config, description, rotation });+ if (tracks.length && (signature !== tracks[0].signature || Math.abs(first.timestamp - segment.from) > 0.000001)) return null;+ if (tracks.length < segments.length - 1) {+ const endKey = await sink.getKeyPacket(segment.to, { verifyKeyPackets: true });+ const duration = await video.computeDuration();+ if (Math.abs((endKey?.timestamp ?? -1) - segment.to) > 0.000001 && Math.abs(duration - segment.to) > 0.0001) return null;+ }+ tracks.push({ segment, video, audio, sink, first, config, rotation, signature });+ }+ // WebCodecs exposes no reliable AAC encoder priming; exact joins use the+ // machine's audio encoder while this path copies the video packets.+ if (!omitAudio && tracks.some((t) => t.audio)) return null;+ const duration = segments.reduce((n, s) => n + s.to - s.from, 0);+ const preroll = segments[0].from - tracks[0].first.timestamp;+ return async (writer: SourceWriter, progress: (ratio: number) => void, stop: () => void) => {+ let movie: { bytes: Uint8Array; position: number } | undefined;+ const output = new Output({+ format: new Mp4OutputFormat({ fastStart: false, onMoov: (bytes, position) => { movie = { bytes, position }; } }),+ target: new StreamTarget(new WritableStream({ write: ({ data, position }) => writer.write(data, position) }), { chunked: true }),+ });+ const videoOut = new EncodedVideoPacketSource(codec === "h264" ? "avc" : "hevc");+ output.addVideoTrack(videoOut, { rotation: tracks[0].rotation });+ async function* videoPackets(): AsyncGenerator<EncodedPacket> {+ let start = 0;+ for (const { segment, sink, first } of tracks) {+ for await (const packet of sink.packets(first, undefined, { verifyKeyPackets: true })) {+ stop();+ if (packet.type === "key" && packet.timestamp >= segment.to) break;+ yield packet.clone({ timestamp: start + preroll + Math.min(packet.timestamp, segment.to) - segment.from,+ duration: Math.max(0, Math.min(packet.duration, segment.to - packet.timestamp)) });+ }+ start += segment.to - segment.from;+ }+ }+ const videos = videoPackets();+ try {+ stop();+ await output.start();+ for await (const packet of videos) {+ stop();+ await videoOut.add(packet, { decoderConfig: tracks[0].config });+ progress(Math.max(0, Math.min(0.99, (packet.timestamp - preroll) / duration)));+ }+ videoOut.close();+ await output.finalize();+ stop();+ if (!movie) throw new Error("Source export produced no movie index.");+ const edited = trimMovieIndex(movie.bytes, [preroll], duration);+ await writer.write(edited, movie.position); await writer.truncate(movie.position + edited.length);+ progress(1);+ } catch (error) { await output.cancel().catch(() => {}); throw error; }+ finally { await videos.return(undefined); }+ };+}diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.tsindex 6e04a9fe..ca330837 100644--- a/site/src/cut/server/ai/catalog.ts+++ b/site/src/cut/server/ai/catalog.ts@@ -564,7 +564,7 @@ Templates (save_template / template_add) ride the same rail and now keep grades,"publish-and-export": `# Publish & exportPublish tab fields (set_publish): caption (TikTok limit 4,000 chars INCLUDING tags/emoji; hook in the first line), tags (3–5 focused tags recommended; stored space-separated, rendered as #tags), soundTitle (TikTok lets you rename the sound once after posting), handle (shown as @handle in platform previews).-Export (open_export): one-click presets — Share (1080p H.264 MP4, plays everywhere), Best (source size, H.264 MP4, high quality), Social 4K (the cut upscaled to 4K in H.264, because TikTok, Reels and YouTube transcode a 4K upload on a higher bitrate rung than a 1080p one, so it comes back sharper), Small (720p, fastest), Master (source size, ProRes 4444 in a MOV with PCM audio, for handing to another editor or archiving the cut) — and an Advanced panel with every axis: file name (the project's until typed over), range (the whole video, or the span from the first selected item's start to the last one's end when something is selected), format (MP4 or MOV), codec (H.264, HEVC at about half the size for newer devices, ProRes 422 HQ, ProRes 4444), resolution (Source, which matches the sharpest clip on the timeline along the project aspect with a 4K cap, preserving smaller sources; the named rungs below it; and the named rungs above it as marked upscales: ${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}), frame rate (Source, the rate the footage plays at, read from the files; or 24, 30, 60), quality (High, Balanced, Small, or a typed bitrate in Mbps), audio (AAC or uncompressed PCM), and a captions file — the subtitle track saved as an SRT to the browser's Downloads folder (the video lands in the project's exports), one per visible language, for platforms that take their own captions. ProRes and PCM take a MOV, and ProRes sets its own rate, so the quality scale and a typed bitrate grey out. A ProRes 4444 master keeps every pixel's own color: the whole composite is built at 4:4:4 for it, so titles, captions and stickers land in the file without the color smearing a 4:2:0 delivery gives them. The other formats subsample, which is what H.264 and HEVC do at the encoder anyway. Every preset runs at the source frame rate. Source resolution also matches source video/audio bitrates unless a custom bitrate or ProRes is chosen; extra soundtrack audio keeps the delivery audio budget. The dialog shows the size the choice will land at. H.264 files carry the High profile and HEVC files the Main profile; both key every two seconds, what the platforms ask for. An engine from an older Donkey app cannot take a range or a typed name, and the export says to update the app. Every export renders at the project aspect ratio, titles and subtitles burned in. Files land in the project's exports/ folder and appear in the Media tab's Exports section, where each can be previewed plain or in TikTok/Instagram/YouTube chrome with the publish metadata rendered in place, revealed in Finder, or deleted.`,+Export (open_export): one-click presets — Share (1080p H.264 MP4, plays everywhere), Best (original file settings, H.264/HEVC MP4), Social 4K (the cut upscaled to 4K in H.264, because TikTok, Reels and YouTube transcode a 4K upload on a higher bitrate rung than a 1080p one, so it comes back sharper), Small (720p, fastest), Master (source size, ProRes 4444 in a MOV with PCM audio, for handing to another editor or archiving the cut) — and an Advanced panel with every axis: file name (the project's until typed over), range (the whole video, or the span from the first selected item's start to the last one's end when something is selected), format (MP4 or MOV), codec (H.264, HEVC at about half the size for newer devices, ProRes 422 HQ, ProRes 4444), resolution (Source, which matches the sharpest clip on the timeline along the project aspect with a 4K cap, preserving smaller sources; the named rungs below it; and the named rungs above it as marked upscales: ${EXPORT_RESOLUTIONS.map((r) => r.label).join(", ")}), frame rate (Source, the rate the footage plays at, read from the files; or 24, 30, 60), quality (High, Balanced, Small, or a typed bitrate in Mbps), audio (AAC or uncompressed PCM), and a captions file — the subtitle track saved as an SRT to the browser's Downloads folder (the video lands in the project's exports), one per visible language, for platforms that take their own captions. ProRes and PCM take a MOV, and ProRes sets its own rate, so the quality scale and a typed bitrate grey out. A ProRes 4444 master keeps every pixel's own color: the whole composite is built at 4:4:4 for it, so titles, captions and stickers land in the file without the color smearing a 4:2:0 delivery gives them. The other formats subsample, which is what H.264 and HEVC do at the encoder anyway. Every preset runs at the source frame rate. Best preserves source resolution, fractional frame rate, supported H.264/HEVC codec, audio sample rate, channels and bitrates. Whole files and trims copy compressed streams; compatible sequences copy video and encode joined audio. Interior video joins need matching codec configurations and keyframe boundaries. Effects, captions, additional tracks and incompatible joins render with the selected source settings. Source resolution also matches source video/audio bitrates unless a custom bitrate or ProRes is chosen; extra soundtrack audio keeps the delivery audio budget. The dialog shows the size the choice will land at. Rendered H.264 files use High profile and HEVC uses Main, with two-second keyframes; packet copies keep source encoding. An engine from an older Donkey app cannot take a range or a typed name, and the export says to update the app. Source copies preserve the media frame. Composited exports use the project aspect, with titles and subtitles burned in. Files land in the project's exports/ folder and appear in the Media tab's Exports section, where each can be previewed plain or in TikTok/Instagram/YouTube chrome with the publish metadata rendered in place, revealed in Finder, or deleted.`,};/** System prompt shared by all providers. */diff --git a/site/src/cut/server/exportPipeline.test.ts b/site/src/cut/server/exportPipeline.test.tsindex f7b5a800..e7f6677f 100644--- a/site/src/cut/server/exportPipeline.test.ts+++ b/site/src/cut/server/exportPipeline.test.ts@@ -19,6 +19,7 @@ const runsFor = async (over: Partial<ExportSpec>): Promise<string[][]> => {// chunk runs that wrote its pieces, so the bake reads back a whole file.const produced = new Map<string, number>();const io: ExportPipelineIO = {+ exportSourceFiles: async () => false,stat: (async () => ({ isFile: () => true })) as unknown as ExportPipelineIO["stat"],writeFile: (async () => {}) as unknown as ExportPipelineIO["writeFile"],readFile: (async () => new Uint8Array(0)) as unknown as ExportPipelineIO["readFile"],diff --git a/site/src/cut/server/exportPipeline.ts b/site/src/cut/server/exportPipeline.tsindex c463bed1..9f4b2809 100644--- a/site/src/cut/server/exportPipeline.ts+++ b/site/src/cut/server/exportPipeline.ts@@ -1,4 +1,6 @@import { spawn, type ChildProcess } from "node:child_process";+import { exportSourceFiles } from "./sourceExport";+import type { SourceSegment } from "../lib/sourceExportPlan";import { deliveryCodec, deliveryContainer, deliverySpan, KEYFRAME_INTERVAL_S, videoBitrateFor, type ExportCodec, type ExportRange } from "../lib/exportDelivery";import { readFile, stat, unlink, writeFile } from "node:fs/promises";import path from "node:path";@@ -52,6 +54,7 @@ const soundChain = (sound: ClipSound | undefined): string => {};export interface ExportSpec {+ sourceSegments?: SourceSegment[];projectId: string;/** Where the render lands instead of a stamped file in exports/: "hls" is the* share's streaming ladder, "preview"@@ -68,6 +71,8 @@ export interface ExportSpec {container?: "mp4" | "mov";audioCodec?: "aac" | "pcm";audioBitrate?: number;+ audioSampleRate?: number;+ audioChannels?: number;/** A bitrate the user typed, bits per second; absent = the `crf` tier. */bitrate?: number;/** The file's name without its extension, as typed; absent = the project's@@ -446,7 +451,9 @@ export function videoCodecArgs(enc: string, spec: ExportSpec): string[] {/** The audio arguments for a spec's delivery. */export function audioCodecArgs(spec: ExportSpec): string[] {- return spec.audioCodec === "pcm" ? ["-c:a", "pcm_s16le"] : ["-c:a", "aac", "-b:a", String(spec.audioBitrate ?? 192_000)];+ return [...(spec.audioCodec === "pcm" ? ["-c:a", "pcm_s16le"] : ["-c:a", "aac", "-b:a", String(spec.audioBitrate ?? 192_000)]),+ ...(spec.audioSampleRate ? ["-ar", String(spec.audioSampleRate)] : []),+ ...(spec.audioChannels ? ["-ac", String(spec.audioChannels)] : [])];}/** The file extension a spec's container takes. */@@ -678,6 +685,7 @@ export function runFfmpeg(* takes them as a parameter so the filtergraph tests can build the real graph* for a spec with these stubbed. */export interface ExportPipelineIO {+ exportSourceFiles: typeof exportSourceFiles;stat: typeof stat;writeFile: typeof writeFile;readFile: typeof readFile;@@ -692,6 +700,7 @@ export interface ExportPipelineIO {}const realIO: ExportPipelineIO = {+ exportSourceFiles,stat,writeFile,readFile,@@ -716,6 +725,19 @@ export async function runExport(io: ExportPipelineIO = realIO) {if (given.clips.length === 0) throw new Error("Nothing to export.");+ const codec = given.codec ?? "h264";+ if (given.target === "export" && given.sourceSegments?.length && (codec === "h264" || codec === "hevc")) {+ for (const segment of given.sourceSegments) {+ if (!given.clips.some((clip) => segment.file === clip.file && segment.from >= clip.in && segment.to <= clip.out)) {+ // Adjacent splits of a source may be merged into one copy span.+ const clips = given.clips.filter((clip) => clip.file === segment.file).sort((a, b) => a.in - b.in);+ let covered = segment.from;+ for (const clip of clips) if (clip.in <= covered && clip.out > covered) covered = clip.out;+ if (covered < segment.to) throw new Error("Source export does not match the timeline media.");+ }+ }+ if (await io.exportSourceFiles(job, mediaPathFor, given.sourceSegments, codec, given.audioBitrate)) return;+ }let spec = narrowSpecToRange(given);const { width: W, height: H, fps } = spec;diff --git a/site/src/cut/server/sourceExport.test.ts b/site/src/cut/server/sourceExport.test.tsnew file mode 100644index 00000000..cf683e9b--- /dev/null+++ b/site/src/cut/server/sourceExport.test.ts@@ -0,0 +1,156 @@+import { afterAll, beforeAll, expect, test } from "bun:test";+import { mkdtemp, readFile, rm, stat } from "node:fs/promises";+import { tmpdir } from "node:os";+import path from "node:path";+import { execFileSync, spawnSync } from "node:child_process";+import { exportSourceFiles } from "./sourceExport";+import { runExport, type RenderHandle } from "./exportPipeline";+import { ALL_FORMATS, BufferSource, Input } from "mediabunny";++const available = spawnSync("ffmpeg", ["-version"]).status === 0 && spawnSync("ffprobe", ["-version"]).status === 0;+let dir = "";+let source = "";+beforeAll(async () => {+ if (!available) return;+ dir = await mkdtemp(path.join(tmpdir(), "donkey-trim-test-"));+ source = path.join(dir, "source.mp4");+ execFileSync("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=320x240:rate=30", "-f", "lavfi", "-i", "sine=frequency=440:sample_rate=48000", "-t", "12", "-c:v", "libx264", "-g", "60", "-bf", "2", "-b:v", "140k", "-c:a", "aac", "-b:a", "48k", source]);+});+afterAll(async () => { if (dir) await rm(dir, { recursive: true, force: true }); });+const handle = (name: string): RenderHandle => ({ tmpDir: dir, outPath: path.join(dir, name), progress: 0, log: [] });+const hashes = (file: string) => JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_packets", "-show_data_hash", "sha256", "-show_entries", "packet=codec_type,data_hash", "-of", "json", file], { encoding: "utf8" })).packets as { codec_type: string; data_hash: string }[];++test.skipIf(!available)("non-keyframe trims preserve compressed packets, duration, dimensions and sync", async () => {+ const job = handle("trim.mp4");+ await runExport(job, {+ projectId: "trim-test", target: "export", width: 320, height: 240, fps: 30, crf: 19, preset: "medium", duration: 5.284,+ sourceSegments: [{ file: "source.mp4", from: 3.137, to: 8.421 }],+ clips: [{ file: "source.mp4", in: 3.137, out: 8.421, muted: false }], audio: [], overlays: [],+ }, () => source);+ expect(job.proc).toBeUndefined();+ expect(job.progress).toBe(1);+ const probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_streams", "-show_format", "-of", "json", job.outPath], { encoding: "utf8" }));+ expect(probe.streams[0]).toMatchObject({ width: 320, height: 240, codec_name: "h264" });+ expect(Number(probe.format.duration)).toBeCloseTo(5.284, 3);+ for (const stream of probe.streams) {+ expect(Number(stream.start_time)).toBeCloseTo(0, 2);+ expect(Number(stream.duration)).toBeCloseTo(5.284, 3);+ }+ const original = new Set(hashes(source).map((p) => p.data_hash));+ const copied = hashes(job.outPath);+ expect(copied.length).toBeGreaterThan(100);+ for (const packet of copied) expect(original.has(packet.data_hash)).toBe(true);+ expect((await stat(job.outPath)).size).toBeLessThan((await stat(source)).size);+ expect(execFileSync("ffmpeg", ["-v", "error", "-i", job.outPath, "-f", "null", "-"], { encoding: "utf8" })).toBe("");+ const input = new Input({ formats: ALL_FORMATS, source: new BufferSource(await readFile(job.outPath)) });+ try { expect(await input.computeDuration()).toBeCloseTo(5.284, 3); }+ finally { input.dispose(); }+ const frameHashes = (file: string, filter: string[]) => execFileSync("ffmpeg", ["-v", "error", "-i", file, ...filter, "-an", "-f", "framemd5", "-"], { encoding: "utf8" })+ .split("\n").filter((line) => line && !line.startsWith("#")).map((line) => line.split(",").at(-1)?.trim());+ expect(frameHashes(job.outPath, [])).toEqual(frameHashes(source, ["-vf", "trim=start=3.137:end=8.421"]));+ const pcm = (file: string, filter: string[]) => execFileSync("ffmpeg", ["-v", "error", "-i", file, ...filter, "-vn", "-f", "f32le", "-"], { maxBuffer: 4 * 1024 * 1024 });+ const expectedAudio = pcm(source, ["-af", "atrim=start=3.137:end=8.421"]);+ const actualAudio = pcm(job.outPath, []);+ expect(actualAudio.length).toBeGreaterThanOrEqual(expectedAudio.length);+ let maxError = 0;+ for (let i = 0; i < expectedAudio.length; i += 4) {+ maxError = Math.max(maxError, Math.abs(expectedAudio.readFloatLE(i) - actualAudio.readFloatLE(i)));+ }+ expect(maxError).toBeLessThan(0.0001);+});++test.skipIf(!available)("video-only trims preserve rotation metadata", async () => {+ const rotated = path.join(dir, "rotated.mp4");+ execFileSync("ffmpeg", ["-v", "error", "-display_rotation", "90", "-i", source, "-map", "0:v", "-c", "copy", rotated]);+ const job = handle("rotated-trim.mp4");+ expect(await exportSourceFiles(job, () => rotated, [{ file: "rotated.mp4", from: 0, to: 4.017 }], "h264")).toBe(true);+ const input = new Input({ formats: ALL_FORMATS, source: new BufferSource(await readFile(job.outPath)) });+ try {+ expect(await input.getPrimaryAudioTrack()).toBeNull();+ const video = (await input.getPrimaryVideoTrack())!;+ expect(await video.getDisplayWidth()).toBe(240);+ expect(await video.getDisplayHeight()).toBe(320);+ expect(await input.computeDuration()).toBeCloseTo(4.017, 3);+ } finally { input.dispose(); }+});++test.skipIf(!available)("codec changes decline packet copy before creating an output", async () => {+ const job = handle("hevc.mp4");+ expect(await exportSourceFiles(job, () => source, [{ file: "source.mp4", from: 1, to: 8 }], "hevc")).toBe(false);+ expect(stat(job.outPath)).rejects.toThrow();+});++test.skipIf(!available)("cancellation stops copying", async () => {+ const job = { ...handle("canceled.mp4"), error: "Export canceled." };+ expect(exportSourceFiles(job, () => source, [{ file: "source.mp4", from: 1, to: 8 }], "h264")).rejects.toThrow("canceled");+});++test.skipIf(!available)("whole sources export without changing encoded media", async () => {+ const job = handle("whole.mp4");+ expect(await exportSourceFiles(job, () => source, [{ file: "source.mp4", from: 0, to: 12 }], "h264")).toBe(true);+ const original = new Set(hashes(source).map((p) => p.data_hash));+ for (const packet of hashes(job.outPath)) expect(original.has(packet.data_hash)).toBe(true);+ const probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_format", "-of", "json", job.outPath], { encoding: "utf8" }));+ expect(Number(probe.format.duration)).toBeCloseTo(12, 3);+});++test.skipIf(!available)("reordered source sequences copy video and join audio at exact sample boundaries", async () => {+ const job = handle("sequence.mp4");+ const segments = [{ file: "source.mp4", from: 4.137, to: 8 }, { file: "source.mp4", from: 0, to: 2.421 }];+ expect(await exportSourceFiles(job, () => source, segments, "h264", 48_000)).toBe(true);+ const original = new Set(hashes(source).filter((p) => p.codec_type === "video").map((p) => p.data_hash));+ for (const packet of hashes(job.outPath).filter((p) => p.codec_type === "video")) expect(original.has(packet.data_hash)).toBe(true);+ const probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_streams", "-show_format", "-of", "json", job.outPath], { encoding: "utf8" }));+ expect(Number(probe.format.duration)).toBeCloseTo(6.284, 3);+ expect(probe.streams.find((s: { codec_type: string }) => s.codec_type === "audio")).toMatchObject({ sample_rate: "48000", channels: 1 });+ const frameHashes = (file: string, filter: string[]) => execFileSync("ffmpeg", ["-v", "error", "-i", file, ...filter, "-an", "-fps_mode", "passthrough", "-f", "framemd5", "-"], { encoding: "utf8" })+ .split("\n").filter((line) => line && !line.startsWith("#")).map((line) => line.split(",").at(-1)?.trim());+ expect(frameHashes(job.outPath, [])).toEqual(segments.flatMap((s) => frameHashes(source, ["-vf", `trim=start=${s.from}:end=${s.to}`])));+ const input = new Input({ formats: ALL_FORMATS, source: new BufferSource(await readFile(job.outPath)) });+ try { expect(await input.computeDuration()).toBeCloseTo(6.284, 3); } finally { input.dispose(); }+ const pcm = (file: string, filter: string[]) => execFileSync("ffmpeg", ["-v", "error", "-i", file, ...filter, "-vn", "-f", "f32le", "-"], { maxBuffer: 4 * 1024 * 1024 });+ const expected = Buffer.concat(segments.map((s) => pcm(source, ["-af", `atrim=start=${s.from}:end=${s.to}`])));+ const actual = pcm(job.outPath, []);+ expect(actual.length).toBeGreaterThanOrEqual(expected.length);+ let error = 0, energy = 0;+ for (let i = 0; i < expected.length; i += 4) {+ error += (expected.readFloatLE(i) - actual.readFloatLE(i)) ** 2;+ energy += expected.readFloatLE(i) ** 2;+ }+ expect(error / energy).toBeLessThan(0.05);+});++test.skipIf(!available)("incompatible interior cuts use the compositor", async () => {+ const job = handle("needs-render.mp4");+ expect(await exportSourceFiles(job, () => source, [{ file: "source.mp4", from: 0, to: 3.137 }, { file: "source.mp4", from: 4.421, to: 8 }], "h264")).toBe(false);+ expect(stat(job.outPath)).rejects.toThrow();+});++test.skipIf(!available)("metadata probing preserves fractional cadence without requiring a decoder", async () => {+ const { sourceExportProfile } = await import("../lib/exportRender");+ const { registerBlobFile, forgetRegistered } = await import("../lib/backend/browser/registry");+ const fractional = path.join(dir, "fractional.mp4");+ execFileSync("ffmpeg", ["-v", "error", "-i", source, "-t", "4", "-r", "30000/1001", "-c:v", "libx264", "-c:a", "aac", "-ar", "44100", "-ac", "1", fractional]);+ const file = new File([await readFile(fractional)], "fractional.mp4");+ const url = registerBlobFile("test-source-profile", file);+ try {+ const profile = await sourceExportProfile({+ assets: [{ id: "a", name: "source", fileName: "fractional.mp4", type: "video", duration: 4, url, sizeBytes: file.size }],+ clips: [{ id: "c", assetId: "a", track: 0, start: 0, in: 0, out: 4, muted: false }],+ }, () => url);+ expect(profile.fps).toBeCloseTo(30000 / 1001, 6);+ expect(profile).toMatchObject({ codec: "h264", audioSampleRate: 44100, audioChannels: 1 });+ } finally { forgetRegistered("test-source-profile"); }+});++test.skipIf(!available)("HEVC sources keep their encoded video", async () => {+ const hevc = path.join(dir, "hevc-source.mp4");+ execFileSync("ffmpeg", ["-v", "error", "-i", source, "-t", "2", "-an", "-c:v", "libx265", "-x265-params", "log-level=error", "-tag:v", "hvc1", hevc]);+ const job = handle("hevc-copy.mp4");+ expect(await exportSourceFiles(job, () => hevc, [{ file: "hevc-source.mp4", from: 0.137, to: 1.721 }], "hevc")).toBe(true);+ const original = new Set(hashes(hevc).map((packet) => packet.data_hash));+ for (const packet of hashes(job.outPath)) expect(original.has(packet.data_hash)).toBe(true);+ const probe = JSON.parse(execFileSync("ffprobe", ["-v", "error", "-show_streams", "-show_format", "-of", "json", job.outPath], { encoding: "utf8" }));+ expect(probe.streams[0].codec_name).toBe("hevc");+ expect(Number(probe.format.duration)).toBeCloseTo(1.584, 3);+});diff --git a/site/src/cut/server/sourceExport.ts b/site/src/cut/server/sourceExport.tsnew file mode 100644index 00000000..97a71655--- /dev/null+++ b/site/src/cut/server/sourceExport.ts@@ -0,0 +1,89 @@+import { open, unlink } from "node:fs/promises";+import path from "node:path";+import { ALL_FORMATS, CustomSource, Input } from "mediabunny";+import { prepareSourceRemux, prepareTrimRemux } from "../lib/sourceRemux";+import type { SourceSegment } from "../lib/sourceExportPlan";+import { runFfmpeg, type RenderHandle } from "./exportPipeline";++/** The Mac and worker share the packet copier with browser exports. */+export async function exportSourceFiles(job: RenderHandle, resolve: (file: string) => string, segments: SourceSegment[], codec: "h264" | "hevc", audioBitrate?: number) {+ const inputs = new Map<string, Input>();+ const sources: Awaited<ReturnType<typeof open>>[] = [];+ const readers: Input[] = [];+ const scratch: string[] = [];+ const stop = () => { if (job.error) throw new Error(job.error); };+ const read = async (file: string) => {+ const source = await open(file, "r");+ sources.push(source);+ const input = new Input({ formats: ALL_FORMATS, source: new CustomSource({+ getSize: async () => (await source.stat()).size,+ read: async (start, end) => {+ const buffer = new Uint8Array(end - start);+ let filled = 0;+ while (filled < buffer.length) {+ stop();+ const { bytesRead } = await source.read(buffer, filled, buffer.length - filled, start + filled);+ if (!bytesRead) throw new Error("Source file ended during export.");+ filled += bytesRead;+ }+ return buffer;+ },+ maxCacheSize: 0,+ }) });+ readers.push(input);+ return input;+ };+ const write = async (copy: NonNullable<Awaited<ReturnType<typeof prepareSourceRemux>>>, file: string, progress: (ratio: number) => void) => {+ const target = await open(file, "w");+ try {+ await copy({+ write: async (data, position) => {+ let written = 0;+ while (written < data.length) {+ const { bytesWritten } = await target.write(data, written, data.length - written, position + written);+ if (!bytesWritten) throw new Error("Could not write source export.");+ written += bytesWritten;+ }+ },+ truncate: (size) => target.truncate(size),+ }, progress, stop);+ } finally { await target.close(); }+ };+ try {+ for (const segment of segments) if (!inputs.has(segment.file)) inputs.set(segment.file, await read(resolve(segment.file)));+ const audioTracks = await Promise.all(segments.map((s) => inputs.get(s.file)!.getPrimaryAudioTrack()));+ const reference = audioTracks.find(Boolean);+ const joinedAudio = segments.length > 1 && !!reference;+ const copy = await prepareSourceRemux(inputs, segments, codec, joinedAudio);+ if (!copy) return false;+ if (!joinedAudio) {+ await write(copy, job.outPath, (ratio) => { job.progress = ratio; });+ return true;+ }+ const videoPath = path.join(job.tmpDir, `source-video-${crypto.randomUUID()}.mp4`);+ const audioPath = path.join(job.tmpDir, `source-audio-${crypto.randomUUID()}.m4a`);+ scratch.push(videoPath, audioPath);+ await write(copy, videoPath, (ratio) => { job.progress = ratio * 0.3; });+ stop();+ const sampleRate = await reference!.getSampleRate();+ const channels = Math.max(...await Promise.all(audioTracks.map((track) => track?.getNumberOfChannels() ?? 0)));+ const filters = segments.map((s, index) => audioTracks[index]+ ? `[${index}:a:0]atrim=start=${s.from}:end=${s.to},asetpts=PTS-${s.from}/TB,aresample=${sampleRate}:async=1:first_pts=0,aformat=channel_layouts=${channels}c,apad,atrim=duration=${s.to - s.from}[a${index}]`+ : `anullsrc=r=${sampleRate}:cl=${channels}c,atrim=duration=${s.to - s.from}[a${index}]`);+ filters.push(`${segments.map((_, i) => `[a${i}]`).join("")}concat=n=${segments.length}:v=0:a=1[audio]`);+ const duration = segments.reduce((n, s) => n + s.to - s.from, 0);+ await runFfmpeg(job, ["-y", ...segments.flatMap((s) => ["-i", resolve(s.file)]),+ "-filter_complex", filters.join(";"), "-map", "[audio]", "-c:a", "aac",+ "-b:a", String(audioBitrate ?? 192_000), "-ar", String(sampleRate), "-ac", String(channels), "-t", String(duration), audioPath],+ (seconds) => { job.progress = 0.3 + Math.min(0.5, seconds / duration * 0.5); });+ stop();+ const joined = await prepareTrimRemux(await read(videoPath), { file: videoPath, from: 0, to: duration }, codec, await read(audioPath));+ if (!joined) throw new Error("Could not mux the source export audio.");+ await write(joined, job.outPath, (ratio) => { job.progress = 0.8 + ratio * 0.2; });+ return true;+ } finally {+ for (const input of readers) input.dispose();+ await Promise.all(sources.map((source) => source.close()));+ await Promise.all(scratch.map((file) => unlink(file).catch(() => {})));+ }+}