|
| 1 | +/* This Source Code Form is subject to the terms of the Mozilla Public |
| 2 | + * License, v. 2.0. If a copy of the MPL was not distributed with this |
| 3 | + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
| 4 | + |
| 5 | +import { canEncodeVideo } from "mediabunny"; |
| 6 | +import { computeOutputSize } from "@diffusionstudio/encoder"; |
| 7 | +import { Computed, FrameRate, getParentNode, isScene, Source, Workarea } from "@diffusionstudio/runtime"; |
| 8 | + |
| 9 | +import { renderOverlay, renderScene } from "@/context/render"; |
| 10 | +import { ElectronWritableFileHandle } from "@/lib/electron-file-writable"; |
| 11 | +import { ProjectConfig as ProjectConfigTrait } from "@/engine/traits"; |
| 12 | +import { sceneConfigKey } from "@/engine/project-config"; |
| 13 | +import { |
| 14 | + getDefaultExportTemplate, |
| 15 | + VIDEO_FORMAT_OPTIONS, |
| 16 | +} from "@/components/sidebar-right/inspector/export-templates"; |
| 17 | +import { mainBridge } from "@/lib/ipc"; |
| 18 | +import { MAIN_CHANNELS } from "@desktop/main-channels"; |
| 19 | +import { resolveNode } from "./nodes"; |
| 20 | + |
| 21 | +import type { ExportRequest, ExportResult, ExportSettings } from "@diffusionstudio/cli/channels"; |
| 22 | +import type { ContainerFormat, ExportConfig } from "@/engine/project-config"; |
| 23 | +import type { EditorSession } from "./session"; |
| 24 | + |
| 25 | +/** |
| 26 | + * The container the export writes: the output extension when a path was |
| 27 | + * given (ffmpeg's rule — the file must be what its name says), the config's |
| 28 | + * format otherwise, mp4 when neither says. A given path settles it entirely, |
| 29 | + * so a bad config format only fails an export that would actually use it. |
| 30 | + */ |
| 31 | +function resolveFormat(path: string | undefined, config: ExportConfig): ContainerFormat { |
| 32 | + const supported = VIDEO_FORMAT_OPTIONS.map((format) => `.${format}`).join(", "); |
| 33 | + if (path !== undefined) { |
| 34 | + const extension = /\.([a-z0-9]+)$/i.exec(path)?.[1]?.toLowerCase(); |
| 35 | + if (!extension || !VIDEO_FORMAT_OPTIONS.includes(extension as ContainerFormat)) { |
| 36 | + throw new Error(`The output path must end in a container extension: ${supported}.`); |
| 37 | + } |
| 38 | + return extension as ContainerFormat; |
| 39 | + } |
| 40 | + const format = config.format ?? "mp4"; |
| 41 | + if (!VIDEO_FORMAT_OPTIONS.includes(format)) { |
| 42 | + throw new Error(`The export entry names an unknown format "${format}" — use one of ${supported.replaceAll(".", "")}.`); |
| 43 | + } |
| 44 | + return format; |
| 45 | +} |
| 46 | + |
| 47 | +export function handleExport(session: () => EditorSession) { |
| 48 | + return async ({ id, path }: ExportRequest): Promise<ExportResult> => { |
| 49 | + const { world, project, engine } = session(); |
| 50 | + |
| 51 | + const scene = resolveNode(world, id); |
| 52 | + if (!isScene(scene)) { |
| 53 | + let parent = getParentNode(scene); |
| 54 | + while (parent !== null && !isScene(parent)) parent = getParentNode(parent); |
| 55 | + const stamp = parent?.get(Source)?.value; |
| 56 | + throw new Error( |
| 57 | + stamp |
| 58 | + ? `"${id}" is not a scene — a scene is the unit an export renders. Export its scene "${stamp}" instead.` |
| 59 | + : `"${id}" is not a scene — a scene is the unit an export renders, so export takes a scene id.`, |
| 60 | + ); |
| 61 | + } |
| 62 | + |
| 63 | + // The scene's entry in the project's package.json (`diffusion.export.<id>`) |
| 64 | + // — the same one the app's export panel writes — so a CLI export |
| 65 | + // reproduces the in-app one; a scene without an entry uses the default |
| 66 | + // template, the way ⌘E does. `template` is only the preset's label. |
| 67 | + const base = world.get(ProjectConfigTrait)?.exportOf(scene) ?? getDefaultExportTemplate(); |
| 68 | + const settings: ExportConfig = { format: base.format, video: base.video, audio: base.audio }; |
| 69 | + |
| 70 | + const format = resolveFormat(path, settings); |
| 71 | + const key = sceneConfigKey(scene) ?? id; |
| 72 | + const target = path ?? `${project.dir()}/exports/${key.replace(/[^\w.-]+/g, "-")}.${format}`; |
| 73 | + |
| 74 | + // Fail before the render machinery spins up: an unencodable configuration |
| 75 | + // is known right away (same precheck the UI export runs). |
| 76 | + const videoEnabled = format !== "ogg" && settings.video?.enabled !== false; |
| 77 | + const computed = scene.get(Computed); |
| 78 | + const { width, height } = computeOutputSize( |
| 79 | + computed?.width || 1920, |
| 80 | + computed?.height || 1080, |
| 81 | + settings.video?.resolution ?? 1080, |
| 82 | + ); |
| 83 | + if (videoEnabled) { |
| 84 | + const codec = settings.video?.codec ?? "avc"; |
| 85 | + const encodable = await canEncodeVideo(codec, { |
| 86 | + width, |
| 87 | + height, |
| 88 | + bitrate: settings.video?.bitrate ?? 10e6, |
| 89 | + }); |
| 90 | + if (!encodable) { |
| 91 | + throw new Error( |
| 92 | + `Cannot encode ${codec.toUpperCase()} at ${width}×${height}. ` + |
| 93 | + "Set a lower resolution, a lower bitrate, or another codec in the scene's export entry.", |
| 94 | + ); |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + const workarea = scene.get(Workarea); |
| 99 | + const frames = workarea ? workarea.end - workarea.start : computed?.duration ?? 0; |
| 100 | + const duration = frames / (world.get(FrameRate)?.value || 30); |
| 101 | + |
| 102 | + // renderScene owns the one render slot (it stops the live engine and |
| 103 | + // raises the progress overlay), so refuse a second export rather than |
| 104 | + // interleave. No await sits between this check and renderScene claiming |
| 105 | + // the overlay, so two racing requests cannot both pass. |
| 106 | + if (renderOverlay()) { |
| 107 | + throw new Error("An export is already running — wait for it to finish, or cancel it in the app."); |
| 108 | + } |
| 109 | + |
| 110 | + const handle = new ElectronWritableFileHandle(target); |
| 111 | + try { |
| 112 | + const result = await renderScene(engine, { |
| 113 | + scene, |
| 114 | + target: handle, |
| 115 | + config: { ...settings, format }, |
| 116 | + dir: project.dir(), |
| 117 | + }); |
| 118 | + if (result.type === "canceled") throw new Error("Export canceled in the app"); |
| 119 | + if (result.type === "error") throw result.error; |
| 120 | + } catch (error) { |
| 121 | + // Close the fd and drop the partial file; a failed export leaves nothing. |
| 122 | + await handle.dispose().catch(() => {}); |
| 123 | + throw error; |
| 124 | + } |
| 125 | + |
| 126 | + const stat = await mainBridge.call(MAIN_CHANNELS.PROJECTS_FS_STAT, { |
| 127 | + dir: project.dir(), |
| 128 | + source: target, |
| 129 | + }); |
| 130 | + |
| 131 | + const config: ExportSettings = { format, video: settings.video, audio: settings.audio }; |
| 132 | + return { |
| 133 | + path: target, |
| 134 | + width: videoEnabled ? width : 0, |
| 135 | + height: videoEnabled ? height : 0, |
| 136 | + duration, |
| 137 | + size: stat?.size ?? 0, |
| 138 | + config, |
| 139 | + }; |
| 140 | + }; |
| 141 | +} |
0 commit comments