@kitsra/kavio-ffmpeg 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,175 @@
1
+ import type { CompositionTiming, KavioAudioAsset, KavioAudioTrack, KavioExportPreset, KavioFit, KavioVideoAsset, KavioVideoCrop, KavioVideoLayer } from "@kitsra/kavio-schema";
2
+ export type FfmpegPlanStepKind = "input" | "filter" | "map" | "output" | "argument";
3
+ export interface FfmpegPlan {
4
+ steps: FfmpegPlanStep[];
5
+ }
6
+ interface FfmpegPlanStepBase {
7
+ id: string;
8
+ kind: FfmpegPlanStepKind;
9
+ description: string;
10
+ args: string[];
11
+ notes?: string[];
12
+ }
13
+ export interface FfmpegInputPlanStep extends FfmpegPlanStepBase {
14
+ kind: "input";
15
+ inputIndex: number;
16
+ source: string;
17
+ }
18
+ export interface FfmpegFilterPlanStep extends FfmpegPlanStepBase {
19
+ kind: "filter";
20
+ chains: FfmpegFilterChain[];
21
+ }
22
+ export interface FfmpegMapPlanStep extends FfmpegPlanStepBase {
23
+ kind: "map";
24
+ labels: string[];
25
+ }
26
+ export interface FfmpegOutputPlanStep extends FfmpegPlanStepBase {
27
+ kind: "output";
28
+ target: string;
29
+ }
30
+ export interface FfmpegArgumentPlanStep extends FfmpegPlanStepBase {
31
+ kind: "argument";
32
+ }
33
+ export type FfmpegPlanStep = FfmpegInputPlanStep | FfmpegFilterPlanStep | FfmpegMapPlanStep | FfmpegOutputPlanStep | FfmpegArgumentPlanStep;
34
+ export interface FfmpegDimensions {
35
+ width: number;
36
+ height: number;
37
+ }
38
+ export interface FfmpegFilterChain {
39
+ inputLabels: string[];
40
+ filters: string[];
41
+ outputLabel: string;
42
+ expression: string;
43
+ }
44
+ export interface FfmpegBaseVideoPlanOptions {
45
+ asset: Pick<KavioVideoAsset, "src" | "trimStartFrames" | "trimEndFrames" | "loop">;
46
+ layer: Pick<KavioVideoLayer, "id" | "asset" | "durationFrames" | "fit" | "crop" | "playbackRate">;
47
+ output: FfmpegDimensions | Pick<CompositionTiming, "width" | "height"> | Pick<KavioExportPreset, "width" | "height">;
48
+ fps: number;
49
+ inputIndex?: number;
50
+ inputLabel?: string;
51
+ outputLabel?: string;
52
+ background?: string;
53
+ }
54
+ export interface FfmpegBaseVideoSequencePlanOptions {
55
+ segments: FfmpegBaseVideoPlanOptions[];
56
+ outputLabel?: string;
57
+ }
58
+ export interface FfmpegInputTrimOptions {
59
+ source: string;
60
+ startFrame?: number;
61
+ durationFrames?: number;
62
+ fps: number;
63
+ }
64
+ export interface FfmpegFitFilterOptions {
65
+ dimensions: FfmpegDimensions;
66
+ fit?: KavioFit;
67
+ crop?: KavioVideoCrop;
68
+ background?: string;
69
+ }
70
+ export interface FfmpegOverlayCompositingOptions {
71
+ baseLabel: string;
72
+ overlayLabel: string;
73
+ outputLabel?: string;
74
+ x?: string | number;
75
+ y?: string | number;
76
+ startFrame?: number;
77
+ durationFrames?: number;
78
+ fps?: number;
79
+ shortest?: boolean;
80
+ }
81
+ export interface FfmpegOverlayFrameInputOptions {
82
+ framePattern: string;
83
+ fps: number;
84
+ inputIndex?: number;
85
+ inputLabel?: string;
86
+ outputLabel?: string;
87
+ startNumber?: number;
88
+ }
89
+ export interface FfmpegOverlayCompositingPlanOptions {
90
+ baseLabel: string;
91
+ frames: FfmpegOverlayFrameInputOptions;
92
+ outputLabel?: string;
93
+ x?: string | number;
94
+ y?: string | number;
95
+ startFrame?: number;
96
+ durationFrames?: number;
97
+ fps?: number;
98
+ shortest?: boolean;
99
+ }
100
+ export interface FfmpegConcatFilterOptions {
101
+ segmentLabels: string[];
102
+ outputLabel?: string;
103
+ }
104
+ export interface FfmpegAudioTrackPlanOptions {
105
+ asset: Pick<KavioAudioAsset | KavioVideoAsset, "src" | "trimStartFrames" | "trimEndFrames" | "loop">;
106
+ track: Pick<KavioAudioTrack, "id" | "asset" | "role" | "startFrame" | "durationFrames" | "offsetFrames" | "volume" | "fadeInFrames" | "fadeOutFrames" | "loop" | "duck">;
107
+ inputIndex?: number;
108
+ inputLabel?: string;
109
+ outputLabel?: string;
110
+ }
111
+ export interface FfmpegAudioMixPlanOptions {
112
+ tracks: FfmpegAudioTrackPlanOptions[];
113
+ fps: number;
114
+ outputLabel?: string;
115
+ normalizeLoudness?: boolean | FfmpegLoudnessNormalizationOptions;
116
+ }
117
+ export interface FfmpegLoudnessNormalizationOptions {
118
+ integratedLufs?: number;
119
+ truePeakDb?: number;
120
+ loudnessRange?: number;
121
+ }
122
+ export declare function createEmptyPlan(): FfmpegPlan;
123
+ export declare function appendPlanStep(plan: FfmpegPlan, step: FfmpegPlanStep): FfmpegPlan;
124
+ export declare function renderFfmpegArgs(plan: FfmpegPlan): string[];
125
+ export declare function framesToSeconds(frames: number, fps: number): number;
126
+ export declare function formatFfmpegTimestamp(seconds: number): string;
127
+ export declare function buildInputTrimArgs(options: FfmpegInputTrimOptions): string[];
128
+ export declare function buildFitVideoFilters(options: FfmpegFitFilterOptions): string[];
129
+ export declare function buildBaseVideoFilterChain(options: FfmpegBaseVideoPlanOptions): FfmpegFilterChain;
130
+ export declare function planBaseVideo(options: FfmpegBaseVideoPlanOptions): FfmpegPlan;
131
+ export declare function planBaseVideoSequence(options: FfmpegBaseVideoSequencePlanOptions): FfmpegPlan;
132
+ export declare function buildOverlayCompositingFilterChain(options: FfmpegOverlayCompositingOptions): FfmpegFilterChain;
133
+ export declare function buildOverlayCompositingArgs(options: FfmpegOverlayCompositingOptions): string[];
134
+ export declare function buildOverlayFrameInputArgs(options: FfmpegOverlayFrameInputOptions): string[];
135
+ export declare function buildOverlayFrameFilterChain(options: FfmpegOverlayFrameInputOptions): FfmpegFilterChain;
136
+ export declare function planOverlayCompositing(options: FfmpegOverlayCompositingPlanOptions): FfmpegPlan;
137
+ export declare function buildConcatFilterChain(options: FfmpegConcatFilterOptions): FfmpegFilterChain;
138
+ export declare function buildAudioMixFilterChains(options: FfmpegAudioMixPlanOptions): FfmpegFilterChain[];
139
+ export declare function planAudioMix(options: FfmpegAudioMixPlanOptions): FfmpegPlan;
140
+ export declare function buildFilterComplexArgs(chains: FfmpegFilterChain[]): string[];
141
+ export declare function createInputStep(options: {
142
+ id: string;
143
+ description: string;
144
+ args: string[];
145
+ inputIndex: number;
146
+ source: string;
147
+ notes?: string[];
148
+ }): FfmpegInputPlanStep;
149
+ export declare function createFilterStep(options: {
150
+ id: string;
151
+ description: string;
152
+ chains: FfmpegFilterChain[];
153
+ notes?: string[];
154
+ }): FfmpegFilterPlanStep;
155
+ export declare function createMapStep(options: {
156
+ id: string;
157
+ description: string;
158
+ labels: string[];
159
+ notes?: string[];
160
+ }): FfmpegMapPlanStep;
161
+ export declare function createOutputStep(options: {
162
+ id: string;
163
+ description: string;
164
+ target: string;
165
+ args?: string[];
166
+ notes?: string[];
167
+ }): FfmpegOutputPlanStep;
168
+ export declare function createArgumentStep(options: {
169
+ id: string;
170
+ description: string;
171
+ args: string[];
172
+ notes?: string[];
173
+ }): FfmpegArgumentPlanStep;
174
+ export {};
175
+ //# sourceMappingURL=index.d.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vB;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;CAAE,GAAG,iBAAiB,CAWjI;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE;IACxC,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB,GAAG,oBAAoB,CAWvB;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE;IAC1C,EAAE,EAAE,MAAM,CAAC;IACX,WAAW,EAAE,MAAM,CAAC;IACpB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;CAClB,GAAG,sBAAsB,CAUzB"}
package/dist/index.js ADDED
@@ -0,0 +1,691 @@
1
+ export function createEmptyPlan() {
2
+ return { steps: [] };
3
+ }
4
+ export function appendPlanStep(plan, step) {
5
+ return { steps: [...plan.steps, step] };
6
+ }
7
+ export function renderFfmpegArgs(plan) {
8
+ return plan.steps.flatMap((step) => step.args);
9
+ }
10
+ export function framesToSeconds(frames, fps) {
11
+ assertNonNegativeFrame(frames, "frames");
12
+ assertPositiveFiniteNumber(fps, "fps");
13
+ return frames / fps;
14
+ }
15
+ export function formatFfmpegTimestamp(seconds) {
16
+ assertFiniteNumber(seconds, "seconds");
17
+ return formatDecimal(seconds);
18
+ }
19
+ export function buildInputTrimArgs(options) {
20
+ assertPositiveFiniteNumber(options.fps, "fps");
21
+ if (options.source.length === 0) {
22
+ throw new Error("FFmpeg input source must not be empty.");
23
+ }
24
+ const args = [];
25
+ if (options.startFrame !== undefined) {
26
+ assertNonNegativeFrame(options.startFrame, "startFrame");
27
+ if (options.startFrame > 0) {
28
+ args.push("-ss", formatFfmpegTimestamp(framesToSeconds(options.startFrame, options.fps)));
29
+ }
30
+ }
31
+ if (options.durationFrames !== undefined) {
32
+ assertPositiveFrame(options.durationFrames, "durationFrames");
33
+ args.push("-t", formatFfmpegTimestamp(framesToSeconds(options.durationFrames, options.fps)));
34
+ }
35
+ args.push("-i", options.source);
36
+ return args;
37
+ }
38
+ export function buildFitVideoFilters(options) {
39
+ const dimensions = normalizeDimensions(options.dimensions);
40
+ const fit = options.fit ?? "cover";
41
+ const background = escapeFilterValue(options.background ?? "black");
42
+ const width = String(dimensions.width);
43
+ const height = String(dimensions.height);
44
+ switch (fit) {
45
+ case "cover":
46
+ return [
47
+ `scale=${width}:${height}:force_original_aspect_ratio=increase`,
48
+ buildCoverCropFilter(width, height, options.crop),
49
+ "setsar=1"
50
+ ];
51
+ case "contain":
52
+ return [
53
+ `scale=${width}:${height}:force_original_aspect_ratio=decrease`,
54
+ `pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2:color=${background}`,
55
+ "setsar=1"
56
+ ];
57
+ case "fill":
58
+ return [`scale=${width}:${height}`, "setsar=1"];
59
+ case "none":
60
+ return ["setsar=1"];
61
+ default:
62
+ throw new Error(`Unsupported video fit "${fit}".`);
63
+ }
64
+ }
65
+ export function buildBaseVideoFilterChain(options) {
66
+ assertPositiveFiniteNumber(options.fps, "fps");
67
+ assertPositiveFrame(options.layer.durationFrames, "layer.durationFrames");
68
+ const inputIndex = options.inputIndex ?? 0;
69
+ const inputLabel = options.inputLabel ?? streamLabel(inputIndex, "v");
70
+ const outputLabel = options.outputLabel ?? `${sanitizeLabelPart(options.layer.id)}_base`;
71
+ const playbackRate = options.layer.playbackRate ?? 1;
72
+ assertPositiveFiniteNumber(playbackRate, "layer.playbackRate");
73
+ const fitOptions = {
74
+ dimensions: normalizeDimensions(options.output)
75
+ };
76
+ if (options.layer.fit !== undefined) {
77
+ fitOptions.fit = options.layer.fit;
78
+ }
79
+ if (options.layer.crop !== undefined) {
80
+ fitOptions.crop = options.layer.crop;
81
+ }
82
+ if (options.background !== undefined) {
83
+ fitOptions.background = options.background;
84
+ }
85
+ const filters = [
86
+ `setpts=${playbackRate === 1 ? "PTS-STARTPTS" : `(PTS-STARTPTS)/${formatDecimal(playbackRate)}`}`,
87
+ ...buildFitVideoFilters(fitOptions)
88
+ ];
89
+ return createFilterChain([inputLabel], filters, outputLabel);
90
+ }
91
+ function buildCoverCropFilter(width, height, crop) {
92
+ if (crop?.mode !== "subject") {
93
+ return `crop=${width}:${height}`;
94
+ }
95
+ const x = escapeFilterExpression(buildSubjectCropExpression(crop, "x"));
96
+ const y = escapeFilterExpression(buildSubjectCropExpression(crop, "y"));
97
+ return `crop=${width}:${height}:${x}:${y}`;
98
+ }
99
+ function buildSubjectCropExpression(crop, axis) {
100
+ const focus = buildSubjectFocusExpression(crop, axis);
101
+ const dimensionExpression = axis === "x" ? "iw-ow" : "ih-oh";
102
+ return `min(max((${dimensionExpression})*(${focus}),0),${dimensionExpression})`;
103
+ }
104
+ function buildSubjectFocusExpression(crop, axis) {
105
+ const points = [];
106
+ const staticValue = crop[axis];
107
+ const keyframes = crop.keyframes ?? [];
108
+ if (keyframes.length === 0 && typeof staticValue === "number") {
109
+ assertNormalizedUnit(staticValue, `crop.${axis}`);
110
+ points.push({ frame: 0, x: crop.x ?? 0.5, y: crop.y ?? 0.5 });
111
+ }
112
+ for (const keyframe of keyframes) {
113
+ assertNonNegativeFrame(keyframe.frame, "crop.keyframes.frame");
114
+ assertNormalizedUnit(keyframe.x, "crop.keyframes.x");
115
+ assertNormalizedUnit(keyframe.y, "crop.keyframes.y");
116
+ points.push({ ...keyframe });
117
+ }
118
+ if (points.length === 0) {
119
+ return "0.5";
120
+ }
121
+ const sorted = [...points].sort((a, b) => a.frame - b.frame);
122
+ if (sorted.length === 1) {
123
+ return formatDecimal(sorted[0][axis]);
124
+ }
125
+ let expression = formatDecimal(sorted[sorted.length - 1][axis]);
126
+ for (let index = sorted.length - 2; index >= 0; index -= 1) {
127
+ const current = sorted[index];
128
+ const next = sorted[index + 1];
129
+ const currentValue = formatDecimal(current[axis]);
130
+ const nextValue = formatDecimal(next[axis]);
131
+ const segment = next.frame === current.frame
132
+ ? currentValue
133
+ : `${currentValue}+(${nextValue}-${currentValue})*(n-${current.frame})/${next.frame - current.frame}`;
134
+ expression = `if(lte(n,${next.frame}),${segment},${expression})`;
135
+ }
136
+ const first = sorted[0];
137
+ return `if(lte(n,${first.frame}),${formatDecimal(first[axis])},${expression})`;
138
+ }
139
+ export function planBaseVideo(options) {
140
+ const inputIndex = options.inputIndex ?? 0;
141
+ const inputStep = buildBaseVideoInputStep(options, inputIndex);
142
+ const filterChain = buildBaseVideoFilterChain(options);
143
+ const steps = [
144
+ inputStep,
145
+ createFilterStep({
146
+ id: `${sanitizeLabelPart(options.layer.id)}:base-filter`,
147
+ description: `Normalize base video layer "${options.layer.id}" to ${options.output.width}x${options.output.height}.`,
148
+ chains: [filterChain]
149
+ })
150
+ ];
151
+ return { steps };
152
+ }
153
+ export function planBaseVideoSequence(options) {
154
+ if (options.segments.length === 0) {
155
+ throw new Error("At least one base video segment is required.");
156
+ }
157
+ const inputSteps = [];
158
+ const chains = [];
159
+ const segmentLabels = [];
160
+ options.segments.forEach((segment, index) => {
161
+ const inputIndex = segment.inputIndex ?? index;
162
+ const fallbackLabel = `${sanitizeLabelPart(segment.layer.id)}_base`;
163
+ const segmentLabel = options.segments.length === 1 ? (options.outputLabel ?? segment.outputLabel ?? fallbackLabel) : (segment.outputLabel ?? `base_segment_${index}`);
164
+ const plannedSegment = withBaseVideoLabels(segment, inputIndex, segmentLabel);
165
+ inputSteps.push(buildBaseVideoInputStep(plannedSegment, inputIndex));
166
+ chains.push(buildBaseVideoFilterChain(plannedSegment));
167
+ segmentLabels.push(segmentLabel);
168
+ });
169
+ if (options.segments.length > 1) {
170
+ chains.push(buildConcatFilterChain({ segmentLabels, outputLabel: options.outputLabel ?? "base_concat" }));
171
+ }
172
+ return {
173
+ steps: [
174
+ ...inputSteps,
175
+ createFilterStep({
176
+ id: "base-video:filter",
177
+ description: options.segments.length === 1
178
+ ? "Normalize one base video segment."
179
+ : `Normalize and concatenate ${options.segments.length} base video segments.`,
180
+ chains
181
+ })
182
+ ]
183
+ };
184
+ }
185
+ export function buildOverlayCompositingFilterChain(options) {
186
+ const outputLabel = options.outputLabel ?? "composited";
187
+ const x = formatOverlayCoordinate(options.x ?? 0);
188
+ const y = formatOverlayCoordinate(options.y ?? 0);
189
+ const overlayOptions = [`x=${x}`, `y=${y}`, "format=auto"];
190
+ if (options.shortest !== undefined) {
191
+ overlayOptions.push(`shortest=${options.shortest ? "1" : "0"}`);
192
+ }
193
+ const enableExpression = buildOverlayEnableExpression(options);
194
+ if (enableExpression !== undefined) {
195
+ overlayOptions.push(`enable='${enableExpression}'`);
196
+ }
197
+ return createFilterChain([options.baseLabel, options.overlayLabel], [`overlay=${overlayOptions.join(":")}`], outputLabel);
198
+ }
199
+ export function buildOverlayCompositingArgs(options) {
200
+ return buildFilterComplexArgs([buildOverlayCompositingFilterChain(options)]);
201
+ }
202
+ export function buildOverlayFrameInputArgs(options) {
203
+ assertPositiveFiniteNumber(options.fps, "fps");
204
+ if (options.framePattern.length === 0) {
205
+ throw new Error("Overlay frame pattern must not be empty.");
206
+ }
207
+ const args = ["-framerate", formatDecimal(options.fps)];
208
+ if (options.startNumber !== undefined) {
209
+ assertNonNegativeFrame(options.startNumber, "startNumber");
210
+ args.push("-start_number", String(options.startNumber));
211
+ }
212
+ args.push("-i", options.framePattern);
213
+ return args;
214
+ }
215
+ export function buildOverlayFrameFilterChain(options) {
216
+ const inputIndex = options.inputIndex ?? 1;
217
+ const inputLabel = options.inputLabel ?? streamLabel(inputIndex, "v");
218
+ const outputLabel = options.outputLabel ?? "overlay_frames";
219
+ return createFilterChain([inputLabel], ["format=rgba", "setpts=PTS-STARTPTS"], outputLabel);
220
+ }
221
+ export function planOverlayCompositing(options) {
222
+ const inputIndex = options.frames.inputIndex ?? 1;
223
+ const overlayLabel = options.frames.outputLabel ?? "overlay_frames";
224
+ const frames = withOverlayFrameLabels(options.frames, inputIndex, overlayLabel);
225
+ const compositeOptions = buildOverlayCompositingPlanFilterOptions(options, overlayLabel);
226
+ return {
227
+ steps: [
228
+ createInputStep({
229
+ id: "overlay-frames:input",
230
+ description: `Read transparent overlay frame sequence "${options.frames.framePattern}".`,
231
+ args: buildOverlayFrameInputArgs(frames),
232
+ inputIndex,
233
+ source: options.frames.framePattern
234
+ }),
235
+ createFilterStep({
236
+ id: "overlay-frames:composite",
237
+ description: "Prepare transparent overlay frames and composite them over the base video.",
238
+ chains: [buildOverlayFrameFilterChain(frames), buildOverlayCompositingFilterChain(compositeOptions)]
239
+ })
240
+ ]
241
+ };
242
+ }
243
+ export function buildConcatFilterChain(options) {
244
+ if (options.segmentLabels.length === 0) {
245
+ throw new Error("At least one segment label is required for concat planning.");
246
+ }
247
+ return createFilterChain(options.segmentLabels, [`concat=n=${options.segmentLabels.length}:v=1:a=0`], options.outputLabel ?? "base_concat");
248
+ }
249
+ export function buildAudioMixFilterChains(options) {
250
+ return buildAudioMixPlanParts(options).chains;
251
+ }
252
+ export function planAudioMix(options) {
253
+ const parts = buildAudioMixPlanParts(options);
254
+ return {
255
+ steps: [
256
+ ...parts.inputSteps,
257
+ createFilterStep({
258
+ id: "audio-mix:filter",
259
+ description: `Mix ${options.tracks.length} audio track${options.tracks.length === 1 ? "" : "s"}.`,
260
+ chains: parts.chains,
261
+ notes: parts.notes
262
+ })
263
+ ]
264
+ };
265
+ }
266
+ export function buildFilterComplexArgs(chains) {
267
+ if (chains.length === 0) {
268
+ return [];
269
+ }
270
+ return ["-filter_complex", chains.map((chain) => chain.expression).join(";")];
271
+ }
272
+ export function createInputStep(options) {
273
+ return withOptionalNotes({
274
+ id: options.id,
275
+ kind: "input",
276
+ description: options.description,
277
+ args: [...options.args],
278
+ inputIndex: options.inputIndex,
279
+ source: options.source
280
+ }, options.notes);
281
+ }
282
+ export function createFilterStep(options) {
283
+ return withOptionalNotes({
284
+ id: options.id,
285
+ kind: "filter",
286
+ description: options.description,
287
+ chains: options.chains.map(cloneFilterChain),
288
+ args: buildFilterComplexArgs(options.chains)
289
+ }, options.notes);
290
+ }
291
+ export function createMapStep(options) {
292
+ return withOptionalNotes({
293
+ id: options.id,
294
+ kind: "map",
295
+ description: options.description,
296
+ labels: [...options.labels],
297
+ args: options.labels.flatMap((label) => ["-map", bracketLabel(label)])
298
+ }, options.notes);
299
+ }
300
+ export function createOutputStep(options) {
301
+ return withOptionalNotes({
302
+ id: options.id,
303
+ kind: "output",
304
+ description: options.description,
305
+ target: options.target,
306
+ args: [...(options.args ?? []), options.target]
307
+ }, options.notes);
308
+ }
309
+ export function createArgumentStep(options) {
310
+ return withOptionalNotes({
311
+ id: options.id,
312
+ kind: "argument",
313
+ description: options.description,
314
+ args: [...options.args]
315
+ }, options.notes);
316
+ }
317
+ function withBaseVideoLabels(options, inputIndex, outputLabel) {
318
+ return {
319
+ ...options,
320
+ inputIndex,
321
+ outputLabel
322
+ };
323
+ }
324
+ function buildBaseVideoInputStep(options, inputIndex) {
325
+ const trimStartFrames = options.asset.trimStartFrames ?? 0;
326
+ assertNonNegativeFrame(trimStartFrames, "asset.trimStartFrames");
327
+ const playbackRate = options.layer.playbackRate ?? 1;
328
+ assertPositiveFiniteNumber(playbackRate, "layer.playbackRate");
329
+ const requestedInputFrames = Math.ceil(options.layer.durationFrames * playbackRate);
330
+ const availableInputFrames = options.asset.trimEndFrames === null || options.asset.trimEndFrames === undefined
331
+ ? undefined
332
+ : Math.max(0, options.asset.trimEndFrames - trimStartFrames);
333
+ const durationFrames = availableInputFrames === undefined || options.asset.loop ? requestedInputFrames : Math.min(requestedInputFrames, availableInputFrames);
334
+ const notes = [];
335
+ if (availableInputFrames !== undefined && availableInputFrames < requestedInputFrames && !options.asset.loop) {
336
+ notes.push("asset trimEndFrames is shorter than the requested layer duration at the configured playback rate");
337
+ }
338
+ if (options.asset.loop) {
339
+ notes.push("asset.loop is recorded for inspection; loop expansion is not emitted by this primitive yet");
340
+ }
341
+ return createInputStep({
342
+ id: `${sanitizeLabelPart(options.layer.id)}:input`,
343
+ description: `Read video asset "${options.layer.asset}" for layer "${options.layer.id}".`,
344
+ args: buildInputTrimArgs({
345
+ source: options.asset.src,
346
+ startFrame: trimStartFrames,
347
+ durationFrames,
348
+ fps: options.fps
349
+ }),
350
+ inputIndex,
351
+ source: options.asset.src,
352
+ notes
353
+ });
354
+ }
355
+ function withOverlayFrameLabels(options, inputIndex, outputLabel) {
356
+ return {
357
+ ...options,
358
+ inputIndex,
359
+ outputLabel
360
+ };
361
+ }
362
+ function buildOverlayCompositingPlanFilterOptions(options, overlayLabel) {
363
+ const compositeOptions = {
364
+ baseLabel: options.baseLabel,
365
+ overlayLabel,
366
+ outputLabel: options.outputLabel ?? "video_composited"
367
+ };
368
+ if (options.x !== undefined) {
369
+ compositeOptions.x = options.x;
370
+ }
371
+ if (options.y !== undefined) {
372
+ compositeOptions.y = options.y;
373
+ }
374
+ if (options.startFrame !== undefined) {
375
+ compositeOptions.startFrame = options.startFrame;
376
+ }
377
+ if (options.durationFrames !== undefined) {
378
+ compositeOptions.durationFrames = options.durationFrames;
379
+ }
380
+ if (options.fps !== undefined) {
381
+ compositeOptions.fps = options.fps;
382
+ }
383
+ if (options.shortest !== undefined) {
384
+ compositeOptions.shortest = options.shortest;
385
+ }
386
+ return compositeOptions;
387
+ }
388
+ function buildAudioMixPlanParts(options) {
389
+ assertPositiveFiniteNumber(options.fps, "fps");
390
+ if (options.tracks.length === 0) {
391
+ throw new Error("At least one audio track is required for mix planning.");
392
+ }
393
+ const voiceoverCount = options.tracks.filter((track) => track.track.role === "voiceover").length;
394
+ if (voiceoverCount > 1) {
395
+ throw new Error("MVP audio mix planning supports at most one voiceover track.");
396
+ }
397
+ const resolvedTracks = options.tracks.map((track, index) => resolveAudioTrackPlan(track, index));
398
+ const chains = [];
399
+ const notes = [];
400
+ const inputSteps = resolvedTracks.map((resolved) => {
401
+ notes.push(...resolved.notes.map((note) => `${resolved.option.track.id}: ${note}`));
402
+ const trimOptions = {
403
+ source: resolved.option.asset.src,
404
+ startFrame: resolved.sourceStartFrame,
405
+ fps: options.fps
406
+ };
407
+ if (resolved.durationFrames !== undefined) {
408
+ trimOptions.durationFrames = resolved.durationFrames;
409
+ }
410
+ return createInputStep({
411
+ id: `${sanitizeLabelPart(resolved.option.track.id)}:audio-input`,
412
+ description: `Read ${resolved.option.track.role} audio asset "${resolved.option.track.asset}" for track "${resolved.option.track.id}".`,
413
+ args: buildInputTrimArgs(trimOptions),
414
+ inputIndex: resolved.inputIndex,
415
+ source: resolved.option.asset.src,
416
+ notes: resolved.notes
417
+ });
418
+ });
419
+ for (const resolved of resolvedTracks) {
420
+ chains.push(buildAudioTrackFilterChain(resolved, options, resolved.outputLabel));
421
+ }
422
+ const mixLabels = new Map();
423
+ for (const resolved of resolvedTracks) {
424
+ mixLabels.set(resolved.option.track.id, resolved.outputLabel);
425
+ }
426
+ for (const resolved of resolvedTracks) {
427
+ const duck = resolved.option.track.duck;
428
+ if (duck === undefined) {
429
+ continue;
430
+ }
431
+ const sidechain = findAudioTrackByRole(resolvedTracks, duck.against, resolved.option.track.id);
432
+ const sidechainDuration = sidechain.durationFrames ?? sidechain.option.track.durationFrames;
433
+ if (sidechainDuration === undefined) {
434
+ throw new Error(`Audio ducking against "${duck.against}" requires the sidechain track durationFrames.`);
435
+ }
436
+ const duckedLabel = `${sanitizeLabelPart(resolved.option.track.id)}_ducked`;
437
+ chains.push(createFilterChain([mixLabels.get(resolved.option.track.id) ?? resolved.outputLabel], [buildAudioDuckingFilter(duck, sidechain.option.track.startFrame, sidechainDuration, options.fps)], duckedLabel));
438
+ mixLabels.set(resolved.option.track.id, duckedLabel);
439
+ notes.push(`${resolved.option.track.id}: ducking represented as a timeline volume envelope against ${duck.against}; sidechain compression execution is deferred`);
440
+ }
441
+ const finalTrackLabels = resolvedTracks.map((resolved) => mixLabels.get(resolved.option.track.id) ?? resolved.outputLabel);
442
+ const mixFilters = [`amix=inputs=${finalTrackLabels.length}:duration=longest:dropout_transition=0`];
443
+ if (options.normalizeLoudness !== false) {
444
+ mixFilters.push(buildLoudnessNormalizationFilter(options.normalizeLoudness));
445
+ }
446
+ chains.push(createFilterChain(finalTrackLabels, mixFilters, options.outputLabel ?? "audio_mix"));
447
+ return { inputSteps, chains, notes };
448
+ }
449
+ function resolveAudioTrackPlan(option, index) {
450
+ assertNonNegativeFrame(option.track.startFrame, "track.startFrame");
451
+ const inputIndex = option.inputIndex ?? index;
452
+ const inputLabel = option.inputLabel ?? streamLabel(inputIndex, "a");
453
+ const outputLabel = option.outputLabel ?? `${sanitizeLabelPart(option.track.id)}_audio`;
454
+ const assetTrimStartFrames = option.asset.trimStartFrames ?? 0;
455
+ const offsetFrames = option.track.offsetFrames ?? 0;
456
+ assertNonNegativeFrame(assetTrimStartFrames, "asset.trimStartFrames");
457
+ assertNonNegativeFrame(offsetFrames, "track.offsetFrames");
458
+ const sourceStartFrame = assetTrimStartFrames + offsetFrames;
459
+ assertNonNegativeFrame(sourceStartFrame, "audio source start frame");
460
+ const notes = [];
461
+ const trimEndFrames = option.asset.trimEndFrames === null ? undefined : option.asset.trimEndFrames;
462
+ let durationFrames = option.track.durationFrames;
463
+ if (durationFrames !== undefined) {
464
+ assertPositiveFrame(durationFrames, "track.durationFrames");
465
+ }
466
+ if (trimEndFrames !== undefined) {
467
+ assertNonNegativeFrame(trimEndFrames, "asset.trimEndFrames");
468
+ const availableFrames = Math.max(0, trimEndFrames - sourceStartFrame);
469
+ if (durationFrames === undefined) {
470
+ durationFrames = availableFrames;
471
+ }
472
+ else if (!option.track.loop && !option.asset.loop) {
473
+ durationFrames = Math.min(durationFrames, availableFrames);
474
+ }
475
+ }
476
+ if (option.track.loop || option.asset.loop) {
477
+ notes.push("loop is recorded for inspection; audio loop expansion is not emitted by this primitive yet");
478
+ }
479
+ const resolved = {
480
+ option,
481
+ inputIndex,
482
+ inputLabel,
483
+ outputLabel,
484
+ sourceStartFrame,
485
+ notes
486
+ };
487
+ if (durationFrames !== undefined) {
488
+ resolved.durationFrames = durationFrames;
489
+ }
490
+ return resolved;
491
+ }
492
+ function buildAudioTrackFilterChain(resolved, options, outputLabel) {
493
+ const track = resolved.option.track;
494
+ const filters = ["asetpts=PTS-STARTPTS", "aresample=async=1"];
495
+ if (track.volume !== undefined) {
496
+ assertNonNegativeFiniteNumber(track.volume, "track.volume");
497
+ if (track.volume !== 1) {
498
+ filters.push(`volume=${formatDecimal(track.volume)}`);
499
+ }
500
+ }
501
+ if (track.fadeInFrames !== undefined) {
502
+ assertNonNegativeFrame(track.fadeInFrames, "track.fadeInFrames");
503
+ if (track.fadeInFrames > 0) {
504
+ filters.push(`afade=t=in:st=0:d=${formatFfmpegTimestamp(framesToSeconds(track.fadeInFrames, options.fps))}`);
505
+ }
506
+ }
507
+ if (track.fadeOutFrames !== undefined) {
508
+ assertNonNegativeFrame(track.fadeOutFrames, "track.fadeOutFrames");
509
+ if (track.fadeOutFrames > 0) {
510
+ if (resolved.durationFrames === undefined) {
511
+ throw new Error(`Audio track "${track.id}" requires durationFrames or trimEndFrames to plan fadeOutFrames.`);
512
+ }
513
+ const fadeOutSeconds = framesToSeconds(track.fadeOutFrames, options.fps);
514
+ const durationSeconds = framesToSeconds(resolved.durationFrames, options.fps);
515
+ filters.push(`afade=t=out:st=${formatFfmpegTimestamp(Math.max(0, durationSeconds - fadeOutSeconds))}:d=${formatFfmpegTimestamp(fadeOutSeconds)}`);
516
+ }
517
+ }
518
+ if (track.startFrame > 0) {
519
+ filters.push(`adelay=${formatFfmpegTimestamp(framesToSeconds(track.startFrame, options.fps) * 1000)}:all=1`);
520
+ }
521
+ return createFilterChain([resolved.inputLabel], filters, outputLabel);
522
+ }
523
+ function findAudioTrackByRole(tracks, role, excludingTrackId) {
524
+ const track = tracks.find((candidate) => candidate.option.track.id !== excludingTrackId && candidate.option.track.role === role);
525
+ if (track === undefined) {
526
+ throw new Error(`Audio ducking requires a track with role "${role}".`);
527
+ }
528
+ return track;
529
+ }
530
+ function buildAudioDuckingFilter(duck, sidechainStartFrame, sidechainDurationFrames, fps) {
531
+ assertNonPositiveFiniteNumber(duck.amountDb, "duck.amountDb");
532
+ const amount = formatDecimal(Math.pow(10, duck.amountDb / 20));
533
+ const start = formatFfmpegTimestamp(framesToSeconds(sidechainStartFrame, fps));
534
+ const end = formatFfmpegTimestamp(framesToSeconds(sidechainStartFrame + sidechainDurationFrames, fps));
535
+ const attackFrames = duck.attackFrames ?? 0;
536
+ const releaseFrames = duck.releaseFrames ?? 0;
537
+ assertNonNegativeFrame(attackFrames, "duck.attackFrames");
538
+ assertNonNegativeFrame(releaseFrames, "duck.releaseFrames");
539
+ const attack = formatFfmpegTimestamp(framesToSeconds(attackFrames, fps));
540
+ const release = formatFfmpegTimestamp(framesToSeconds(releaseFrames, fps));
541
+ let expression;
542
+ if (attackFrames === 0 && releaseFrames === 0) {
543
+ expression = `if(between(t,${start},${end}),${amount},1)`;
544
+ }
545
+ else if (attackFrames === 0) {
546
+ expression = `if(lt(t,${start}),1,if(lte(t,${end}),${amount},if(lt(t,${end}+${release}),${amount}+(1-${amount})*(t-${end})/${release},1)))`;
547
+ }
548
+ else if (releaseFrames === 0) {
549
+ expression = `if(lt(t,${start}),1,if(lt(t,${start}+${attack}),1-(1-${amount})*(t-${start})/${attack},if(lte(t,${end}),${amount},1)))`;
550
+ }
551
+ else {
552
+ expression = `if(lt(t,${start}),1,if(lt(t,${start}+${attack}),1-(1-${amount})*(t-${start})/${attack},if(lte(t,${end}),${amount},if(lt(t,${end}+${release}),${amount}+(1-${amount})*(t-${end})/${release},1))))`;
553
+ }
554
+ return `volume='${escapeFilterExpression(expression)}'`;
555
+ }
556
+ function buildLoudnessNormalizationFilter(options) {
557
+ const normalizedOptions = typeof options === "object" ? options : {};
558
+ const integratedLufs = normalizedOptions.integratedLufs ?? -14;
559
+ const truePeakDb = normalizedOptions.truePeakDb ?? -1.5;
560
+ const loudnessRange = normalizedOptions.loudnessRange ?? 11;
561
+ assertFiniteNumber(integratedLufs, "integratedLufs");
562
+ assertFiniteNumber(truePeakDb, "truePeakDb");
563
+ assertPositiveFiniteNumber(loudnessRange, "loudnessRange");
564
+ return `loudnorm=I=${formatDecimal(integratedLufs)}:TP=${formatDecimal(truePeakDb)}:LRA=${formatDecimal(loudnessRange)}`;
565
+ }
566
+ function createFilterChain(inputLabels, filters, outputLabel) {
567
+ if (inputLabels.length === 0) {
568
+ throw new Error("At least one filter input label is required.");
569
+ }
570
+ if (filters.length === 0) {
571
+ throw new Error("At least one FFmpeg filter is required.");
572
+ }
573
+ return {
574
+ inputLabels: inputLabels.map(unbracketLabel),
575
+ filters: [...filters],
576
+ outputLabel: unbracketLabel(outputLabel),
577
+ expression: `${inputLabels.map(bracketLabel).join("")}${filters.join(",")}${bracketLabel(outputLabel)}`
578
+ };
579
+ }
580
+ function buildOverlayEnableExpression(options) {
581
+ if (options.startFrame === undefined && options.durationFrames === undefined) {
582
+ return undefined;
583
+ }
584
+ if (options.fps === undefined) {
585
+ throw new Error("fps is required when overlay startFrame or durationFrames is provided.");
586
+ }
587
+ const startFrame = options.startFrame ?? 0;
588
+ assertNonNegativeFrame(startFrame, "startFrame");
589
+ const startSeconds = formatFfmpegTimestamp(framesToSeconds(startFrame, options.fps));
590
+ if (options.durationFrames === undefined) {
591
+ return `gte(t,${startSeconds})`;
592
+ }
593
+ assertPositiveFrame(options.durationFrames, "durationFrames");
594
+ const endSeconds = formatFfmpegTimestamp(framesToSeconds(startFrame + options.durationFrames, options.fps));
595
+ return `between(t,${startSeconds},${endSeconds})`;
596
+ }
597
+ function formatOverlayCoordinate(value) {
598
+ if (typeof value === "number") {
599
+ assertFiniteNumber(value, "overlay coordinate");
600
+ return formatDecimal(value);
601
+ }
602
+ if (value.length === 0) {
603
+ throw new Error("Overlay coordinate expression must not be empty.");
604
+ }
605
+ return escapeFilterValue(value);
606
+ }
607
+ function streamLabel(inputIndex, stream) {
608
+ assertNonNegativeFrame(inputIndex, "inputIndex");
609
+ return `${inputIndex}:${stream}`;
610
+ }
611
+ function bracketLabel(label) {
612
+ const value = unbracketLabel(label);
613
+ return `[${value}]`;
614
+ }
615
+ function unbracketLabel(label) {
616
+ if (label.startsWith("[") && label.endsWith("]")) {
617
+ return label.slice(1, -1);
618
+ }
619
+ return label;
620
+ }
621
+ function sanitizeLabelPart(value) {
622
+ const normalized = value.trim().replaceAll(/[^A-Za-z0-9_]+/g, "_").replaceAll(/^_+|_+$/g, "");
623
+ return normalized.length > 0 ? normalized : "layer";
624
+ }
625
+ function normalizeDimensions(dimensions) {
626
+ assertPositiveFrame(dimensions.width, "width");
627
+ assertPositiveFrame(dimensions.height, "height");
628
+ return { width: dimensions.width, height: dimensions.height };
629
+ }
630
+ function escapeFilterValue(value) {
631
+ return value.replaceAll("\\", "\\\\").replaceAll(":", "\\:").replaceAll("'", "\\'");
632
+ }
633
+ function escapeFilterExpression(value) {
634
+ return escapeFilterValue(value).replaceAll(",", "\\,");
635
+ }
636
+ function cloneFilterChain(chain) {
637
+ return {
638
+ inputLabels: [...chain.inputLabels],
639
+ filters: [...chain.filters],
640
+ outputLabel: chain.outputLabel,
641
+ expression: chain.expression
642
+ };
643
+ }
644
+ function withOptionalNotes(step, notes) {
645
+ if (notes === undefined || notes.length === 0) {
646
+ return step;
647
+ }
648
+ return { ...step, notes: [...notes] };
649
+ }
650
+ function formatDecimal(value) {
651
+ assertFiniteNumber(value, "value");
652
+ if (Number.isInteger(value)) {
653
+ return String(value);
654
+ }
655
+ return value.toFixed(6).replace(/0+$/, "").replace(/\.$/, "");
656
+ }
657
+ function assertPositiveFrame(value, name) {
658
+ if (!Number.isSafeInteger(value) || value <= 0) {
659
+ throw new Error(`${name} must be a positive integer.`);
660
+ }
661
+ }
662
+ function assertNonNegativeFrame(value, name) {
663
+ if (!Number.isSafeInteger(value) || value < 0) {
664
+ throw new Error(`${name} must be a non-negative integer.`);
665
+ }
666
+ }
667
+ function assertPositiveFiniteNumber(value, name) {
668
+ if (!Number.isFinite(value) || value <= 0) {
669
+ throw new Error(`${name} must be a positive finite number.`);
670
+ }
671
+ }
672
+ function assertNonNegativeFiniteNumber(value, name) {
673
+ if (!Number.isFinite(value) || value < 0) {
674
+ throw new Error(`${name} must be a non-negative finite number.`);
675
+ }
676
+ }
677
+ function assertNonPositiveFiniteNumber(value, name) {
678
+ if (!Number.isFinite(value) || value > 0) {
679
+ throw new Error(`${name} must be a non-positive finite number.`);
680
+ }
681
+ }
682
+ function assertNormalizedUnit(value, name) {
683
+ if (!Number.isFinite(value) || value < 0 || value > 1) {
684
+ throw new Error(`${name} must be between 0 and 1.`);
685
+ }
686
+ }
687
+ function assertFiniteNumber(value, name) {
688
+ if (!Number.isFinite(value)) {
689
+ throw new Error(`${name} must be finite.`);
690
+ }
691
+ }
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@kitsra/kavio-ffmpeg",
3
+ "version": "0.1.0",
4
+ "description": "FFmpeg planning primitives for Kavio rendering.",
5
+ "license": "Elastic-2.0",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "publishConfig": {
9
+ "access": "public"
10
+ },
11
+ "dependencies": {
12
+ "@kitsra/kavio-schema": "0.1.0"
13
+ },
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist",
22
+ "!dist/**/*.tsbuildinfo",
23
+ "!dist/self-check.*"
24
+ ],
25
+ "scripts": {
26
+ "build": "tsc -p tsconfig.json",
27
+ "check": "tsc -p tsconfig.json --noEmit",
28
+ "test": "tsc -p tsconfig.json && node dist/self-check.js"
29
+ }
30
+ }