@kitsra/kavio-render 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,94 @@
1
+ Elastic License 2.0
2
+
3
+ URL: https://www.elastic.co/licensing/elastic-license
4
+
5
+ Acceptance
6
+
7
+ By using the software, you agree to all of the terms and conditions below.
8
+
9
+ Copyright License
10
+
11
+ The licensor grants you a non-exclusive, royalty-free, worldwide,
12
+ non-sublicensable, non-transferable license to use, copy, distribute, make
13
+ available, and prepare derivative works of the software, in each case subject to
14
+ the limitations and conditions below.
15
+
16
+ Limitations
17
+
18
+ You may not provide the software to third parties as a hosted or managed
19
+ service, where the service provides users with access to any substantial set of
20
+ the features or functionality of the software.
21
+
22
+ You may not move, change, disable, or circumvent the license key functionality
23
+ in the software, and you may not remove or obscure any functionality in the
24
+ software that is protected by the license key.
25
+
26
+ You may not alter, remove, or obscure any licensing, copyright, or other
27
+ notices of the licensor in the software. Any use of the licensor's trademarks
28
+ is subject to applicable law.
29
+
30
+ Patents
31
+
32
+ The licensor grants you a license, under any patent claims the licensor can
33
+ license, or becomes able to license, to make, have made, use, sell, offer for
34
+ sale, import and have imported the software, in each case subject to the
35
+ limitations and conditions in this license. This license does not cover any
36
+ patent claims that you cause to be infringed by modifications or additions to
37
+ the software.
38
+
39
+ If you or your company make any written claim that the software infringes or
40
+ contributes to infringement of any patent, your patent license for the software
41
+ granted under these terms ends immediately. If your company makes such a claim,
42
+ your patent license ends immediately for work on behalf of your company.
43
+
44
+ Notices
45
+
46
+ You must ensure that anyone who gets a copy of any part of the software from
47
+ you also gets a copy of these terms.
48
+
49
+ If you modify the software, you must include in any modified copies of the
50
+ software prominent notices stating that you have modified the software.
51
+
52
+ No Other Rights
53
+
54
+ These terms do not imply any licenses other than those expressly granted in
55
+ these terms.
56
+
57
+ Termination
58
+
59
+ If you use the software in violation of these terms, such use is not licensed,
60
+ and your licenses will automatically terminate. If the licensor provides you
61
+ with a notice of your violation, and you cease all violation of this license no
62
+ later than 30 days after you receive that notice, your licenses will be
63
+ reinstated retroactively. However, if you violate these terms after such
64
+ reinstatement, any additional violation of these terms will cause your licenses
65
+ to terminate automatically and permanently.
66
+
67
+ No Liability
68
+
69
+ As far as the law allows, the software comes as is, without any warranty or
70
+ condition, and the licensor will not be liable to you for any damages arising
71
+ out of these terms or the use or nature of the software, under any kind of
72
+ legal claim.
73
+
74
+ Definitions
75
+
76
+ The licensor is the entity offering these terms, and the software is the
77
+ software the licensor makes available under these terms, including any portion
78
+ of it.
79
+
80
+ you refers to the individual or entity agreeing to these terms.
81
+
82
+ your company is any legal entity, sole proprietorship, or other kind of
83
+ organization that you work for, plus all organizations that have control over,
84
+ are under the control of, or are under common control with that organization.
85
+ control means ownership of substantially all the assets of an entity, or the
86
+ power to direct its management and policies by vote, contract, or otherwise.
87
+ Control can be direct or indirect.
88
+
89
+ your licenses are all the licenses granted to you for the software under these
90
+ terms.
91
+
92
+ use means anything you do with the software requiring one of your licenses.
93
+
94
+ trademark means trademarks, service marks, and similar rights.
@@ -0,0 +1,19 @@
1
+ import type { KavioDocument, KavioExportPreset } from "@kitsra/kavio-schema";
2
+ export interface AssembleRenderCommandOptions {
3
+ /** Composition with props resolved and the export preset already applied. */
4
+ view: KavioDocument;
5
+ preset: KavioExportPreset;
6
+ /** printf-style path to the captured transparent overlay frames, e.g. work/overlay-%05d.png */
7
+ framePattern: string;
8
+ /** Output file path. Defaults to `<preset.name>.<ext>`. */
9
+ outputPath?: string;
10
+ }
11
+ /**
12
+ * Fuse the FFmpeg planner's base-video, overlay, and audio-mix pieces into a single
13
+ * runnable `ffmpeg` argument list. Pure: no IO, no process spawning.
14
+ *
15
+ * Hybrid (source-video base) and graphics-only (generated color base) differ only
16
+ * in how the base stream is produced; everything downstream is identical.
17
+ */
18
+ export declare function assembleRenderCommand(options: AssembleRenderCommandOptions): string[];
19
+ //# sourceMappingURL=assemble-command.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assemble-command.d.ts","sourceRoot":"","sources":["../src/assemble-command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAGV,aAAa,EACb,iBAAiB,EAGlB,MAAM,sBAAsB,CAAC;AAY9B,MAAM,WAAW,4BAA4B;IAC3C,6EAA6E;IAC7E,IAAI,EAAE,aAAa,CAAC;IACpB,MAAM,EAAE,iBAAiB,CAAC;IAC1B,+FAA+F;IAC/F,YAAY,EAAE,MAAM,CAAC;IACrB,2DAA2D;IAC3D,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAMD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,4BAA4B,GAAG,MAAM,EAAE,CA2ErF"}
@@ -0,0 +1,197 @@
1
+ import { extensionForFormat } from "@kitsra/kavio-schema";
2
+ import { buildFilterComplexArgs, planAudioMix, planBaseVideoSequence, planOverlayCompositing } from "@kitsra/kavio-ffmpeg";
3
+ import { renderError } from "./errors.js";
4
+ import { audioEncoder, defaultAudioCodec, defaultVideoCodec, pixelFormat, videoEncoder } from "./encoding.js";
5
+ const VIDEO_OUT_LABEL = "video_out";
6
+ const AUDIO_OUT_LABEL = "audio_out";
7
+ const BASE_LABEL = "base_video";
8
+ /**
9
+ * Fuse the FFmpeg planner's base-video, overlay, and audio-mix pieces into a single
10
+ * runnable `ffmpeg` argument list. Pure: no IO, no process spawning.
11
+ *
12
+ * Hybrid (source-video base) and graphics-only (generated color base) differ only
13
+ * in how the base stream is produced; everything downstream is identical.
14
+ */
15
+ export function assembleRenderCommand(options) {
16
+ const { view, preset, framePattern } = options;
17
+ const fps = preset.fps ?? view.composition.fps;
18
+ const width = preset.width;
19
+ const height = preset.height;
20
+ const background = preset.background ?? view.composition.background ?? "black";
21
+ const outputPath = options.outputPath ?? `${preset.name}.${extensionForFormat(preset.format)}`;
22
+ const durationSeconds = view.composition.durationFrames / fps;
23
+ const inputArgs = [];
24
+ const chains = [];
25
+ let inputIndex = 0;
26
+ // --- Base video: source clips, or a synthesized color background --------
27
+ const videoLayers = view.layers.filter((layer) => layer.type === "video");
28
+ let baseLabel;
29
+ if (videoLayers.length > 0) {
30
+ const segments = videoLayers.map((layer, index) => baseSegment(view, layer, { width, height }, fps, inputIndex + index, background));
31
+ const basePlan = planBaseVideoSequence({ segments, outputLabel: BASE_LABEL });
32
+ inputArgs.push(...planInputArgs(basePlan));
33
+ chains.push(...planFilterChains(basePlan));
34
+ inputIndex += segments.length;
35
+ baseLabel = BASE_LABEL;
36
+ }
37
+ else {
38
+ inputArgs.push("-f", "lavfi", "-i", `color=c=${escapeLavfi(background)}:s=${width}x${height}:r=${fps}:d=${formatSeconds(durationSeconds)}`);
39
+ baseLabel = `${inputIndex}:v`;
40
+ inputIndex += 1;
41
+ }
42
+ // --- Transparent overlay frame sequence ---------------------------------
43
+ const overlayPlan = planOverlayCompositing({
44
+ baseLabel,
45
+ frames: { framePattern, fps, inputIndex, startNumber: 0, outputLabel: "overlay_frames" },
46
+ outputLabel: VIDEO_OUT_LABEL,
47
+ shortest: true
48
+ });
49
+ inputArgs.push(...planInputArgs(overlayPlan));
50
+ chains.push(...planFilterChains(overlayPlan));
51
+ inputIndex += 1;
52
+ // --- Audio: mix declared tracks, or synthesize silence ------------------
53
+ const audioTracks = view.audio ?? [];
54
+ if (audioTracks.length > 0) {
55
+ const trackOptions = audioTracks.map((track, index) => audioOption(view, track, inputIndex + index));
56
+ const audioPlan = planAudioMix({ tracks: trackOptions, fps, outputLabel: AUDIO_OUT_LABEL, normalizeLoudness: true });
57
+ inputArgs.push(...planInputArgs(audioPlan));
58
+ chains.push(...planFilterChains(audioPlan));
59
+ inputIndex += trackOptions.length;
60
+ }
61
+ else {
62
+ inputArgs.push("-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000");
63
+ chains.push(silentAudioChain(inputIndex));
64
+ inputIndex += 1;
65
+ }
66
+ return [
67
+ "-y",
68
+ ...inputArgs,
69
+ ...buildFilterComplexArgs(chains),
70
+ "-map",
71
+ `[${VIDEO_OUT_LABEL}]`,
72
+ "-map",
73
+ `[${AUDIO_OUT_LABEL}]`,
74
+ ...encodeArgs(preset, fps),
75
+ "-t",
76
+ formatSeconds(durationSeconds),
77
+ outputPath
78
+ ];
79
+ }
80
+ function baseSegment(view, layer, output, fps, inputIndex, background) {
81
+ const asset = videoAsset(view, layer.asset, layer.id);
82
+ const segment = {
83
+ asset: {
84
+ src: asset.src,
85
+ trimStartFrames: asset.trimStartFrames ?? 0,
86
+ trimEndFrames: asset.trimEndFrames ?? null,
87
+ loop: asset.loop ?? false
88
+ },
89
+ layer: {
90
+ id: layer.id,
91
+ asset: layer.asset,
92
+ durationFrames: layer.durationFrames,
93
+ fit: layer.fit ?? "cover",
94
+ ...(layer.crop === undefined ? {} : { crop: layer.crop }),
95
+ playbackRate: layer.playbackRate ?? 1
96
+ },
97
+ output,
98
+ fps,
99
+ inputIndex,
100
+ background
101
+ };
102
+ return segment;
103
+ }
104
+ function audioOption(view, track, inputIndex) {
105
+ const asset = audioAsset(view, track.asset);
106
+ return {
107
+ asset: {
108
+ src: asset.src,
109
+ trimStartFrames: asset.trimStartFrames ?? 0,
110
+ trimEndFrames: asset.trimEndFrames ?? null,
111
+ loop: asset.loop ?? false
112
+ },
113
+ track,
114
+ inputIndex
115
+ };
116
+ }
117
+ function silentAudioChain(inputIndex) {
118
+ return {
119
+ inputLabels: [`${inputIndex}:a`],
120
+ filters: ["anull"],
121
+ outputLabel: AUDIO_OUT_LABEL,
122
+ expression: `[${inputIndex}:a]anull[${AUDIO_OUT_LABEL}]`
123
+ };
124
+ }
125
+ function encodeArgs(preset, fps) {
126
+ const codec = preset.codec ?? defaultVideoCodec(preset.format);
127
+ const args = [
128
+ "-c:v",
129
+ videoEncoder(codec),
130
+ "-crf",
131
+ String(preset.crf ?? 18),
132
+ "-pix_fmt",
133
+ pixelFormat(codec),
134
+ "-r",
135
+ String(fps),
136
+ "-c:a",
137
+ audioEncoder(preset.audioCodec ?? defaultAudioCodec(preset.format)),
138
+ "-b:a",
139
+ preset.audioBitrate ?? "192k"
140
+ ];
141
+ if (preset.format === "mp4" || preset.format === "mov") {
142
+ args.push("-movflags", "+faststart");
143
+ }
144
+ return args;
145
+ }
146
+ function planInputArgs(plan) {
147
+ return plan.steps.filter((step) => step.kind === "input").flatMap((step) => step.args);
148
+ }
149
+ function planFilterChains(plan) {
150
+ const chains = [];
151
+ for (const step of plan.steps) {
152
+ if (step.kind === "filter") {
153
+ chains.push(...step.chains);
154
+ }
155
+ }
156
+ return chains;
157
+ }
158
+ function videoAsset(view, id, layerId) {
159
+ const asset = view.assets[id];
160
+ if (asset === undefined || asset.type !== "video") {
161
+ throw renderError({
162
+ code: "ASSET_UNSUPPORTED",
163
+ stage: "render",
164
+ message: `Video layer "${layerId}" references missing or non-video asset "${id}".`,
165
+ path: `assets.${id}`
166
+ });
167
+ }
168
+ return asset;
169
+ }
170
+ function audioAsset(view, id) {
171
+ const asset = view.assets[id];
172
+ if (asset === undefined || asset.type !== "audio") {
173
+ throw renderError({
174
+ code: "ASSET_UNSUPPORTED",
175
+ stage: "render",
176
+ message: `Audio track references missing or non-audio asset "${id}".`,
177
+ path: `assets.${id}`
178
+ });
179
+ }
180
+ return asset;
181
+ }
182
+ function escapeLavfi(value) {
183
+ return value
184
+ .replace(/\\/g, "\\\\")
185
+ .replace(/'/g, "\\'")
186
+ .replace(/:/g, "\\:")
187
+ .replace(/\[/g, "\\[")
188
+ .replace(/\]/g, "\\]")
189
+ .replace(/,/g, "\\,")
190
+ .replace(/;/g, "\\;");
191
+ }
192
+ function formatSeconds(seconds) {
193
+ if (Number.isInteger(seconds)) {
194
+ return String(seconds);
195
+ }
196
+ return seconds.toFixed(6).replace(/0+$/, "").replace(/\.$/, "");
197
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Resolve the path to the bundled FFmpeg binary (`ffmpeg-static`) or fall back to
3
+ * a system `ffmpeg` command available on the PATH. Throws a structured
4
+ * `BINARY_MISSING` error when neither is available.
5
+ */
6
+ export declare function resolveFfmpegPath(): Promise<string>;
7
+ //# sourceMappingURL=binaries.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binaries.d.ts","sourceRoot":"","sources":["../src/binaries.ts"],"names":[],"mappings":"AAKA;;;;GAIG;AACH,wBAAsB,iBAAiB,IAAI,OAAO,CAAC,MAAM,CAAC,CAkCzD"}
@@ -0,0 +1,50 @@
1
+ import { stat } from "node:fs/promises";
2
+ import { renderError } from "./errors.js";
3
+ import { execSync } from "node:child_process";
4
+ /**
5
+ * Resolve the path to the bundled FFmpeg binary (`ffmpeg-static`) or fall back to
6
+ * a system `ffmpeg` command available on the PATH. Throws a structured
7
+ * `BINARY_MISSING` error when neither is available.
8
+ */
9
+ export async function resolveFfmpegPath() {
10
+ // 1. Try resolving system ffmpeg from the environment PATH
11
+ try {
12
+ const systemPath = execSync("which ffmpeg", { stdio: ["ignore", "pipe", "ignore"] })
13
+ .toString()
14
+ .trim();
15
+ if (systemPath.length > 0) {
16
+ await stat(systemPath);
17
+ return systemPath;
18
+ }
19
+ }
20
+ catch {
21
+ // Fall back to ffmpeg-static if system ffmpeg is missing
22
+ }
23
+ // 2. Try resolving bundled ffmpeg-static
24
+ let resolved;
25
+ try {
26
+ const mod = (await import("ffmpeg-static"));
27
+ resolved = mod.default ?? mod;
28
+ }
29
+ catch {
30
+ throw missingFfmpeg();
31
+ }
32
+ if (typeof resolved !== "string" || resolved.length === 0) {
33
+ throw missingFfmpeg();
34
+ }
35
+ try {
36
+ await stat(resolved);
37
+ }
38
+ catch {
39
+ throw missingFfmpeg();
40
+ }
41
+ return resolved;
42
+ }
43
+ function missingFfmpeg() {
44
+ return renderError({
45
+ code: "BINARY_MISSING",
46
+ stage: "ffmpeg",
47
+ message: "Bundled or system FFmpeg is not available.",
48
+ hint: "Install a system ffmpeg or install render binaries with 'corepack pnpm run install:render-binaries'."
49
+ });
50
+ }
@@ -0,0 +1,8 @@
1
+ import type { KavioAudioCodec, KavioExportCodec, KavioExportFormat, KavioExportPreset } from "@kitsra/kavio-schema";
2
+ export declare function withEffectiveCodecs(preset: KavioExportPreset): KavioExportPreset;
3
+ export declare function defaultVideoCodec(format: KavioExportFormat): KavioExportCodec;
4
+ export declare function defaultAudioCodec(format: KavioExportFormat): KavioAudioCodec;
5
+ export declare function videoEncoder(codec: KavioExportCodec): string;
6
+ export declare function audioEncoder(codec: KavioAudioCodec): string;
7
+ export declare function pixelFormat(codec: KavioExportCodec): string;
8
+ //# sourceMappingURL=encoding.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encoding.d.ts","sourceRoot":"","sources":["../src/encoding.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAClB,MAAM,sBAAsB,CAAC;AAE9B,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,iBAAiB,GAAG,iBAAiB,CAMhF;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,iBAAiB,GAAG,gBAAgB,CAW7E;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,iBAAiB,GAAG,eAAe,CAU5E;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAW5D;AAED,wBAAgB,YAAY,CAAC,KAAK,EAAE,eAAe,GAAG,MAAM,CAW3D;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,gBAAgB,GAAG,MAAM,CAS3D"}
@@ -0,0 +1,64 @@
1
+ export function withEffectiveCodecs(preset) {
2
+ return {
3
+ ...preset,
4
+ codec: preset.codec ?? defaultVideoCodec(preset.format),
5
+ audioCodec: preset.audioCodec ?? defaultAudioCodec(preset.format)
6
+ };
7
+ }
8
+ export function defaultVideoCodec(format) {
9
+ switch (format) {
10
+ case "webm":
11
+ return "vp9";
12
+ case "mov":
13
+ return "prores";
14
+ case "mp4":
15
+ case "gif":
16
+ case "png-sequence":
17
+ return "h264";
18
+ }
19
+ }
20
+ export function defaultAudioCodec(format) {
21
+ switch (format) {
22
+ case "webm":
23
+ return "opus";
24
+ case "mp4":
25
+ case "mov":
26
+ case "gif":
27
+ case "png-sequence":
28
+ return "aac";
29
+ }
30
+ }
31
+ export function videoEncoder(codec) {
32
+ switch (codec) {
33
+ case "hevc":
34
+ return "libx265";
35
+ case "vp9":
36
+ return "libvpx-vp9";
37
+ case "prores":
38
+ return "prores_ks";
39
+ case "h264":
40
+ return "libx264";
41
+ }
42
+ }
43
+ export function audioEncoder(codec) {
44
+ switch (codec) {
45
+ case "opus":
46
+ return "libopus";
47
+ case "mp3":
48
+ return "libmp3lame";
49
+ case "pcm":
50
+ return "pcm_s16le";
51
+ case "aac":
52
+ return "aac";
53
+ }
54
+ }
55
+ export function pixelFormat(codec) {
56
+ switch (codec) {
57
+ case "prores":
58
+ return "yuv422p10le";
59
+ case "vp9":
60
+ case "hevc":
61
+ case "h264":
62
+ return "yuv420p";
63
+ }
64
+ }
@@ -0,0 +1,14 @@
1
+ import type { KavioError, KavioErrorStage } from "@kitsra/kavio-schema";
2
+ export declare const RENDER_ERROR_CODES: readonly ["BINARY_MISSING", "BINARY_INCOMPATIBLE", "ASSET_FETCH_FAILED", "ASSET_UNSUPPORTED", "RENDER_FRAME_FAILED", "RENDER_TIMEOUT", "RENDER_CANCELLED", "RENDER_FAILED", "FFMPEG_FAILED", "FFMPEG_TIMEOUT", "IO_WRITE_FAILED", "IO_TEMP_FAILED"];
3
+ export type RenderErrorCode = (typeof RENDER_ERROR_CODES)[number];
4
+ export interface RenderErrorOptions {
5
+ code: RenderErrorCode;
6
+ stage: KavioErrorStage;
7
+ message: string;
8
+ path?: string;
9
+ hint?: string;
10
+ retryable?: boolean;
11
+ }
12
+ export declare function renderError(options: RenderErrorOptions): KavioError;
13
+ export declare function isRenderError(value: unknown): value is KavioError;
14
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAExE,eAAO,MAAM,kBAAkB,qPAarB,CAAC;AAEX,MAAM,MAAM,eAAe,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAElE,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,eAAe,CAAC;IACtB,KAAK,EAAE,eAAe,CAAC;IACvB,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,wBAAgB,WAAW,CAAC,OAAO,EAAE,kBAAkB,GAAG,UAAU,CAenE;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,UAAU,CAOjE"}
package/dist/errors.js ADDED
@@ -0,0 +1,34 @@
1
+ export const RENDER_ERROR_CODES = [
2
+ "BINARY_MISSING",
3
+ "BINARY_INCOMPATIBLE",
4
+ "ASSET_FETCH_FAILED",
5
+ "ASSET_UNSUPPORTED",
6
+ "RENDER_FRAME_FAILED",
7
+ "RENDER_TIMEOUT",
8
+ "RENDER_CANCELLED",
9
+ "RENDER_FAILED",
10
+ "FFMPEG_FAILED",
11
+ "FFMPEG_TIMEOUT",
12
+ "IO_WRITE_FAILED",
13
+ "IO_TEMP_FAILED"
14
+ ];
15
+ export function renderError(options) {
16
+ const error = {
17
+ code: options.code,
18
+ severity: "error",
19
+ message: options.message,
20
+ path: options.path ?? "",
21
+ stage: options.stage,
22
+ retryable: options.retryable ?? false
23
+ };
24
+ if (options.hint !== undefined) {
25
+ error.hint = options.hint;
26
+ }
27
+ return error;
28
+ }
29
+ export function isRenderError(value) {
30
+ return (typeof value === "object" &&
31
+ value !== null &&
32
+ typeof value.code === "string" &&
33
+ typeof value.stage === "string");
34
+ }
@@ -0,0 +1,28 @@
1
+ export interface FfmpegChildStream {
2
+ on(event: "data", listener: (chunk: unknown) => void): void;
3
+ }
4
+ export interface FfmpegChildProcess {
5
+ stdout: FfmpegChildStream | null;
6
+ stderr: FfmpegChildStream | null;
7
+ on(event: "error", listener: (error: Error) => void): void;
8
+ on(event: "close", listener: (code: number | null) => void): void;
9
+ kill(signal?: string): void;
10
+ }
11
+ export type FfmpegSpawn = (command: string, args: readonly string[]) => FfmpegChildProcess;
12
+ export interface FfmpegRunOptions {
13
+ onProgress?: (chunk: string) => void;
14
+ signal?: AbortSignal;
15
+ }
16
+ export interface FfmpegRunResult {
17
+ code: number;
18
+ stderr: string;
19
+ }
20
+ export interface FfmpegRunner {
21
+ run(args: readonly string[], options?: FfmpegRunOptions): Promise<FfmpegRunResult>;
22
+ }
23
+ export interface CreateFfmpegRunnerOptions {
24
+ spawn?: FfmpegSpawn;
25
+ resolveBinary?: () => string | Promise<string>;
26
+ }
27
+ export declare function createFfmpegRunner(options?: CreateFfmpegRunnerOptions): FfmpegRunner;
28
+ //# sourceMappingURL=ffmpeg-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ffmpeg-runner.d.ts","sourceRoot":"","sources":["../src/ffmpeg-runner.ts"],"names":[],"mappings":"AAGA,MAAM,WAAW,iBAAiB;IAChC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,IAAI,GAAG,IAAI,CAAC;CAC7D;AAED,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,iBAAiB,GAAG,IAAI,CAAC;IACjC,MAAM,EAAE,iBAAiB,GAAG,IAAI,CAAC;IACjC,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,GAAG,IAAI,CAAC;IAC3D,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,GAAG,IAAI,CAAC;IAClE,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED,MAAM,MAAM,WAAW,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,SAAS,MAAM,EAAE,KAAK,kBAAkB,CAAC;AAE3F,MAAM,WAAW,gBAAgB;IAC/B,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,IAAI,CAAC;IACrC,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,YAAY;IAC3B,GAAG,CAAC,IAAI,EAAE,SAAS,MAAM,EAAE,EAAE,OAAO,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;CACpF;AAED,MAAM,WAAW,yBAAyB;IACxC,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAChD;AAID,wBAAgB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,YAAY,CA2ExF"}
@@ -0,0 +1,75 @@
1
+ import { resolveFfmpegPath } from "./binaries.js";
2
+ import { renderError } from "./errors.js";
3
+ const STDERR_TAIL_LENGTH = 800;
4
+ export function createFfmpegRunner(options = {}) {
5
+ return {
6
+ async run(args, runOptions = {}) {
7
+ const spawn = options.spawn ?? (await defaultSpawn());
8
+ const binary = await (options.resolveBinary ?? resolveFfmpegPath)();
9
+ return await new Promise((resolve, reject) => {
10
+ const signal = runOptions.signal;
11
+ if (signal?.aborted === true) {
12
+ reject(cancelledError());
13
+ return;
14
+ }
15
+ const child = spawn(binary, args);
16
+ let stderr = "";
17
+ let settled = false;
18
+ const settle = (action) => {
19
+ if (settled) {
20
+ return;
21
+ }
22
+ settled = true;
23
+ if (signal !== undefined) {
24
+ signal.removeEventListener("abort", onAbort);
25
+ }
26
+ action();
27
+ };
28
+ function onAbort() {
29
+ child.kill("SIGKILL");
30
+ settle(() => reject(cancelledError()));
31
+ }
32
+ if (signal !== undefined) {
33
+ signal.addEventListener("abort", onAbort);
34
+ }
35
+ child.stderr?.on("data", (chunk) => {
36
+ stderr = `${stderr}${String(chunk)}`.slice(-STDERR_TAIL_LENGTH);
37
+ });
38
+ if (runOptions.onProgress !== undefined) {
39
+ const onProgress = runOptions.onProgress;
40
+ child.stdout?.on("data", (chunk) => onProgress(String(chunk)));
41
+ }
42
+ child.on("error", (error) => {
43
+ settle(() => reject(renderError({
44
+ code: "FFMPEG_FAILED",
45
+ stage: "ffmpeg",
46
+ message: `Failed to start ffmpeg: ${error.message}`
47
+ })));
48
+ });
49
+ child.on("close", (code) => {
50
+ settle(() => {
51
+ if (code === 0) {
52
+ resolve({ code: 0, stderr });
53
+ return;
54
+ }
55
+ const message = `ffmpeg exited with code ${code ?? "unknown"}.`;
56
+ reject(stderr.length > 0
57
+ ? renderError({ code: "FFMPEG_FAILED", stage: "ffmpeg", message, hint: stderr })
58
+ : renderError({ code: "FFMPEG_FAILED", stage: "ffmpeg", message }));
59
+ });
60
+ });
61
+ });
62
+ }
63
+ };
64
+ }
65
+ function cancelledError() {
66
+ return renderError({
67
+ code: "RENDER_CANCELLED",
68
+ stage: "ffmpeg",
69
+ message: "Render cancelled before ffmpeg completed."
70
+ });
71
+ }
72
+ async function defaultSpawn() {
73
+ const childProcess = await import("node:child_process");
74
+ return (command, args) => childProcess.spawn(command, [...args]);
75
+ }
@@ -0,0 +1,15 @@
1
+ import type { KavioDocument } from "@kitsra/kavio-schema";
2
+ export interface RenderHarnessServer {
3
+ url: string;
4
+ close(): Promise<void>;
5
+ }
6
+ export interface CreateRenderHarnessServerOptions {
7
+ composition: KavioDocument;
8
+ }
9
+ /**
10
+ * Tiny localhost static server that feeds the headless render harness page to
11
+ * Chromium: the shared harness HTML, `/composition.json`, and the vendored
12
+ * `@kitsra/kavio-core` and `@kitsra/kavio-browser-renderer` ESM bundles.
13
+ */
14
+ export declare function createRenderHarnessServer(options: CreateRenderHarnessServerOptions): Promise<RenderHarnessServer>;
15
+ //# sourceMappingURL=harness-server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"harness-server.d.ts","sourceRoot":"","sources":["../src/harness-server.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAwB,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAEhF,MAAM,WAAW,mBAAmB;IAClC,GAAG,EAAE,MAAM,CAAC;IACZ,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,MAAM,WAAW,gCAAgC;IAC/C,WAAW,EAAE,aAAa,CAAC;CAC5B;AAED;;;;GAIG;AACH,wBAAsB,yBAAyB,CAC7C,OAAO,EAAE,gCAAgC,GACxC,OAAO,CAAC,mBAAmB,CAAC,CA0B9B"}