Repository navigation
Expand file tree
/
Copy pathCliExportRunner.tsx
More file actions
287 lines (267 loc) · 11.3 KB
/
Copy pathCliExportRunner.tsx
File metadata and controls
287 lines (267 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Hidden-window runner for `openscreen export`. Loads an .openscreen project,
// migrates it to the AxcutDocument the native Rust compositor consumes, and
// drives exportMultiNative/exportGifNative — mirroring the v4 ExportDialog so
// CLI exports and GUI exports stay pixel-identical. The hidden window does no
// compositing itself: the render runs in the main process; this runner only
// builds the clip list + scene JSON and relays progress.
import { useEffect, useRef, useState } from "react";
import { toFileUrl } from "@/components/video-editor/projectPersistence";
import { prepareClickSound } from "@/lib/ai-edition/clickSound";
import {
collectEffectiveClipDims,
pickExtremeDims,
resolveAspectRatioValue,
} from "@/lib/ai-edition/document/outputFormat";
import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import {
appendAutoZoomSuggestions,
collectAutoZoomSuggestionsForDocument,
} from "@/lib/ai-edition/timeline/apply-auto-zooms";
import {
audioRenderPath,
type CliDoneResult,
type CliExportRequest,
defaultExportPath,
isAudioExportFormat,
} from "@/lib/cliContracts";
import { GIF_SIZE_PRESETS, type GifSizePreset } from "@/lib/exporter";
import { extractAudio, isolateAudioTrack } from "@/lib/exporter/audioExport";
import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";
import { outputFrameCount } from "@/lib/exporter/outputFrameCount";
import { mixVoiceoverIntoVideo } from "@/lib/exporter/voiceoverMix";
import { exportGifNative, exportMultiNative, nativeBridgeClient } from "@/native";
import { buildNativeClipList, buildSceneDescription } from "@/native/sceneDescription";
import { type ExportProject, loadDocumentProject } from "./exportProject";
import { loadCliProject, probeVideoDimensions } from "./loadCliProject";
/** Mirrors ExportDialog.gifOutputDims: from the "Source" size, cap height at the preset, keep even. */
function gifOutputDims(
preset: GifSizePreset,
sourceDims: { width: number; height: number } | null,
): { width?: number; height?: number } {
if (!sourceDims) return {};
const maxHeight = GIF_SIZE_PRESETS[preset].maxHeight;
if (!Number.isFinite(maxHeight) || sourceDims.height <= maxHeight) {
return { width: sourceDims.width, height: sourceDims.height };
}
const scale = maxHeight / sourceDims.height;
const even = (n: number) => Math.max(2, Math.round(n * scale) & ~1);
return { width: even(sourceDims.width), height: even(sourceDims.height) };
}
/** The project to export: by id when the MCP server names one, else the file at its path. */
async function loadExportProject(request: CliExportRequest): Promise<ExportProject> {
if (request.projectId) {
const stored = await nativeBridgeClient.aiEdition.get(request.projectId);
if (!stored.success || !stored.document) {
throw new Error(stored.error ?? `No project has the id "${request.projectId}"`);
}
return loadDocumentProject(stored.document, (videoPath) =>
probeVideoDimensions(toFileUrl(videoPath)),
);
}
return loadCliProject(request.projectPath);
}
async function runExport(request: CliExportRequest): Promise<CliDoneResult> {
const project = await loadExportProject(request);
const { editor } = project;
let axcutDocument = project.document;
const format = request.format ?? editor.exportFormat;
const audioFormat = isAudioExportFormat(format) ? format : null;
if (request.audioPath && format !== "mp4") {
throw new Error(
`--audio is only supported for MP4 exports (this export's format is ${format}; pass --format mp4)`,
);
}
if (request.audioTrackId && !audioFormat) {
throw new Error("--track is only supported for audio exports (.wav or .m4a)");
}
if (request.quality && format === "gif") {
throw new Error(
"--quality is only supported for MP4 exports (this project's stored format is gif; a GIF is sized with --gif-size)",
);
}
const quality = request.quality ?? editor.exportQuality;
const gifFrameRate = request.gifFrameRate ?? editor.gifFrameRate;
const gifSizePreset = request.gifSizePreset ?? editor.gifSizePreset;
const gifLoop = request.gifLoop ?? editor.gifLoop;
const mp4FrameRate = request.mp4FrameRate;
const outPath = request.outPath ?? defaultExportPath(request.projectPath, format);
// Use the same per-clip auto-zoom suggestions as the editor, including its default span and
// anchoring behavior.
if (request.autoZoom) {
const suggestions = await collectAutoZoomSuggestionsForDocument(axcutDocument, (videoPath) =>
nativeBridgeClient.cursor.getTelemetry(videoPath).catch(() => []),
);
axcutDocument = appendAutoZoomSuggestions(axcutDocument, suggestions);
window.electronAPI.cliLog(
"info",
`Auto-zoom: added ${suggestions.length} region(s) from cursor telemetry`,
);
}
// Output sizing mirrors the ExportDialog: crop-aware smallest clip on the
// timeline, normalized to the document's aspect ratio.
const smallestSource =
pickExtremeDims(collectEffectiveClipDims(axcutDocument), "smallest") ?? project.sourceDims;
const aspectRatioValue = resolveAspectRatioValue(
axcutDocument,
getEditorSettings(axcutDocument).aspectRatio,
);
const dimsFor = (tier: typeof quality) =>
calculateMp4ExportSettings({
quality: tier,
sourceWidth: smallestSource.width,
sourceHeight: smallestSource.height,
aspectRatioValue,
frameRate: mp4FrameRate,
});
const outDims = dimsFor(quality);
// One track alone: the export of a project whose only sound is that track.
const soloTrack = Boolean(request.audioTrackId);
if (request.audioTrackId) axcutDocument = isolateAudioTrack(axcutDocument, request.audioTrackId);
const builtClips = buildNativeClipList(axcutDocument);
if (builtClips.length === 0) {
throw new Error("The project's timeline has no visible clips to export");
}
// The scene carries the click hits, whose cues and staged samples are read out of caches a
// scene build cannot await — without this a cold CLI export builds its scene from empty
// caches and comes out silent. Clicks that will not load must not cost the export.
if (!soloTrack) await prepareClickSound(axcutDocument).catch(() => undefined);
const built = buildSceneDescription(axcutDocument);
// A track alone is heard without the take's sound and the clicks.
const sceneDesc = soloTrack ? { ...built, clickSound: undefined } : built;
if (soloTrack && sceneDesc.audioTracks.length === 0) {
throw new Error(`The audio track "${request.audioTrackId}" plays nowhere in the export`);
}
// The webcam background effect is applied by the compositor from the scene, so the clip
// list needs no pre-rendering pass.
const clips = soloTrack ? builtClips.map((clip) => ({ ...clip, hasAudio: false })) : builtClips;
const sceneJson = JSON.stringify(sceneDesc);
// Progress: native pushes raw encoded-frame counts; totals and pacing are
// computed here, mirroring the ExportDialog.
const outFps = format === "gif" ? gifFrameRate : mp4FrameRate;
// Speed-adjusted, not source seconds — see `outputFrameCount`. Counting raw duration
// is what made a 1.25x timeline stop the bar at 80% (OpenScreen#371).
const totalFrames = outputFrameCount(clips, sceneDesc.speedRegions, outFps);
const exportStartedAt = Date.now();
const unsubscribeProgress = window.electronAPI.onNativeExportProgress?.((frames: number) => {
const elapsedSec = (Date.now() - exportStartedAt) / 1000;
const rate = frames > 0 ? frames / Math.max(elapsedSec, 0.001) : 0;
window.electronAPI.cliProgress({
percentage: Math.min(100, (frames / totalFrames) * 100),
currentFrame: frames,
totalFrames,
estimatedTimeRemaining: rate > 0 ? Math.max(0, (totalFrames - frames) / rate) : 0,
});
});
try {
if (format === "gif") {
// From the "Source" size as the dialog does, never the MP4 quality tier.
const dims = gifOutputDims(gifSizePreset, dimsFor("source"));
await exportGifNative(clips, outPath, sceneJson, {
...dims,
fps: gifFrameRate,
loopCount: gifLoop ? 0 : 1,
});
return {
success: true,
outputPath: outPath,
format,
width: dims.width,
height: dims.height,
};
}
if (audioFormat) {
// The audio of the MP4 this project exports to, rendered at the smallest size: the
// picture is thrown away, the frame rate stays the one the audio is laid out on.
const renderPath = audioRenderPath(outPath);
const dims = dimsFor("medium");
await exportMultiNative(clips, renderPath, sceneJson, {
width: dims.width,
height: dims.height,
fps: mp4FrameRate,
codec: "h264",
bitrate: dims.bitrate,
});
window.electronAPI.cliProgress({ percentage: 100, phase: "extracting-audio" });
const rendered = await fetch(toFileUrl(renderPath));
if (!rendered.ok) throw new Error(`Failed to read the rendered video back: ${renderPath}`);
const audio = await extractAudio(await rendered.blob(), audioFormat);
const saveResult = await window.electronAPI.writeExportToPath(audio, outPath);
if (!saveResult.success) {
throw new Error(saveResult.message ?? `Failed to write the audio to ${outPath}`);
}
return { success: true, outputPath: outPath, format };
}
// MP4: native writes outPath directly. When a voiceover is requested, mix
// it afterwards (the native pipeline has no extra-audio-track concept) and
// overwrite the same file.
await exportMultiNative(clips, outPath, sceneJson, {
width: outDims.width,
height: outDims.height,
fps: mp4FrameRate,
codec: "h264",
bitrate: outDims.bitrate,
});
if (request.audioPath) {
window.electronAPI.cliProgress({ percentage: 100, phase: "mixing-voiceover" });
const [videoResponse, audioResponse] = await Promise.all([
fetch(toFileUrl(outPath)),
fetch(toFileUrl(request.audioPath)),
]);
if (!videoResponse.ok) {
throw new Error(`Failed to read the exported video back for mixing: ${outPath}`);
}
if (!audioResponse.ok) {
throw new Error(`Failed to read voiceover file: ${request.audioPath}`);
}
const mixed = await mixVoiceoverIntoVideo(await videoResponse.blob(), {
voiceoverData: await audioResponse.arrayBuffer(),
mode: request.audioMode,
offsetSec: request.audioOffsetSec,
});
const saveResult = await window.electronAPI.writeExportToPath(
await mixed.arrayBuffer(),
outPath,
);
if (!saveResult.success) {
throw new Error(saveResult.message ?? `Failed to write mixed output to ${outPath}`);
}
}
return {
success: true,
outputPath: outPath,
format,
width: outDims.width,
height: outDims.height,
};
} finally {
unsubscribeProgress?.();
}
}
export function CliExportRunner() {
const startedRef = useRef(false);
const [status, setStatus] = useState("Starting export…");
useEffect(() => {
if (startedRef.current) return;
startedRef.current = true;
void (async () => {
try {
const request = (await window.electronAPI.cliGetRequest()) as CliExportRequest;
if (request.kind !== "export") {
throw new Error(`cli-export window received a ${request.kind} request`);
}
setStatus(`Exporting ${request.projectPath}…`);
const result = await runExport(request);
await window.electronAPI.cliDone(result);
} catch (error) {
const message = error instanceof Error ? (error.stack ?? error.message) : String(error);
await window.electronAPI.cliDone({ success: false, error: message });
}
})();
}, []);
return (
<div className="flex h-screen items-center justify-center bg-[#09090b] text-white/60 text-sm">
{status}
</div>
);
}
export default CliExportRunner;