@margoengine/headless 0.1.0 → 1.0.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.
@@ -1,6 +1,6 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
- const a=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
3
+ const a=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
4
  import { i as e } from "./src-VufTH2fo.js";
5
5
  import { n as t, r as n, t as r } from "./errors-CDgOgzCd.js";
6
6
  import { readTexture as i } from "./formats.js";
@@ -0,0 +1,15 @@
1
+ //#region src/ffmpeg-colour.ts
2
+ var e = "setparams=color_primaries=bt709:color_trc=iec61966-2-1:colorspace=bt709:range=tv:chroma_location=left", t = (t) => `scale=out_color_matrix=bt709:out_range=tv:out_chroma_loc=left,format=${t},${e}`, n = [
3
+ "-colorspace",
4
+ "bt709",
5
+ "-color_primaries",
6
+ "bt709",
7
+ "-color_trc",
8
+ "iec61966-2-1",
9
+ "-color_range",
10
+ "tv",
11
+ "-chroma_sample_location",
12
+ "left"
13
+ ];
14
+ //#endregion
15
+ export { e as n, t as r, n as t };
@@ -1,3 +1,5 @@
1
+ /** The tags the frames carry (setparams): ffmpeg 9 writes them into the stream over the output options. */
2
+ export declare const TAG_FILTER = "setparams=color_primaries=bt709:color_trc=iec61966-2-1:colorspace=bt709:range=tv:chroma_location=left";
1
3
  /** The filter that turns RGB(A) frames into `format` with the engine's matrix, range, chroma siting and tags. */
2
4
  export declare const colourFilter: (format: string) => string;
3
5
  /** The output options that tag the stream as the filter made it. */
@@ -1,5 +1,5 @@
1
1
  import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
2
- import { n as r, t as i } from "./ffmpeg-colour-Cg00HQ4H.js";
2
+ import { r, t as i } from "./ffmpeg-colour-B_r-2O-e.js";
3
3
  import { spawn as a } from "node:child_process";
4
4
  import { open as o, rename as s, rm as c, writeFile as l } from "node:fs/promises";
5
5
  import { basename as u, dirname as d, join as f, resolve as p } from "node:path";
package/dist/ffmpeg.d.ts CHANGED
@@ -21,6 +21,11 @@ export interface FFmpegOptions {
21
21
  layers?: readonly FFmpegLayer[];
22
22
  /** Stops ffmpeg; the promise rejects with the signal's reason, and a partial file may stay behind. Default none. */
23
23
  signal?: AbortSignal;
24
+ /** Who makes the 4:2:0 picture. `'sharp'` (default): the engine (`@margoengine/headless/yuv420`), choosing each
25
+ * block's chroma and each pixel's luma so the frame a player decodes matches the render, and ffmpeg reads I420;
26
+ * slower (seconds a 1080p frame with much fine colour detail), for film delivery. `'scaler'`: ffmpeg's scaler
27
+ * filters the RGBA frames. `args`, `alpha` and `layers` always use the scaler (the layer graph works in RGB). */
28
+ chroma?: 'sharp' | 'scaler';
24
29
  }
25
30
  /** A file laid over the rendered frames by {@link encodeWithFFmpeg}. */
26
31
  export interface FFmpegLayer {
@@ -130,7 +135,7 @@ export declare function resolveLayers(layers: readonly FFmpegLayer[], { ffmpeg,
130
135
  signal?: AbortSignal;
131
136
  }): Promise<FFmpegLayer[]>;
132
137
  /** The full ffmpeg argument list for a stream of RGBA frames on standard input. */
133
- export declare function ffmpegArguments(width: number, height: number, { output, fps, args, audio, alpha, layers, }: Pick<FFmpegOptions, 'output' | 'fps' | 'args' | 'audio' | 'alpha' | 'layers'>): string[];
138
+ export declare function ffmpegArguments(width: number, height: number, { output, fps, args, audio, alpha, layers, chroma, }: Pick<FFmpegOptions, 'output' | 'fps' | 'args' | 'audio' | 'alpha' | 'layers' | 'chroma'>): string[];
134
139
  /**
135
140
  * The ffmpeg argument list of {@link layersOverPicture}: `picture` (`width` x `height`, one frame) as frame `frame` of
136
141
  * a video at `fps`, with `layers` laid over it by the same graph {@link encodeWithFFmpeg} uses, written to `output` as
package/dist/ffmpeg.js CHANGED
@@ -1,29 +1,29 @@
1
1
  import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
2
- import { n as r, t as i } from "./ffmpeg-colour-Cg00HQ4H.js";
3
- import { spawn as a } from "node:child_process";
4
- import { hexColor as o } from "@margoengine/math/color";
2
+ import { r, t as i } from "./ffmpeg-colour-B_r-2O-e.js";
3
+ import { Yuv420Pool as a } from "./yuv420-pool.js";
4
+ import { spawn as o } from "node:child_process";
5
+ import { hexColor as s } from "@margoengine/math/color";
5
6
  //#region src/ffmpeg.ts
6
- var s = (e) => [
7
+ var c = (e) => [
7
8
  "-vf",
8
9
  r(e),
9
10
  ...i
10
- ], c = [
11
+ ], l = [
11
12
  "-c:v",
12
13
  "libvpx-vp9",
13
14
  "-crf",
14
15
  "32",
15
16
  "-b:v",
16
17
  "0"
17
- ], l = [
18
- ...s("yuv420p"),
18
+ ], u = [
19
19
  "-c:v",
20
20
  "libx264",
21
21
  "-crf",
22
22
  "20",
23
23
  "-movflags",
24
24
  "+faststart"
25
- ], u = 3, d = 16384;
26
- function f({ channels: t, sampleRate: n, bitrate: r = 128e3 }) {
25
+ ], d = [...c("yuv420p"), ...u], f = 3, p = 16384;
26
+ function m({ channels: t, sampleRate: n, bitrate: r = 128e3 }) {
27
27
  if (!Array.isArray(t) || t.length !== 1 && t.length !== 2) throw e("Audio takes one or two channels", "headless");
28
28
  let i = t[0].length;
29
29
  if (!i || t.some((e) => !(e instanceof Float32Array) || e.length !== i)) throw e("Audio channels must be Float32Arrays of one length, above 0", "headless");
@@ -31,36 +31,40 @@ function f({ channels: t, sampleRate: n, bitrate: r = 128e3 }) {
31
31
  if (!(r > 0) || !Number.isFinite(r)) throw e("Invalid audio bitrate", "headless");
32
32
  return i;
33
33
  }
34
- function p(e, t, n) {
34
+ function h(e, t, n) {
35
35
  let r = e.length, i = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer((n - t) * r * 4));
36
36
  for (let a = t, o = 0; a < n; a++) for (let t = 0; t < r; t++, o += 4) i.setFloat32(o, e[t][a], !0);
37
37
  return new Uint8Array(i.buffer);
38
38
  }
39
- function m(e, t, r) {
39
+ function g({ args: t, alpha: n, layers: r, chroma: i = "sharp" }) {
40
+ if (i !== "sharp" && i !== "scaler") throw e(`chroma must be 'sharp' or 'scaler', got ${String(i)}`, "headless");
41
+ return i === "sharp" && !t && !n && !r?.length;
42
+ }
43
+ function _(e, t, r) {
40
44
  if (r && (t || !/\.webm$/i.test(e))) throw n("unsupported", "Alpha video needs a .webm file and the default arguments", "headless");
41
45
  }
42
- var h = (e) => String(Math.round(e * 1e6) / 1e6), g = "flags=lanczos+accurate_rnd+full_chroma_int", _ = [
46
+ var v = (e) => String(Math.round(e * 1e6) / 1e6), y = "flags=lanczos+accurate_rnd+full_chroma_int", b = [
43
47
  "bt709",
44
48
  "bt601",
45
49
  "bt2020"
46
50
  ];
47
- function v(e) {
48
- let t = o(e);
51
+ function x(e) {
52
+ let t = s(e);
49
53
  return t && `0x${t.map((e) => Math.round(e * 255).toString(16).padStart(2, "0")).join("")}`;
50
54
  }
51
- function y(n, r, i) {
55
+ function S(n, r, i) {
52
56
  if (i === void 0) return [];
53
57
  if (!Array.isArray(i)) throw t("layers must be an array", "headless");
54
58
  return i.map((i, a) => {
55
- let o = `Layer ${a}`, { input: s, rect: c, start: l = 0, duration: u, in: d = 0, speed: f = 1, fit: p = "contain", crop: m, pad: h, matrix: g, range: y } = i ?? {};
59
+ let o = `Layer ${a}`, { input: s, rect: c, start: l = 0, duration: u, in: d = 0, speed: f = 1, fit: p = "contain", crop: m, pad: h, matrix: g, range: _ } = i ?? {};
56
60
  if (typeof s != "string" || !s) throw t(`${o} needs an input file`, "headless");
57
- let { x: b, y: x, width: S, height: C } = c ?? {};
61
+ let { x: v, y, width: S, height: C } = c ?? {};
58
62
  if (![
59
- b,
60
- x,
63
+ v,
64
+ y,
61
65
  S,
62
66
  C
63
- ].every(Number.isInteger) || b < 0 || x < 0 || S < 1 || C < 1 || b + S > n || x + C > r) throw e(`${o} rect must be whole pixels inside the ${n}x${r} frame`, "headless");
67
+ ].every(Number.isInteger) || v < 0 || y < 0 || S < 1 || C < 1 || v + S > n || y + C > r) throw e(`${o} rect must be whole pixels inside the ${n}x${r} frame`, "headless");
64
68
  if (!(l >= 0) || !Number.isFinite(l)) throw e(`${o} start must be 0 or more seconds`, "headless");
65
69
  if (u !== void 0 && (!(u > 0) || !Number.isFinite(u))) throw e(`${o} duration must be above 0 seconds`, "headless");
66
70
  if (!(d >= 0) || !Number.isFinite(d)) throw e(`${o} in must be 0 or more seconds`, "headless");
@@ -71,14 +75,14 @@ function y(n, r, i) {
71
75
  "fill"
72
76
  ].includes(p)) throw e(`${o} fit is 'contain', 'cover' or 'fill'`, "headless");
73
77
  if (m !== void 0 && (!Array.isArray(m) || m.length !== 4 || !m.every((e) => Number.isInteger(e) && e >= 0 && e % 2 == 0) || m[2] < 2 || m[3] < 2)) throw e(`${o} crop is [x, y, width, height] in even whole pixels, width and height from 2`, "headless");
74
- let w = h === void 0 ? "0x00000000" : typeof h == "string" ? v(h) : void 0;
78
+ let w = h === void 0 ? "0x00000000" : typeof h == "string" ? x(h) : void 0;
75
79
  if (!w) throw e(`${o} pad is a colour '#rgb', '#rrggbb' or '#rrggbbaa'`, "headless");
76
- if (g !== void 0 && !_.includes(g)) throw e(`${o} matrix is 'bt709', 'bt601' or 'bt2020'`, "headless");
77
- if (y !== void 0 && y !== "tv" && y !== "pc") throw e(`${o} range is 'tv' or 'pc'`, "headless");
80
+ if (g !== void 0 && !b.includes(g)) throw e(`${o} matrix is 'bt709', 'bt601' or 'bt2020'`, "headless");
81
+ if (_ !== void 0 && _ !== "tv" && _ !== "pc") throw e(`${o} range is 'tv' or 'pc'`, "headless");
78
82
  return {
79
83
  input: s,
80
- x: b,
81
- y: x,
84
+ x: v,
85
+ y,
82
86
  w: S,
83
87
  h: C,
84
88
  start: l,
@@ -89,23 +93,23 @@ function y(n, r, i) {
89
93
  crop: m,
90
94
  padding: w,
91
95
  matrix: g,
92
- range: y
96
+ range: _
93
97
  };
94
98
  });
95
99
  }
96
- function b(e, t, n, r, i = "0:v") {
100
+ function C(e, t, n, r, i = "0:v") {
97
101
  let a = [], o = [], s = .5 / n;
98
102
  return e.forEach((e, r) => {
99
- a.push(...e.from ? ["-ss", h(e.from)] : [], ...e.duration ? ["-t", h(e.duration * e.speed + 1)] : [], "-i", e.input);
100
- let c = `${e.matrix ? `:in_color_matrix=${e.matrix}` : ""}${e.range ? `:in_range=${e.range}` : ""}`, l = (e, t) => `scale=${e}:${t}${c}:${g},format=rgba`, u = "iw*sar/ih", d = `gt(${u},${e.w}/${e.h})`, f = `max(1,round(${e.h}*${u}))`, p = `max(1,round(${e.w}/(${u})))`, m = e.fit === "cover" ? `${l(`'if(${d},${f},${e.w})'`, `'if(${d},${e.h},${p})'`)},crop=${e.w}:${e.h}` : e.fit === "fill" ? l(e.w, e.h) : `${l(`'if(${d},${e.w},${f})'`, `'if(${d},${p},${e.h})'`)},pad=${e.w}:${e.h}:(ow-iw)/2:(oh-ih)/2:color=${e.padding}`, _ = e.crop ? `crop=${e.crop[2]}:${e.crop[3]}:${e.crop[0]}:${e.crop[1]},` : "", v = e.duration ? e.start + e.duration : void 0, y = v === void 0 ? "" : `,tpad=stop_mode=clone:stop_duration=${h(e.duration)},trim=end=${h(v)}`, b = v === void 0 ? `gte(t,${h(e.start - s)})` : `between(t,${h(e.start - s)},${h(v - s)})`;
101
- o.push(`[${t + r}:v]${_}setpts=(PTS-STARTPTS)/${h(e.speed)}+${h(e.start)}/TB,fps=${h(n)}:round=near${y},${m},setsar=1[l${r}]`), o.push(`[${i}][l${r}]overlay=x=${e.x}:y=${e.y}:format=rgb:eof_action=pass:enable='${b}'[b${r + 1}]`), i = `b${r + 1}`;
103
+ a.push(...e.from ? ["-ss", v(e.from)] : [], ...e.duration ? ["-t", v(e.duration * e.speed + 1)] : [], "-i", e.input);
104
+ let c = `${e.matrix ? `:in_color_matrix=${e.matrix}` : ""}${e.range ? `:in_range=${e.range}` : ""}`, l = (e, t) => `scale=${e}:${t}${c}:${y},format=rgba`, u = "iw*sar/ih", d = `gt(${u},${e.w}/${e.h})`, f = `max(1,round(${e.h}*${u}))`, p = `max(1,round(${e.w}/(${u})))`, m = e.fit === "cover" ? `${l(`'if(${d},${f},${e.w})'`, `'if(${d},${e.h},${p})'`)},crop=${e.w}:${e.h}` : e.fit === "fill" ? l(e.w, e.h) : `${l(`'if(${d},${e.w},${f})'`, `'if(${d},${p},${e.h})'`)},pad=${e.w}:${e.h}:(ow-iw)/2:(oh-ih)/2:color=${e.padding}`, h = e.crop ? `crop=${e.crop[2]}:${e.crop[3]}:${e.crop[0]}:${e.crop[1]},` : "", g = e.duration ? e.start + e.duration : void 0, _ = g === void 0 ? "" : `,tpad=stop_mode=clone:stop_duration=${v(e.duration)},trim=end=${v(g)}`, b = g === void 0 ? `gte(t,${v(e.start - s)})` : `between(t,${v(e.start - s)},${v(g - s)})`;
105
+ o.push(`[${t + r}:v]${h}setpts=(PTS-STARTPTS)/${v(e.speed)}+${v(e.start)}/TB,fps=${v(n)}:round=near${_},${m},setsar=1[l${r}]`), o.push(`[${i}][l${r}]overlay=x=${e.x}:y=${e.y}:format=rgb:eof_action=pass:enable='${b}'[b${r + 1}]`), i = `b${r + 1}`;
102
106
  }), o.push(`[${i}]${r}[v]`), {
103
107
  inputs: a,
104
108
  graph: o.join(";")
105
109
  };
106
110
  }
107
- var x = /^(?:rgb|bgr|gbr|argb|abgr|0rgb|0bgr|x2rgb|x2bgr|pal8|gray|ya8|ya16|monow|monob)/;
108
- function S(e) {
111
+ var w = /^(?:rgb|bgr|gbr|argb|abgr|0rgb|0bgr|x2rgb|x2bgr|pal8|gray|ya8|ya16|monow|monob)/;
112
+ function T(e) {
109
113
  let t = /^\s*Stream #\d+:\d+.*?: Video: (.*)$/m.exec(e)?.[1];
110
114
  if (!t) return;
111
115
  let n = [], r = 0, i = "";
@@ -119,16 +123,16 @@ function S(e) {
119
123
  pixelFormat: c,
120
124
  width: Number(s[1]),
121
125
  height: Number(s[2]),
122
- rgb: x.test(c) || d === "gbr",
126
+ rgb: w.test(c) || d === "gbr",
123
127
  ...d && d !== "unknown" ? { matrix: d } : {},
124
128
  ...u ? { range: u } : {}
125
129
  };
126
130
  }
127
- function C(e, t, r, i = !1) {
131
+ function E(e, t, r, i = !1) {
128
132
  r?.throwIfAborted();
129
- let [o, ...s] = typeof e == "string" ? [e] : e;
133
+ let [a, ...s] = typeof e == "string" ? [e] : e;
130
134
  return new Promise((e, c) => {
131
- let l = "", u = a(o, [...s, ...t], {
135
+ let l = "", u = o(a, [...s, ...t], {
132
136
  stdio: [
133
137
  "ignore",
134
138
  "ignore",
@@ -143,24 +147,24 @@ function C(e, t, r, i = !1) {
143
147
  });
144
148
  });
145
149
  }
146
- async function w(e, { ffmpeg: r = "ffmpeg", signal: i } = {}) {
150
+ async function D(e, { ffmpeg: r = "ffmpeg", signal: i } = {}) {
147
151
  if (typeof e != "string" || !e) throw t("probeVideo needs an input file", "headless");
148
- let a = await C(r, [
152
+ let a = await E(r, [
149
153
  "-hide_banner",
150
154
  "-nostdin",
151
155
  "-i",
152
156
  e
153
- ], i), o = S(a);
157
+ ], i), o = T(a);
154
158
  if (!o) throw Object.assign(n("failed", `ffmpeg found no video stream in ${e}`, "headless"), { cause: a.slice(-4096) });
155
159
  return o;
156
160
  }
157
- async function T(n, { ffmpeg: r = "ffmpeg", signal: i } = {}) {
161
+ async function O(n, { ffmpeg: r = "ffmpeg", signal: i } = {}) {
158
162
  if (!Array.isArray(n)) throw t("layers must be an array", "headless");
159
163
  let a = /* @__PURE__ */ new Map();
160
164
  return Promise.all(n.map(async (n, o) => {
161
165
  if (typeof n?.input != "string" || !n.input) throw t(`Layer ${o} needs an input file`, "headless");
162
166
  if (n.matrix && n.range && !n.crop) return { ...n };
163
- a.has(n.input) || a.set(n.input, w(n.input, {
167
+ a.has(n.input) || a.set(n.input, D(n.input, {
164
168
  ffmpeg: r,
165
169
  signal: i
166
170
  }));
@@ -180,18 +184,23 @@ async function T(n, { ffmpeg: r = "ffmpeg", signal: i } = {}) {
180
184
  };
181
185
  }));
182
186
  }
183
- function E(e, t, { output: n, fps: r = 30, args: i, audio: a, alpha: o, layers: d }) {
184
- m(n, i, o);
185
- let f = y(e, t, d), p = /\.webm$/i.test(n), h = a ? {
187
+ function k(e, t, { output: n, fps: r = 30, args: a, audio: o, alpha: s, layers: p, chroma: m = "sharp" }) {
188
+ _(n, a, s);
189
+ let h = S(e, t, p), v = g({
190
+ args: a,
191
+ alpha: s,
192
+ layers: p,
193
+ chroma: m
194
+ }), y = /\.webm$/i.test(n), b = o ? {
186
195
  input: [
187
196
  "-f",
188
197
  "f32le",
189
198
  "-ar",
190
- String(a.sampleRate),
199
+ String(o.sampleRate),
191
200
  "-ac",
192
- String(a.channels.length),
201
+ String(o.channels.length),
193
202
  "-i",
194
- `pipe:${u}`
203
+ `pipe:${f}`
195
204
  ],
196
205
  map: [
197
206
  "-map",
@@ -200,49 +209,65 @@ function E(e, t, { output: n, fps: r = 30, args: i, audio: a, alpha: o, layers:
200
209
  "1:a:0"
201
210
  ],
202
211
  codec: [
203
- ...p ? ["-c:a", "libopus"] : ["-c:a", "aac"],
212
+ ...y ? ["-c:a", "libopus"] : ["-c:a", "aac"],
204
213
  "-b:a",
205
- String(Math.round(a.bitrate ?? 128e3))
214
+ String(Math.round(o.bitrate ?? 128e3))
206
215
  ]
207
- } : void 0, g = [
216
+ } : void 0, x = [
208
217
  "-y",
209
218
  "-f",
210
219
  "rawvideo",
211
220
  "-pix_fmt",
212
- "rgba",
221
+ v ? "yuv420p" : "rgba",
222
+ ...v ? [
223
+ "-color_range",
224
+ "tv",
225
+ "-colorspace",
226
+ "bt709",
227
+ "-chroma_sample_location",
228
+ "left"
229
+ ] : [],
213
230
  "-s",
214
231
  `${e}x${t}`,
215
232
  "-r",
216
233
  String(r),
217
234
  "-i",
218
235
  "pipe:0"
219
- ], _ = i ?? [...p ? [...s(o ? "yuva420p" : "yuv420p"), ...c] : l, ...h?.codec ?? []];
220
- if (!f.length) return [
221
- ...g,
222
- ...h ? [...h.input, ...h.map] : ["-an"],
223
- ..._,
236
+ ], w = a ?? (v ? [
237
+ "-vf",
238
+ "setparams=color_primaries=bt709:color_trc=iec61966-2-1:colorspace=bt709:range=tv:chroma_location=left",
239
+ ...i,
240
+ "-pix_fmt",
241
+ "yuv420p",
242
+ ...y ? l : u,
243
+ ...b?.codec ?? []
244
+ ] : [...y ? [...c(s ? "yuva420p" : "yuv420p"), ...l] : d, ...b?.codec ?? []]);
245
+ if (!h.length) return [
246
+ ...x,
247
+ ...b ? [...b.input, ...b.map] : ["-an"],
248
+ ...w,
224
249
  n
225
250
  ];
226
- let v = _.indexOf("-vf"), { inputs: x, graph: S } = b(f, h ? 2 : 1, r, v < 0 ? "null" : _[v + 1]);
251
+ let T = w.indexOf("-vf"), { inputs: E, graph: D } = C(h, b ? 2 : 1, r, T < 0 ? "null" : w[T + 1]);
227
252
  return [
228
- ...g,
229
- ...h?.input ?? [],
230
253
  ...x,
254
+ ...b?.input ?? [],
255
+ ...E,
231
256
  "-filter_complex",
232
- S,
257
+ D,
233
258
  "-map",
234
259
  "[v]",
235
- ...h ? ["-map", "1:a:0"] : ["-an"],
236
- ...v < 0 ? _ : [..._.slice(0, v), ..._.slice(v + 2)],
260
+ ...b ? ["-map", "1:a:0"] : ["-an"],
261
+ ...T < 0 ? w : [...w.slice(0, T), ...w.slice(T + 2)],
237
262
  n
238
263
  ];
239
264
  }
240
- function D(n, r, { picture: i, output: a, fps: o = 30, frame: s, layers: c }) {
265
+ function A(n, r, { picture: i, output: a, fps: o = 30, frame: s, layers: c }) {
241
266
  if (typeof i != "string" || !i) throw t("layersOverPicture needs a picture file", "headless");
242
267
  if (typeof a != "string" || !a) throw t("layersOverPicture needs an output file", "headless");
243
268
  if (!(o > 0) || !Number.isFinite(o)) throw e("Invalid fps", "headless");
244
269
  if (!Number.isInteger(s) || s < 0) throw e("frame must be a whole number from 0", "headless");
245
- let { inputs: l, graph: u } = b(y(n, r, c), 1, o, "format=rgb24", "p");
270
+ let { inputs: l, graph: u } = C(S(n, r, c), 1, o, "format=rgb24", "p");
246
271
  return [
247
272
  "-y",
248
273
  "-framerate",
@@ -261,21 +286,21 @@ function D(n, r, { picture: i, output: a, fps: o = 30, frame: s, layers: c }) {
261
286
  a
262
287
  ];
263
288
  }
264
- async function O(e, t, r) {
265
- let { fps: i = 30, frame: a, layers: o, ffmpeg: s = "ffmpeg", signal: c } = r ?? {}, l = await w(e, {
289
+ async function j(e, t, r) {
290
+ let { fps: i = 30, frame: a, layers: o, ffmpeg: s = "ffmpeg", signal: c } = r ?? {}, l = await D(e, {
266
291
  ffmpeg: s,
267
292
  signal: c
268
- }), u = await C(s, [
293
+ }), u = await E(s, [
269
294
  "-hide_banner",
270
295
  "-nostdin",
271
296
  "-v",
272
297
  "error",
273
- ...D(l.width, l.height, {
298
+ ...A(l.width, l.height, {
274
299
  picture: e,
275
300
  output: t,
276
301
  fps: i,
277
302
  frame: a,
278
- layers: await T(o, {
303
+ layers: await O(o, {
279
304
  ffmpeg: s,
280
305
  signal: c
281
306
  })
@@ -283,7 +308,7 @@ async function O(e, t, r) {
283
308
  ], c, !0);
284
309
  if (u !== void 0) throw Object.assign(n("failed", "ffmpeg failed", "headless"), { cause: u.slice(-4096) });
285
310
  }
286
- function k(e, t, n, r, i) {
311
+ function M(e, t, n, r, i) {
287
312
  let a = new Uint8Array(r * i * 4);
288
313
  for (let o = 0; o < i; o++) {
289
314
  let i = Math.min(o, n - 1) * t * 4, s = o * r * 4;
@@ -292,27 +317,33 @@ function k(e, t, n, r, i) {
292
317
  }
293
318
  return a;
294
319
  }
295
- async function A(r, i) {
296
- let { output: o, fps: s = 30, ffmpeg: c = "ffmpeg", signal: l, audio: d } = i;
297
- if (typeof o != "string" || !o) throw t("encodeWithFFmpeg needs an output file", "headless");
298
- if (!(s > 0) || !Number.isFinite(s)) throw e("Invalid fps", "headless");
299
- let p = d === void 0 ? 0 : f(d);
300
- m(o, i.args, i.alpha), l?.throwIfAborted();
301
- let h = i.layers === void 0 ? void 0 : await T(i.layers, {
302
- ffmpeg: c,
303
- signal: l
304
- }), g = {
320
+ async function N(r, i) {
321
+ let { output: s, fps: c = 30, ffmpeg: l = "ffmpeg", signal: u, audio: d } = i;
322
+ if (typeof s != "string" || !s) throw t("encodeWithFFmpeg needs an output file", "headless");
323
+ if (!(c > 0) || !Number.isFinite(c)) throw e("Invalid fps", "headless");
324
+ let p = d === void 0 ? 0 : m(d);
325
+ _(s, i.args, i.alpha), u?.throwIfAborted();
326
+ let h = i.layers === void 0 ? void 0 : await O(i.layers, {
327
+ ffmpeg: l,
328
+ signal: u
329
+ }), v = {
305
330
  ...i,
306
331
  layers: h
307
- }, [_, ...v] = typeof c == "string" ? [c] : c, y, b, x = !1, S = () => {}, C = 0, w = 0, D = 0, O = 0, A = 0, M = "", N, P = () => y?.kill();
308
- l?.addEventListener("abort", P, { once: !0 });
332
+ }, y = g(v), b = y ? new a() : void 0, x = [], [S, ...C] = typeof l == "string" ? [l] : l, w, T, E = !1, D = () => {}, A = 0, j = 0, N = 0, F = 0, I = 0, L = "", R, z = () => w?.kill();
333
+ u?.addEventListener("abort", z, { once: !0 });
334
+ let B = async (e) => {
335
+ if (!E && w && !w.stdin.write(e)) {
336
+ let e = w.stdin, t = () => D();
337
+ e.once("drain", t), await new Promise((e) => D = e), e.off("drain", t);
338
+ }
339
+ };
309
340
  try {
310
341
  for await (let t of r) {
311
- if (l?.throwIfAborted(), !y) {
312
- ({width: C, height: w} = t);
313
- let e = !i.args && !/\.webm$/i.test(o);
314
- [D, O] = e ? [C + (C & 1), w + (w & 1)] : [C, w];
315
- let r = a(_, [...v, ...E(D, O, g)], {
342
+ if (u?.throwIfAborted(), !w) {
343
+ ({width: A, height: j} = t);
344
+ let e = !i.args && !/\.webm$/i.test(s) || y;
345
+ [N, F] = e ? [A + (A & 1), j + (j & 1)] : [A, j];
346
+ let r = o(S, [...C, ...k(N, F, v)], {
316
347
  stdio: d ? [
317
348
  "pipe",
318
349
  "ignore",
@@ -325,42 +356,41 @@ async function A(r, i) {
325
356
  ],
326
357
  windowsHide: !0
327
358
  });
328
- y = r, r.stderr.setEncoding("utf8").on("data", (e) => {
329
- M = (M + e).slice(-4096);
330
- }), r.stdin.on("error", () => {}), b = new Promise((e, t) => {
359
+ w = r, r.stderr.setEncoding("utf8").on("data", (e) => {
360
+ L = (L + e).slice(-4096);
361
+ }), r.stdin.on("error", () => {}), T = new Promise((e, t) => {
331
362
  r.once("error", (e) => {
332
- x = !0, S(), t(e.code === "ENOENT" ? Object.assign(n("unsupported", "ffmpeg was not found", "headless"), { cause: e }) : e);
363
+ E = !0, D(), t(e.code === "ENOENT" ? Object.assign(n("unsupported", "ffmpeg was not found", "headless"), { cause: e }) : e);
333
364
  }), r.once("close", (r) => {
334
- x = !0, S(), r === 0 ? e() : t(Object.assign(n("failed", "ffmpeg failed", "headless"), { cause: M }));
365
+ E = !0, D(), r === 0 ? e() : t(Object.assign(n("failed", "ffmpeg failed", "headless"), { cause: L }));
335
366
  });
336
- }), b.catch(() => {}), d && (N = j(r.stdio[u], d.channels, p, () => x));
337
- } else if (t.width !== C || t.height !== w) throw e("Video frames must all be one size", "headless");
338
- if (t.data.length !== C * w * 4) throw e("Frame data does not match its size", "headless");
339
- if (x) break;
340
- let r = D === C && O === w ? t.data : k(t.data, C, w, D, O);
341
- if (!y.stdin.write(r)) {
342
- let e = y.stdin, t = () => S();
343
- e.once("drain", t), await new Promise((e) => S = e), e.off("drain", t);
344
- }
345
- A++;
367
+ }), T.catch(() => {}), d && (R = P(r.stdio[f], d.channels, p, () => E));
368
+ } else if (t.width !== A || t.height !== j) throw e("Video frames must all be one size", "headless");
369
+ if (t.data.length !== A * j * 4) throw e("Frame data does not match its size", "headless");
370
+ if (E) break;
371
+ let r = N === A && F === j ? t.data : M(t.data, A, j, N, F);
372
+ b ? (x.push(b.convert(r, N, F)), x.length >= b.size * 2 && await B(await x.shift())) : await B(r), I++;
346
373
  }
347
- if (!y) throw n("state", "No frames to encode", "headless");
348
- return y.stdin.end(), await N, await b, {
349
- output: o,
350
- width: D,
351
- height: O,
352
- frames: A,
374
+ for (; x.length && !E;) await B(await x.shift());
375
+ if (!w) throw n("state", "No frames to encode", "headless");
376
+ return w.stdin.end(), await R, await T, {
377
+ output: s,
378
+ width: N,
379
+ height: F,
380
+ frames: I,
353
381
  ...d ? { audioDuration: p / d.sampleRate } : {}
354
382
  };
355
383
  } catch (e) {
356
- throw l?.throwIfAborted(), e;
384
+ throw u?.throwIfAborted(), e;
357
385
  } finally {
358
- l?.removeEventListener("abort", P), y && !x && y.kill();
386
+ u?.removeEventListener("abort", z), w && !E && w.kill();
387
+ for (let e of x) e.catch(() => {});
388
+ await b?.close();
359
389
  }
360
390
  }
361
- async function j(e, t, n, r) {
391
+ async function P(e, t, n, r) {
362
392
  e.on("error", () => {});
363
- for (let i = 0; i < n && !r(); i += d) e.write(p(t, i, Math.min(n, i + d))) || await new Promise((t) => {
393
+ for (let i = 0; i < n && !r(); i += p) e.write(h(t, i, Math.min(n, i + p))) || await new Promise((t) => {
364
394
  let n = () => {
365
395
  e.off("drain", n), e.off("close", n), t();
366
396
  };
@@ -369,4 +399,4 @@ async function j(e, t, n, r) {
369
399
  e.end();
370
400
  }
371
401
  //#endregion
372
- export { A as encodeWithFFmpeg, E as ffmpegArguments, O as layersOverPicture, D as layersPictureArguments, w as probeVideo, T as resolveLayers };
402
+ export { N as encodeWithFFmpeg, k as ffmpegArguments, j as layersOverPicture, A as layersPictureArguments, D as probeVideo, O as resolveLayers };
package/dist/formats.js CHANGED
@@ -1,6 +1,6 @@
1
- // @margo/core-built 0.1.0
1
+ // @margo/core-built 1.0.0
2
2
  import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
- const r=(engine,version="0.1.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
3
+ const r=(engine,version="1.0.0",source=import.meta.url)=>__margoRuntime(engine,version,source);
4
4
  import { n as e, r as t, t as n } from "./errors-CDgOgzCd.js";
5
5
  import { engineRuntime as __margoRuntime } from "@margoengine/core/extension";
6
6
  //#region src/formats.ts
@@ -0,0 +1,87 @@
1
+ import type { HeadlessPixels } from './index.js';
2
+ /** An 8-bit sRGB frame: RGBA, straight alpha, top row first, as `readPixels` and `decodePNG` give. */
3
+ export type LookImage = HeadlessPixels;
4
+ /** A mask: one byte per pixel, or RGBA where the first channel counts. 128 and above is inside. */
5
+ export interface LookMask {
6
+ width: number;
7
+ height: number;
8
+ data: Uint8Array;
9
+ }
10
+ /** A float frame, RGBA: `Float32Array`, or `Uint16Array` of half-float bits as an `rgba16float` readback holds them. */
11
+ export interface FloatFrame {
12
+ width: number;
13
+ height: number;
14
+ data: Float32Array | Uint16Array;
15
+ }
16
+ /** A bound from a shot file's `lookBounds`: a number is the largest value that passes, `[low, high]` a range. */
17
+ export type LookBound = number | readonly [number, number];
18
+ /** The name of a look check, as `lookBounds` names it. */
19
+ export type LookCheckName = 'skyClip' | 'grain' | 'speckle' | 'banding' | 'flat' | 'blocks' | 'horizonSeam' | 'waterSeam' | 'lights' | 'foamEdges' | 'crush' | 'flicker' | 'shimmer' | 'nan' | 'backends' | 'reference' | 'penumbra' | 'penumbraPlants' | 'stairs' | 'colourEdges' | 'chromaSmear' | 'shimmerMoving' | 'motionBlur' | 'silhouette' | 'silhouetteShape' | 'bounce' | 'shadowTint' | 'nightLuma' | 'nightPeak';
20
+ /** What a check gives back. */
21
+ export interface LookResult {
22
+ /** The check's name. */
23
+ check: LookCheckName | string;
24
+ /** The measured value, in `unit`. NaN when the check could not run (`missing`), which never passes. */
25
+ value: number;
26
+ /** `[low, high]`: the value passes when inside, ends included. */
27
+ bound: [number, number];
28
+ pass: boolean;
29
+ unit: string;
30
+ /** Set when the check could not run: what was missing. */
31
+ missing?: string;
32
+ /**
33
+ * Set with `missing` when the check could not run because the frame holds too little of what it measures, as
34
+ * counted against what it needs: T6 with fewer than 30 (`GROUND_MIN_PIXELS`) umbra or lit ground pixels (a shot whose sun
35
+ * casts no full shadow in frame). The row is never a pass (`pass` stays false, `value` NaN); the report shows it as
36
+ * "not run" with `missing`, and a probe's verdict leaves it out as it leaves out a family check with no input. A bound
37
+ * the shot names itself for the check turns it into a failure (KB-LOOK-TV-POOLFAILS1, rail-line).
38
+ */
39
+ notRun?: true;
40
+ /**
41
+ * Set when the check ran over a mask with no pixels in it, so it measured nothing: for example `0 sky pixels` for
42
+ * a shot with no sky in view. The row passes, and the report says what it measured, so the pass is never silent.
43
+ */
44
+ empty?: string;
45
+ /**
46
+ * The mask the check measured inside, by name, when {@link checkProbe} chose one: `sky` (the page's sky mask),
47
+ * `sky-coverage` (the pixels `@margoengine/sky` drew, when there is no `sky` mask) or `frame` (the whole frame).
48
+ * Set on `skyClip`; the report says which.
49
+ */
50
+ mask?: string;
51
+ /** Further numbers the check measured, for the report. */
52
+ detail: Record<string, number>;
53
+ }
54
+ /** Each check's default bound, its unit and what it measures. A shot's `lookBounds` replaces the bound by name. */
55
+ export declare const LOOK_CHECKS: Readonly<Record<LookCheckName, {
56
+ bound: [number, number];
57
+ unit: string;
58
+ about: string;
59
+ }>>;
60
+ export declare const finite: (value: unknown) => value is number;
61
+ /** The `[low, high]` of a bound: a number is the high end, with no low end. */
62
+ export declare function lookBound(bound: LookBound): [number, number];
63
+ export declare function result(check: LookCheckName, value: number, bound: LookBound | undefined, detail?: Record<string, number>): LookResult;
64
+ /** A row for a check that could not run, which fails: an asked-for check that did not run is not a pass. */
65
+ export declare function missingResult(check: LookCheckName | string, missing: string, bound?: LookBound): LookResult;
66
+ export declare function checkImage(image: LookImage, what?: string): void;
67
+ export declare function sameSize(a: {
68
+ width: number;
69
+ height: number;
70
+ }, b: {
71
+ width: number;
72
+ height: number;
73
+ }, what: string): void;
74
+ /** Inside flags of a mask, one per pixel, or all inside when no mask is given. */
75
+ export declare function maskBits(frame: {
76
+ width: number;
77
+ height: number;
78
+ }, mask: LookMask | undefined, what: string, least?: number): Uint8Array;
79
+ /** Luma of each pixel on 0 to 255: BT.709 weights on the encoded values. */
80
+ export declare function luma(image: LookImage): Float32Array;
81
+ export declare const percent: (part: number, whole: number) => number;
82
+ /** Options of {@link flicker} and {@link shimmer}. */
83
+ export interface FlickerOptions {
84
+ /** Only pixels inside this mask count. */
85
+ mask?: LookMask;
86
+ bound?: LookBound;
87
+ }