@motionhub/oms 0.0.0-stage → 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/README.md +31 -2
- package/dist/LICENSE +201 -0
- package/dist/OFL.txt +91 -0
- package/dist/example/film.tsx +97 -0
- package/dist/film-format.md +53 -0
- package/dist/player.js +1 -0
- package/dist/resources/preview/core.js +66 -0
- package/dist/resources/preview/pick.js +1 -0
- package/dist/starter.tsx +35 -0
- package/dist/worker.cjs +2980 -0
- package/oms.mjs +225 -0
- package/package.json +34 -3
- package/skills/oms/SKILL.md +25 -0
- package/skills/oms/references/assets.md +15 -0
- package/skills/oms/references/craft.md +49 -0
- package/skills/oms/references/drawing.md +29 -0
- package/skills/oms/references/look.md +35 -0
- package/skills/oms/references/review.md +33 -0
package/dist/worker.cjs
ADDED
|
@@ -0,0 +1,2980 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
20
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
21
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
22
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
23
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
24
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
25
|
+
mod
|
|
26
|
+
));
|
|
27
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
28
|
+
|
|
29
|
+
// worker.ts
|
|
30
|
+
var worker_exports = {};
|
|
31
|
+
__export(worker_exports, {
|
|
32
|
+
OFL: () => OFL,
|
|
33
|
+
VOICE_ENV: () => VOICE_ENV,
|
|
34
|
+
check: () => check,
|
|
35
|
+
effectsTrack: () => effectsTrack,
|
|
36
|
+
motionWords: () => motionWords,
|
|
37
|
+
pack: () => pack,
|
|
38
|
+
parseCues: () => parseCues,
|
|
39
|
+
player: () => player,
|
|
40
|
+
preview: () => preview,
|
|
41
|
+
record: () => record,
|
|
42
|
+
recordingReport: () => recordingReport,
|
|
43
|
+
render: () => render,
|
|
44
|
+
renderStages: () => renderStages,
|
|
45
|
+
searchMotions: () => searchMotions,
|
|
46
|
+
still: () => still,
|
|
47
|
+
takeFont: () => takeFont,
|
|
48
|
+
useMotion: () => useMotion,
|
|
49
|
+
voice: () => voice2,
|
|
50
|
+
voiceSetup: () => voiceSetup,
|
|
51
|
+
voices: () => voices
|
|
52
|
+
});
|
|
53
|
+
module.exports = __toCommonJS(worker_exports);
|
|
54
|
+
var import_node_crypto7 = require("node:crypto");
|
|
55
|
+
var import_promises12 = require("node:fs/promises");
|
|
56
|
+
var import_node_os3 = require("node:os");
|
|
57
|
+
var import_node_path14 = require("node:path");
|
|
58
|
+
|
|
59
|
+
// ../desktop/src/main/film/film.ts
|
|
60
|
+
var import_node_module = require("node:module");
|
|
61
|
+
var import_promises2 = require("node:fs/promises");
|
|
62
|
+
var import_node_path2 = require("node:path");
|
|
63
|
+
|
|
64
|
+
// ../desktop/src/main/motions.ts
|
|
65
|
+
var import_node_fs = require("node:fs");
|
|
66
|
+
var import_promises = require("node:fs/promises");
|
|
67
|
+
var import_node_path = require("node:path");
|
|
68
|
+
|
|
69
|
+
// ../desktop/src/main/project.ts
|
|
70
|
+
var STATE_DIR = ".motion-studio";
|
|
71
|
+
|
|
72
|
+
// ../desktop/src/main/motions.ts
|
|
73
|
+
var hub = () => import("@motionhub/cli/hub");
|
|
74
|
+
var HUB = "https://motionhub.dev";
|
|
75
|
+
var MOTIONS = "motions";
|
|
76
|
+
var INDEX_MS = 5 * 6e4;
|
|
77
|
+
var cached = null;
|
|
78
|
+
async function rows(base) {
|
|
79
|
+
if (cached && cached.base === base && Date.now() - cached.at < INDEX_MS) return cached.rows;
|
|
80
|
+
const fetched = await (await hub()).index(base);
|
|
81
|
+
cached = { base, at: Date.now(), rows: fetched };
|
|
82
|
+
return fetched;
|
|
83
|
+
}
|
|
84
|
+
var english = (text) => text ? text.en ?? Object.values(text)[0] ?? "" : "";
|
|
85
|
+
function row(motion, base) {
|
|
86
|
+
return {
|
|
87
|
+
id: motion.slug,
|
|
88
|
+
version: motion.version,
|
|
89
|
+
name: english(motion.name),
|
|
90
|
+
line: english(motion.line),
|
|
91
|
+
fit: english(motion.fit?.for),
|
|
92
|
+
tags: motion.tags,
|
|
93
|
+
poster: motion.poster ? new URL(motion.poster, base).href : null,
|
|
94
|
+
page: new URL(`/m/${motion.slug}`, base).href
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
async function searchMotions(words, base = HUB) {
|
|
98
|
+
const { search } = await hub();
|
|
99
|
+
const all = await rows(base);
|
|
100
|
+
const wanted = [...new Set(words.toLowerCase().split(/\s+/).filter(Boolean))];
|
|
101
|
+
if (!wanted.length) return all.map((motion) => row(motion, base));
|
|
102
|
+
const matched = /* @__PURE__ */ new Map();
|
|
103
|
+
for (const word of wanted) for (const motion of search(all, [word])) matched.set(motion, (matched.get(motion) ?? 0) + 1);
|
|
104
|
+
return [...matched].sort((a, b) => b[1] - a[1]).map(([motion]) => row(motion, base));
|
|
105
|
+
}
|
|
106
|
+
async function motionWords(base = HUB) {
|
|
107
|
+
const counts = /* @__PURE__ */ new Map();
|
|
108
|
+
for (const motion of await rows(base)) for (const tag of [...motion.tags, ...motion.catalogs ?? []]) counts.set(tag, (counts.get(tag) ?? 0) + 1);
|
|
109
|
+
return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([tag]) => tag);
|
|
110
|
+
}
|
|
111
|
+
async function useMotion(dir, id, base = HUB) {
|
|
112
|
+
if (typeof id !== "string" || !/^@[A-Za-z0-9-]+\/[a-z0-9-]+$/.test(id)) throw new Error(`Not a motion id: ${String(id)}`);
|
|
113
|
+
const { getMotion, motionPath, readLock, writeLock } = await hub();
|
|
114
|
+
const out = motionPath(id, dir);
|
|
115
|
+
if ((0, import_node_fs.existsSync)(out)) throw new Error(`The project already holds ${id}.`);
|
|
116
|
+
const lock = readLock(dir);
|
|
117
|
+
const taken = await getMotion(id, out, base, await rows(base));
|
|
118
|
+
lock.motions[id] = { version: taken.version, sha256: taken.package.sha256 };
|
|
119
|
+
writeLock(lock, dir);
|
|
120
|
+
return described(dir, id, taken.version, "");
|
|
121
|
+
}
|
|
122
|
+
async function described(dir, id, version, source) {
|
|
123
|
+
const folder = (0, import_node_path.join)(dir, MOTIONS, ...id.split("/"));
|
|
124
|
+
let manifest = {};
|
|
125
|
+
try {
|
|
126
|
+
manifest = JSON.parse(await (0, import_promises.readFile)((0, import_node_path.join)(folder, "motion.json"), "utf8"));
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error.code !== "ENOENT") throw error;
|
|
129
|
+
}
|
|
130
|
+
const path = (0, import_node_path.join)(MOTIONS, ...id.split("/"));
|
|
131
|
+
return {
|
|
132
|
+
id,
|
|
133
|
+
path,
|
|
134
|
+
name: english(manifest.name) || id,
|
|
135
|
+
line: english(manifest.line),
|
|
136
|
+
version,
|
|
137
|
+
fromHub: id.startsWith("@"),
|
|
138
|
+
// The film's code imports a motion from its folder, whose path holds its id.
|
|
139
|
+
used: source.includes(id),
|
|
140
|
+
poster: (0, import_node_fs.existsSync)((0, import_node_path.join)(folder, "poster.jpg")) ? web((0, import_node_path.join)(path, "poster.jpg")) : null
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
var web = (path) => path.split(/[/\\]/).join("/");
|
|
144
|
+
var directories = async (dir) => {
|
|
145
|
+
try {
|
|
146
|
+
return (await (0, import_promises.readdir)(dir, { withFileTypes: true })).filter((d) => d.isDirectory()).map((d) => d.name);
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (error.code === "ENOENT") return [];
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
async function motionIds(dir) {
|
|
153
|
+
const ids = [];
|
|
154
|
+
for (const name of await directories((0, import_node_path.join)(dir, MOTIONS))) {
|
|
155
|
+
if (name.startsWith("@")) {
|
|
156
|
+
for (const slug2 of await directories((0, import_node_path.join)(dir, MOTIONS, name))) ids.push(`${name}/${slug2}`);
|
|
157
|
+
} else ids.push(name);
|
|
158
|
+
}
|
|
159
|
+
return ids.sort();
|
|
160
|
+
}
|
|
161
|
+
var cssString = (text) => `"${text.replace(/[\\"]/g, "\\$&").replace(/[\n\r\f]/g, " ")}"`;
|
|
162
|
+
async function motionFaces(dir) {
|
|
163
|
+
const rules = [];
|
|
164
|
+
const skipped = [];
|
|
165
|
+
for (const id of await motionIds(dir)) {
|
|
166
|
+
const fonts = (0, import_node_path.join)(dir, MOTIONS, id, "react", "fonts");
|
|
167
|
+
let list;
|
|
168
|
+
try {
|
|
169
|
+
list = JSON.parse(await (0, import_promises.readFile)((0, import_node_path.join)(fonts, "fonts.json"), "utf8"));
|
|
170
|
+
} catch (error) {
|
|
171
|
+
if (error.code === "ENOENT") continue;
|
|
172
|
+
skipped.push(`${id}: react/fonts/fonts.json is not JSON`);
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
if (!Array.isArray(list)) {
|
|
176
|
+
skipped.push(`${id}: react/fonts/fonts.json is not a list`);
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
for (const face of list) {
|
|
180
|
+
const { family, file, weight, style } = face ?? {};
|
|
181
|
+
if (typeof family !== "string" || !family.trim() || typeof file !== "string" || !/^[^/\\]+\.woff2$/.test(file) || file.startsWith(".")) {
|
|
182
|
+
skipped.push(`${id}: a face needs a family and a .woff2 file in react/fonts/ (${JSON.stringify(face)})`);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (!(0, import_node_fs.existsSync)((0, import_node_path.join)(fonts, file))) {
|
|
186
|
+
skipped.push(`${id}: react/fonts/${file} is not there`);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
const url = ["", "project", MOTIONS, ...id.split("/"), "react", "fonts", file].map(encodeURIComponent).join("/");
|
|
190
|
+
const descriptors = [
|
|
191
|
+
`font-family: ${cssString(family.trim())}`,
|
|
192
|
+
`src: url(${cssString(url)}) format("woff2")`,
|
|
193
|
+
// a weight is a number or a range of two ("100 900"); a style is a keyword
|
|
194
|
+
typeof weight === "number" || typeof weight === "string" && /^\d{1,3}( \d{1,3})?$/.test(weight) ? `font-weight: ${weight}` : "",
|
|
195
|
+
typeof style === "string" && /^(normal|italic|oblique)$/.test(style) ? `font-style: ${style}` : "",
|
|
196
|
+
"font-display: block"
|
|
197
|
+
].filter(Boolean);
|
|
198
|
+
rules.push(`@font-face { ${descriptors.join("; ")}; }`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
return { css: rules.join("\n"), skipped };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// ../desktop/src/main/log.ts
|
|
205
|
+
var stderr = console.error.bind(console);
|
|
206
|
+
var runtime;
|
|
207
|
+
function log(event, fields = {}) {
|
|
208
|
+
runtime?.write(event, fields);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ../desktop/src/main/film/film.ts
|
|
212
|
+
var require2 = (0, import_node_module.createRequire)(__filename);
|
|
213
|
+
var bundlerEntry = require2.resolve("esbuild").replace(/([/\\])app\.asar([/\\])/, "$1app.asar.unpacked$2");
|
|
214
|
+
log("bundler.load", { entry: bundlerEntry });
|
|
215
|
+
var { build, context, formatMessages } = require2(bundlerEntry);
|
|
216
|
+
var FILM = "film.tsx";
|
|
217
|
+
var buildDir = (dir) => (0, import_node_path2.join)(dir, STATE_DIR, "build");
|
|
218
|
+
var FACES = "fonts.css";
|
|
219
|
+
var PROVIDED = ["react", "react/jsx-runtime", "@motionhub/runtime"];
|
|
220
|
+
var threeModules = (0, import_node_path2.dirname)((0, import_node_path2.dirname)((0, import_node_path2.dirname)(require2.resolve("three")))).replace(/([/\\])app\.asar([/\\])/, "$1app.asar.unpacked$2");
|
|
221
|
+
var THREE = /* @__PURE__ */ Symbol("three");
|
|
222
|
+
var studioThree = {
|
|
223
|
+
name: "studio-three",
|
|
224
|
+
setup(build2) {
|
|
225
|
+
build2.onResolve(
|
|
226
|
+
{ filter: /^three(\/|$)/ },
|
|
227
|
+
(args) => args.pluginData === THREE ? void 0 : build2.resolve(args.path, { kind: args.kind, resolveDir: threeModules, pluginData: THREE })
|
|
228
|
+
);
|
|
229
|
+
}
|
|
230
|
+
};
|
|
231
|
+
var ASSETS = [
|
|
232
|
+
".png",
|
|
233
|
+
".jpg",
|
|
234
|
+
".jpeg",
|
|
235
|
+
".gif",
|
|
236
|
+
".webp",
|
|
237
|
+
".avif",
|
|
238
|
+
".svg",
|
|
239
|
+
".woff",
|
|
240
|
+
".woff2",
|
|
241
|
+
".ttf",
|
|
242
|
+
".otf",
|
|
243
|
+
".mp4",
|
|
244
|
+
".webm",
|
|
245
|
+
".mp3",
|
|
246
|
+
".wav",
|
|
247
|
+
".ogg",
|
|
248
|
+
".m4a"
|
|
249
|
+
];
|
|
250
|
+
var formatted = async (messages) => messages.length ? await formatMessages(messages, { kind: "error", color: false }) : [];
|
|
251
|
+
function reporter(onBuilt, dir, output = buildDir(dir)) {
|
|
252
|
+
let version = 0;
|
|
253
|
+
return {
|
|
254
|
+
name: "report",
|
|
255
|
+
setup(build2) {
|
|
256
|
+
build2.onEnd(async (result) => {
|
|
257
|
+
const errors = await formatted(result.errors);
|
|
258
|
+
version++;
|
|
259
|
+
if (!errors.length) {
|
|
260
|
+
await (0, import_promises2.copyFile)((0, import_node_path2.join)(output, "film.js"), (0, import_node_path2.join)(output, `film-${version}.js`));
|
|
261
|
+
const faces2 = await motionFaces(dir);
|
|
262
|
+
for (const reason of faces2.skipped) console.warn(`A motion's face was left out: ${reason}`);
|
|
263
|
+
await (0, import_promises2.writeFile)((0, import_node_path2.join)(output, FACES), faces2.css);
|
|
264
|
+
}
|
|
265
|
+
onBuilt({ ok: errors.length === 0, version, errors });
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
var ASSET_LOADERS = Object.fromEntries(ASSETS.map((ext) => [ext, "file"]));
|
|
271
|
+
function filmOptions(dir, output, plugins = []) {
|
|
272
|
+
return {
|
|
273
|
+
absWorkingDir: dir,
|
|
274
|
+
entryPoints: [FILM],
|
|
275
|
+
outfile: (0, import_node_path2.join)(output, "film.js"),
|
|
276
|
+
bundle: true,
|
|
277
|
+
format: "iife",
|
|
278
|
+
globalName: "__omsFilm",
|
|
279
|
+
platform: "browser",
|
|
280
|
+
target: "chrome130",
|
|
281
|
+
jsx: "automatic",
|
|
282
|
+
external: PROVIDED,
|
|
283
|
+
loader: ASSET_LOADERS,
|
|
284
|
+
publicPath: "build",
|
|
285
|
+
sourcemap: "inline",
|
|
286
|
+
logLevel: "silent",
|
|
287
|
+
plugins: [studioThree, ...plugins]
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
async function buildFilmOnce(dir, output) {
|
|
291
|
+
let built;
|
|
292
|
+
const failed = (error) => ({ ok: false, version: 1, errors: [error instanceof Error ? error.message : String(error)] });
|
|
293
|
+
try {
|
|
294
|
+
await build(filmOptions(dir, output, [reporter((result) => {
|
|
295
|
+
built = result;
|
|
296
|
+
}, dir, output)]));
|
|
297
|
+
} catch (error) {
|
|
298
|
+
return built ?? failed(error);
|
|
299
|
+
}
|
|
300
|
+
return built ?? failed(new Error("The film build reported no result."));
|
|
301
|
+
}
|
|
302
|
+
var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
303
|
+
function sourceAt(map, line, column) {
|
|
304
|
+
const lines = map.mappings.split(";");
|
|
305
|
+
let source = 0;
|
|
306
|
+
let sourceLine = 0;
|
|
307
|
+
let sourceColumn = 0;
|
|
308
|
+
let found = null;
|
|
309
|
+
for (let l = 0; l < lines.length && l < line; l++) {
|
|
310
|
+
let generated = 0;
|
|
311
|
+
for (const segment of lines[l].split(",")) {
|
|
312
|
+
if (!segment) continue;
|
|
313
|
+
const fields = [];
|
|
314
|
+
let value = 0;
|
|
315
|
+
let shift = 0;
|
|
316
|
+
for (const char of segment) {
|
|
317
|
+
const digit = BASE64.indexOf(char);
|
|
318
|
+
value += (digit & 31) << shift;
|
|
319
|
+
if (digit & 32) shift += 5;
|
|
320
|
+
else {
|
|
321
|
+
fields.push(value & 1 ? -(value >> 1) : value >> 1);
|
|
322
|
+
value = 0;
|
|
323
|
+
shift = 0;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
generated += fields[0] ?? 0;
|
|
327
|
+
if (fields.length < 4) continue;
|
|
328
|
+
source += fields[1];
|
|
329
|
+
sourceLine += fields[2];
|
|
330
|
+
sourceColumn += fields[3];
|
|
331
|
+
if (l === line - 1 && generated <= column - 1) found = { source: map.sources[source] ?? "?", line: sourceLine + 1, column: sourceColumn + 1 };
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return found;
|
|
335
|
+
}
|
|
336
|
+
async function located(text, bundle, dir) {
|
|
337
|
+
const [first, ...stack] = text.split("\n");
|
|
338
|
+
const frame = stack.join("\n").match(/film(?:-\d+)?\.js:(\d+):(\d+)/);
|
|
339
|
+
if (!frame) return text.includes("\n at ") ? first : text;
|
|
340
|
+
try {
|
|
341
|
+
const code = await (0, import_promises2.readFile)(bundle, "utf8");
|
|
342
|
+
const inline = /\/\/# sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+)\s*$/.exec(code);
|
|
343
|
+
if (!inline) return first;
|
|
344
|
+
const at = sourceAt(JSON.parse(Buffer.from(inline[1], "base64").toString("utf8")), Number(frame[1]), Number(frame[2]));
|
|
345
|
+
if (!at) return first;
|
|
346
|
+
const file = (0, import_node_path2.resolve)((0, import_node_path2.dirname)(bundle), at.source);
|
|
347
|
+
const source = (0, import_node_path2.relative)(await (0, import_promises2.realpath)(dir), await (0, import_promises2.realpath)(file).catch(() => file)).split(import_node_path2.sep).join("/");
|
|
348
|
+
return `${first} (at ${source}:${at.line}:${at.column})`;
|
|
349
|
+
} catch {
|
|
350
|
+
return first;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ../desktop/src/main/film/mix.ts
|
|
355
|
+
var import_node_child_process = require("node:child_process");
|
|
356
|
+
var import_node_fs2 = require("node:fs");
|
|
357
|
+
var import_node_path4 = require("node:path");
|
|
358
|
+
|
|
359
|
+
// ../desktop/src/shared/sound.ts
|
|
360
|
+
function soundPlace(src) {
|
|
361
|
+
const path = src.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
|
|
362
|
+
if (!path || path.startsWith("/") || /^[a-z][a-z0-9+.-]*:/i.test(path) || path.split("/").includes("..")) return null;
|
|
363
|
+
return path.startsWith("build/") ? { root: "build", path: path.slice("build/".length) } : { root: "project", path };
|
|
364
|
+
}
|
|
365
|
+
var soundRegion = (sound, fileSeconds) => Math.max(0, sound.dur ?? fileSeconds - sound.trim);
|
|
366
|
+
var soundSpan = (sound, fileSeconds) => Math.max(0, Math.min(sound.loop ? Infinity : soundRegion(sound, fileSeconds), sound.until - sound.at));
|
|
367
|
+
function soundFades(sound, span) {
|
|
368
|
+
const total = sound.fadeIn + sound.fadeOut;
|
|
369
|
+
const fit = total > span && total > 0 ? span / total : 1;
|
|
370
|
+
return { fadeIn: sound.fadeIn * fit, fadeOut: sound.fadeOut * fit };
|
|
371
|
+
}
|
|
372
|
+
var decibels = (db) => 10 ** (db / 20);
|
|
373
|
+
var DUCK = { attack: 0.12, release: 0.5 };
|
|
374
|
+
function ducked(spans, t) {
|
|
375
|
+
let level = 0;
|
|
376
|
+
for (const { at, until } of spans) {
|
|
377
|
+
const rise = Math.min(1, Math.max(0, (t - (at - DUCK.attack)) / DUCK.attack));
|
|
378
|
+
const fall = Math.min(1, Math.max(0, (until + DUCK.release - t) / DUCK.release));
|
|
379
|
+
level = Math.max(level, Math.min(rise, fall));
|
|
380
|
+
}
|
|
381
|
+
return level;
|
|
382
|
+
}
|
|
383
|
+
var spokenSound = (line) => ({
|
|
384
|
+
src: line.src,
|
|
385
|
+
at: line.at,
|
|
386
|
+
dur: null,
|
|
387
|
+
until: line.until,
|
|
388
|
+
trim: 0,
|
|
389
|
+
loop: false,
|
|
390
|
+
volume: 0,
|
|
391
|
+
fadeIn: 0,
|
|
392
|
+
fadeOut: 0
|
|
393
|
+
});
|
|
394
|
+
|
|
395
|
+
// ../desktop/src/main/film/serve.ts
|
|
396
|
+
var import_promises3 = require("node:fs/promises");
|
|
397
|
+
var import_node_path3 = require("node:path");
|
|
398
|
+
var filmPolicy = (origin) => [
|
|
399
|
+
"default-src 'none'",
|
|
400
|
+
// Scripts come only from the film's host: the page carries none inline (the Studio's own
|
|
401
|
+
// calls into a render page go through executeJavaScript, which the policy does not see).
|
|
402
|
+
`script-src ${origin}`,
|
|
403
|
+
`style-src ${origin} 'unsafe-inline'`,
|
|
404
|
+
`img-src ${origin} data: blob:`,
|
|
405
|
+
`font-src ${origin} data:`,
|
|
406
|
+
`media-src ${origin} data: blob:`,
|
|
407
|
+
// A film may fetch its own files; nothing beyond its host.
|
|
408
|
+
`connect-src ${origin}`,
|
|
409
|
+
"form-action 'none'",
|
|
410
|
+
"base-uri 'none'"
|
|
411
|
+
].join("; ");
|
|
412
|
+
var PAGE = `<!doctype html>
|
|
413
|
+
<html><head><meta charset="utf-8"><title>Preview</title>
|
|
414
|
+
<style>html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent}</style>
|
|
415
|
+
</head><body><div id="root"></div><script src="studio/core.js"></script><script src="studio/pick.js"></script></body></html>`;
|
|
416
|
+
var TYPES = {
|
|
417
|
+
".js": "text/javascript",
|
|
418
|
+
".css": "text/css",
|
|
419
|
+
".json": "application/json",
|
|
420
|
+
".png": "image/png",
|
|
421
|
+
".jpg": "image/jpeg",
|
|
422
|
+
".jpeg": "image/jpeg",
|
|
423
|
+
".gif": "image/gif",
|
|
424
|
+
".webp": "image/webp",
|
|
425
|
+
".avif": "image/avif",
|
|
426
|
+
".svg": "image/svg+xml",
|
|
427
|
+
".woff": "font/woff",
|
|
428
|
+
".woff2": "font/woff2",
|
|
429
|
+
".ttf": "font/ttf",
|
|
430
|
+
".otf": "font/otf",
|
|
431
|
+
".mp4": "video/mp4",
|
|
432
|
+
".webm": "video/webm",
|
|
433
|
+
".mp3": "audio/mpeg",
|
|
434
|
+
".wav": "audio/wav",
|
|
435
|
+
".ogg": "audio/ogg",
|
|
436
|
+
".m4a": "audio/mp4"
|
|
437
|
+
};
|
|
438
|
+
function within(root, urlPath) {
|
|
439
|
+
const relative3 = (0, import_node_path3.normalize)(decodeURIComponent(urlPath)).replace(/^[/\\]+/, "");
|
|
440
|
+
if (relative3 === "" || relative3.split(/[/\\]/).includes("..")) return null;
|
|
441
|
+
const path = (0, import_node_path3.join)(root, relative3);
|
|
442
|
+
return path.startsWith(root + import_node_path3.sep) ? path : null;
|
|
443
|
+
}
|
|
444
|
+
async function safePreviewFile(root, urlPath, project = false) {
|
|
445
|
+
const file = within(root, urlPath);
|
|
446
|
+
if (!file) return null;
|
|
447
|
+
const actualRoot = await (0, import_promises3.realpath)(root);
|
|
448
|
+
const actual = await (0, import_promises3.realpath)(file);
|
|
449
|
+
const path = (0, import_node_path3.relative)(actualRoot, actual);
|
|
450
|
+
if (path === ".." || path.startsWith(`..${import_node_path3.sep}`) || !actual.startsWith(actualRoot + import_node_path3.sep)) return null;
|
|
451
|
+
const hidden = (value) => value.toLowerCase().split(/[/\\]/).some((part) => part === ".motion-studio" || part === ".git" || part === "node_modules");
|
|
452
|
+
if (project && (hidden(path) || hidden(decodeURIComponent(urlPath)))) return null;
|
|
453
|
+
return actual;
|
|
454
|
+
}
|
|
455
|
+
async function filmFile(dir, output, studio2, pathname) {
|
|
456
|
+
if (pathname === "/" || pathname === "/index.html") return { body: PAGE, type: "text/html" };
|
|
457
|
+
const roots = [
|
|
458
|
+
["/studio/", studio2],
|
|
459
|
+
["/build/", output],
|
|
460
|
+
["/reels/", (0, import_node_path3.join)(dir, STATE_DIR, "reels")],
|
|
461
|
+
["/project/", dir]
|
|
462
|
+
];
|
|
463
|
+
try {
|
|
464
|
+
for (const [prefix, root] of roots) {
|
|
465
|
+
if (!pathname.startsWith(prefix)) continue;
|
|
466
|
+
const file = await safePreviewFile(root, pathname.slice(prefix.length), prefix === "/project/");
|
|
467
|
+
if (file) return { body: await (0, import_promises3.readFile)(file), type: TYPES[(0, import_node_path3.extname)(file).toLowerCase()] ?? "application/octet-stream" };
|
|
468
|
+
}
|
|
469
|
+
} catch (error) {
|
|
470
|
+
if (error.code !== "ENOENT") throw error;
|
|
471
|
+
}
|
|
472
|
+
return null;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// ../desktop/src/main/film/mix.ts
|
|
476
|
+
var RATE = 48e3;
|
|
477
|
+
var CEILING = 0.891;
|
|
478
|
+
async function soundFile(dir, src, output = buildDir(dir)) {
|
|
479
|
+
const place = soundPlace(src);
|
|
480
|
+
const file = place && await safePreviewFile(place.root === "build" ? output : dir, place.path, place.root === "project").catch(() => null);
|
|
481
|
+
if (!file) throw new Error(`<Sound src="${src}">: no such file in the project. A sound's src is a path in the project, as media/music.mp3.`);
|
|
482
|
+
return file;
|
|
483
|
+
}
|
|
484
|
+
function mediaSeconds(ffmpeg, file) {
|
|
485
|
+
return new Promise(
|
|
486
|
+
(done, fail) => (
|
|
487
|
+
// ffmpeg with an input and no output says what the input is, and exits 1.
|
|
488
|
+
(0, import_node_child_process.execFile)(ffmpeg, ["-hide_banner", "-i", file], { timeout: 3e4, windowsHide: true }, (_error, _stdout, stderr2) => {
|
|
489
|
+
const match = /Duration: (\d+):(\d+):(\d+(?:\.\d+)?)/.exec(String(stderr2));
|
|
490
|
+
if (!match) return fail(new Error(`${file} is no sound ffmpeg can read.`));
|
|
491
|
+
done(Number(match[1]) * 3600 + Number(match[2]) * 60 + Number(match[3]));
|
|
492
|
+
})
|
|
493
|
+
)
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
var n = (value) => Number(value.toFixed(6)).toString();
|
|
497
|
+
var MIX_FORMAT = ["-f", "f32le", "-ar", String(RATE), "-ac", "2"];
|
|
498
|
+
var mixFinish = (seconds) => `alimiter=limit=${CEILING}:level=false:latency=true,apad,atrim=end=${n(seconds)},asetpts=PTS-STARTPTS`;
|
|
499
|
+
var run = (ffmpeg, args) => new Promise(
|
|
500
|
+
(done, fail) => (0, import_node_child_process.execFile)(
|
|
501
|
+
ffmpeg,
|
|
502
|
+
["-hide_banner", "-loglevel", "error", ...args],
|
|
503
|
+
{ timeout: 6e5, windowsHide: true, maxBuffer: 16 * 1024 * 1024 },
|
|
504
|
+
(error, _out, stderr2) => error ? fail(new Error(`ffmpeg could not decode a sound: ${String(stderr2).trim().split("\n").slice(-2).join(" / ") || error.message}`)) : done()
|
|
505
|
+
)
|
|
506
|
+
);
|
|
507
|
+
function mono(ffmpeg, file) {
|
|
508
|
+
return new Promise(
|
|
509
|
+
(done) => (
|
|
510
|
+
// ffmpeg with an input and no output says what the input is, and exits 1.
|
|
511
|
+
(0, import_node_child_process.execFile)(
|
|
512
|
+
ffmpeg,
|
|
513
|
+
["-hide_banner", "-i", file],
|
|
514
|
+
{ timeout: 3e4, windowsHide: true },
|
|
515
|
+
(_error, _stdout, stderr2) => done(/Audio: [^\n]*?, (mono|1 channels)\b/.test(String(stderr2)))
|
|
516
|
+
)
|
|
517
|
+
)
|
|
518
|
+
);
|
|
519
|
+
}
|
|
520
|
+
var BLOCK_SECONDS = 30;
|
|
521
|
+
async function mixSounds(sounds, seconds, ffmpeg, work, narration = []) {
|
|
522
|
+
const heard = sounds.filter(({ sound, fileSeconds }) => soundSpan(sound, fileSeconds) > 0 && sound.at < seconds);
|
|
523
|
+
if (!heard.length) return null;
|
|
524
|
+
const decoded = /* @__PURE__ */ new Map();
|
|
525
|
+
for (const { file } of heard) {
|
|
526
|
+
if (decoded.has(file)) continue;
|
|
527
|
+
const raw = (0, import_node_path4.join)(work, `sound-${decoded.size}.f32`);
|
|
528
|
+
const stereo = await mono(ffmpeg, file) ? "pan=stereo|c0=c0|c1=c0" : "aformat=sample_fmts=fltp:channel_layouts=stereo";
|
|
529
|
+
await run(ffmpeg, ["-y", "-i", file, "-af", `aresample=${RATE},${stereo}`, ...MIX_FORMAT, raw]);
|
|
530
|
+
decoded.set(file, raw);
|
|
531
|
+
}
|
|
532
|
+
const total = Math.round(seconds * RATE);
|
|
533
|
+
const out = (0, import_node_path4.join)(work, "mix.f32");
|
|
534
|
+
const handles = [];
|
|
535
|
+
try {
|
|
536
|
+
const opened = new Map([...decoded].map(([file, raw]) => {
|
|
537
|
+
const fd = (0, import_node_fs2.openSync)(raw, "r");
|
|
538
|
+
handles.push(fd);
|
|
539
|
+
return [file, { fd, frames: Math.floor((0, import_node_fs2.fstatSync)(fd).size / 8) }];
|
|
540
|
+
}));
|
|
541
|
+
const placed = heard.map(({ sound, file, fileSeconds }) => {
|
|
542
|
+
const span = soundSpan(sound, fileSeconds);
|
|
543
|
+
const { fadeIn, fadeOut } = soundFades(sound, span);
|
|
544
|
+
const source = opened.get(file);
|
|
545
|
+
const trim = Math.round(sound.trim * RATE);
|
|
546
|
+
const region = Math.max(1, Math.min(Math.round(soundRegion(sound, fileSeconds) * RATE), source.frames - trim));
|
|
547
|
+
const at = Math.round(sound.at * RATE);
|
|
548
|
+
return { sound, span, fadeIn, fadeOut, level: decibels(sound.volume), ...source, trim, region, at, end: Math.min(total, at + Math.round(span * RATE)) };
|
|
549
|
+
});
|
|
550
|
+
const target = (0, import_node_fs2.openSync)(out, "w");
|
|
551
|
+
handles.push(target);
|
|
552
|
+
const block = BLOCK_SECONDS * RATE;
|
|
553
|
+
for (let start2 = 0; start2 < total; start2 += block) {
|
|
554
|
+
const count = Math.min(block, total - start2);
|
|
555
|
+
const mix = new Float32Array(count * 2);
|
|
556
|
+
for (const p of placed) {
|
|
557
|
+
const from = Math.max(start2, p.at);
|
|
558
|
+
const to = Math.min(start2 + count, p.end);
|
|
559
|
+
if (to <= from || p.frames <= p.trim) continue;
|
|
560
|
+
const samples = new Float32Array((to - from) * 2);
|
|
561
|
+
const bytes = new Uint8Array(samples.buffer);
|
|
562
|
+
for (let i = from; i < to; ) {
|
|
563
|
+
const k = i - p.at;
|
|
564
|
+
const offset = p.sound.loop ? k % p.region : k;
|
|
565
|
+
if (offset >= p.region) break;
|
|
566
|
+
const frames = Math.min(to - i, p.region - offset);
|
|
567
|
+
(0, import_node_fs2.readSync)(p.fd, bytes, (i - from) * 8, frames * 8, (p.trim + offset) * 8);
|
|
568
|
+
i += frames;
|
|
569
|
+
}
|
|
570
|
+
const duck = p.sound.duck && narration.length ? 1 - decibels(-p.sound.duck) : 0;
|
|
571
|
+
for (let i = from; i < to; i++) {
|
|
572
|
+
const u = (i - p.at) / RATE;
|
|
573
|
+
const rise = p.fadeIn > 0 ? Math.min(1, u / p.fadeIn) : 1;
|
|
574
|
+
const fall = p.fadeOut > 0 ? Math.min(1, (p.span - u) / p.fadeOut) : 1;
|
|
575
|
+
let gain = p.level * Math.max(0, Math.min(rise, fall));
|
|
576
|
+
if (duck) gain *= 1 - duck * ducked(narration, i / RATE);
|
|
577
|
+
const j = 2 * (i - from);
|
|
578
|
+
const d = 2 * (i - start2);
|
|
579
|
+
mix[d] = mix[d] + samples[j] * gain;
|
|
580
|
+
mix[d + 1] = mix[d + 1] + samples[j + 1] * gain;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
(0, import_node_fs2.writeSync)(target, new Uint8Array(mix.buffer));
|
|
584
|
+
}
|
|
585
|
+
} finally {
|
|
586
|
+
for (const fd of handles) (0, import_node_fs2.closeSync)(fd);
|
|
587
|
+
}
|
|
588
|
+
return out;
|
|
589
|
+
}
|
|
590
|
+
async function soundInputs(dir, ffmpeg, sounds, output = buildDir(dir)) {
|
|
591
|
+
return Promise.all(
|
|
592
|
+
sounds.map(async (sound) => {
|
|
593
|
+
const file = await soundFile(dir, sound.src, output);
|
|
594
|
+
return { sound, file, fileSeconds: await mediaSeconds(ffmpeg, file) };
|
|
595
|
+
})
|
|
596
|
+
);
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// ../desktop/src/main/film/review.ts
|
|
600
|
+
async function reviewBuild(build2, open, signal, where) {
|
|
601
|
+
const told = async (error) => {
|
|
602
|
+
const text = error instanceof Error ? error.message : String(error);
|
|
603
|
+
return where ? located(text, where.bundle, where.dir) : text;
|
|
604
|
+
};
|
|
605
|
+
const review = { version: build2?.version ?? 0, checkedFrames: 0, issues: [] };
|
|
606
|
+
if (!build2?.ok) {
|
|
607
|
+
review.issues = (build2?.errors.length ? build2.errors : ["The film is not ready yet."]).map((text, i) => ({
|
|
608
|
+
id: `build-${i}`,
|
|
609
|
+
kind: "build",
|
|
610
|
+
severity: "error",
|
|
611
|
+
text
|
|
612
|
+
}));
|
|
613
|
+
return review;
|
|
614
|
+
}
|
|
615
|
+
let stage;
|
|
616
|
+
try {
|
|
617
|
+
signal?.throwIfAborted();
|
|
618
|
+
stage = await open(build2.version);
|
|
619
|
+
const film = stage.film;
|
|
620
|
+
review.film = film;
|
|
621
|
+
if (!Number.isInteger(film.width) || !Number.isInteger(film.height) || film.width % 2 || film.height % 2)
|
|
622
|
+
review.issues.push({
|
|
623
|
+
id: "export-size",
|
|
624
|
+
kind: "export",
|
|
625
|
+
severity: "error",
|
|
626
|
+
text: "MP4 needs even, whole-pixel width and height. Ask the agent to adjust the film size."
|
|
627
|
+
});
|
|
628
|
+
for (const scene of film.scenes)
|
|
629
|
+
for (const layer of scene.layers) {
|
|
630
|
+
if (layer.x < 0 || layer.y < 0 || layer.x + layer.w > film.width || layer.y + layer.h > film.height)
|
|
631
|
+
review.issues.push({
|
|
632
|
+
id: `bounds-${scene.id}-${layer.id}`,
|
|
633
|
+
kind: "layout",
|
|
634
|
+
severity: "warning",
|
|
635
|
+
text: `Layer \u201C${layer.id}\u201D extends beyond the frame. This may be intentional.`,
|
|
636
|
+
time: scene.start + scene.duration / 2,
|
|
637
|
+
scene: scene.id
|
|
638
|
+
});
|
|
639
|
+
}
|
|
640
|
+
for (const scene of film.scenes) {
|
|
641
|
+
const placed = scene.layers.filter((l) => !(l.x <= 0 && l.y <= 0 && l.x + l.w >= film.width && l.y + l.h >= film.height));
|
|
642
|
+
for (const [i, a] of placed.entries())
|
|
643
|
+
for (const b of placed.slice(i + 1)) {
|
|
644
|
+
const w = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x);
|
|
645
|
+
const h = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y);
|
|
646
|
+
if (w <= 0 || h <= 0) continue;
|
|
647
|
+
review.issues.push({
|
|
648
|
+
id: `overlap-${scene.id}-${a.id}-${b.id}`,
|
|
649
|
+
kind: "layout",
|
|
650
|
+
severity: "warning",
|
|
651
|
+
text: `Layers \u201C${a.id}\u201D and \u201C${b.id}\u201D in scene \u201C${scene.id}\u201D overlap by ${Math.round(w)}\xD7${Math.round(h)} px at x ${Math.round(Math.max(a.x, b.x))}, y ${Math.round(Math.max(a.y, b.y))}. Give each its own part of the frame, or draw what overlaps on purpose in one layer.`,
|
|
652
|
+
time: scene.start + scene.duration / 2,
|
|
653
|
+
scene: scene.id
|
|
654
|
+
});
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
const lineTimes = film.scenes.flatMap((s) => s.lines.map((line) => line.start + 0.85 * (line.end - line.start)));
|
|
658
|
+
const entered = new Map(film.scenes.map((s) => [s.start + Math.min(0.5, s.duration / 4), s]));
|
|
659
|
+
const times = [.../* @__PURE__ */ new Set([0, ...entered.keys(), ...film.scenes.map((s) => s.start + s.duration / 2), ...lineTimes, Math.max(0, film.seconds - 1 / film.fps)])].filter((time) => time >= 0 && time < film.seconds).sort((a, b) => a - b);
|
|
660
|
+
const WHOLE = "";
|
|
661
|
+
const GENERIC = /* @__PURE__ */ new Set(["serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-serif", "ui-sans-serif", "ui-monospace", "ui-rounded", "math", "emoji", "fangsong"]);
|
|
662
|
+
const sceneAt = (time) => film.scenes.find((s) => time >= s.start && time < s.start + s.duration)?.id;
|
|
663
|
+
const said = /* @__PURE__ */ new Set();
|
|
664
|
+
const faces2 = /* @__PURE__ */ new Map();
|
|
665
|
+
for (const time of times) {
|
|
666
|
+
signal?.throwIfAborted();
|
|
667
|
+
try {
|
|
668
|
+
await stage.png(time);
|
|
669
|
+
review.checkedFrames++;
|
|
670
|
+
const seen = await stage.inspect();
|
|
671
|
+
const opening = entered.get(time);
|
|
672
|
+
if (opening && opening.layers.length && seen.shown && !opening.layers.some((layer) => seen.shown.includes(layer.id)))
|
|
673
|
+
review.issues.push({
|
|
674
|
+
id: `empty-${opening.id}`,
|
|
675
|
+
kind: "layout",
|
|
676
|
+
severity: "warning",
|
|
677
|
+
text: `Scene \u201C${opening.id}\u201D still shows none of its layers at ${time.toFixed(2)} s, ${(time - opening.start).toFixed(2)} s after it opens: the film's ground alone. Have its picture in by then, and bring in later only what its lines add.`,
|
|
678
|
+
time,
|
|
679
|
+
scene: opening.id
|
|
680
|
+
});
|
|
681
|
+
for (const layer of new Set(seen.outside.map((o) => o.layer))) {
|
|
682
|
+
if (said.has(`outside|${layer}`)) continue;
|
|
683
|
+
said.add(`outside|${layer}`);
|
|
684
|
+
const texts = seen.outside.filter((o) => o.layer === layer);
|
|
685
|
+
const edges = [...new Set(texts.flatMap((o) => o.edges))];
|
|
686
|
+
const more = texts.length > 1 ? ` and ${texts.length - 1} more` : "";
|
|
687
|
+
review.issues.push({
|
|
688
|
+
id: `outside-${layer}`,
|
|
689
|
+
kind: "layout",
|
|
690
|
+
severity: "warning",
|
|
691
|
+
text: `Text in layer \u201C${layer}\u201D (\u201C${texts[0].text}\u201D${more}) runs past the frame's ${edges.join(" and ")} edge at ${time.toFixed(2)} s. A component's coordinates are its layer's, not the frame's.`,
|
|
692
|
+
time,
|
|
693
|
+
scene: sceneAt(time)
|
|
694
|
+
});
|
|
695
|
+
}
|
|
696
|
+
for (const { layer, family, chars } of seen.unloaded) {
|
|
697
|
+
const key = family.toLowerCase();
|
|
698
|
+
const face = faces2.get(key) ?? { family, layers: /* @__PURE__ */ new Map(), time };
|
|
699
|
+
faces2.set(key, face);
|
|
700
|
+
const drawn = face.layers.get(layer) ?? /* @__PURE__ */ new Set();
|
|
701
|
+
face.layers.set(layer, drawn);
|
|
702
|
+
if (!chars) drawn.add(WHOLE);
|
|
703
|
+
for (const char of chars) drawn.add(char);
|
|
704
|
+
}
|
|
705
|
+
} catch (error) {
|
|
706
|
+
if (signal?.aborted) throw error;
|
|
707
|
+
review.issues.push({
|
|
708
|
+
id: "drawing",
|
|
709
|
+
kind: "runtime",
|
|
710
|
+
severity: "error",
|
|
711
|
+
text: await told(error),
|
|
712
|
+
time,
|
|
713
|
+
scene: film.scenes.find((s) => time >= s.start && time < s.start + s.duration)?.id
|
|
714
|
+
});
|
|
715
|
+
break;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
for (const [key, { family, layers, time }] of faces2) {
|
|
719
|
+
const where2 = GENERIC.has(key) ? `this machine's own ${family} face` : `\u201C${family}\u201D, which neither the film nor its motion loads, so to this machine's fallback`;
|
|
720
|
+
const place = (layer) => layer === "captions" ? "the captions" : `layer \u201C${layer}\u201D`;
|
|
721
|
+
const lacking2 = [...layers].filter(([, drawn]) => [...drawn].some((char) => char !== WHOLE)).map(([layer, drawn]) => {
|
|
722
|
+
const chars = [...drawn].filter((char) => char !== WHOLE);
|
|
723
|
+
return `${place(layer)} (\u201C${chars.slice(0, 40).join("")}\u201D${chars.length > 40 ? ` and ${chars.length - 40} more` : ""})`;
|
|
724
|
+
});
|
|
725
|
+
const whole = [...layers].filter(([, drawn]) => drawn.has(WHOLE)).map(([layer]) => place(layer));
|
|
726
|
+
const said2 = [
|
|
727
|
+
...lacking2.length ? [`Characters the faces it loads lack fall to ${where2}: ${lacking2.join(", ")}.`] : [],
|
|
728
|
+
...whole.length ? [`${whole.join(", ").replace(/^./, (c) => c.toUpperCase())} ${whole.length > 1 || whole[0] === "the captions" ? "set" : "sets"} text in ${where2}.`] : []
|
|
729
|
+
];
|
|
730
|
+
review.issues.push({
|
|
731
|
+
id: `face-${key}`,
|
|
732
|
+
kind: "layout",
|
|
733
|
+
severity: "warning",
|
|
734
|
+
text: `${said2.join(" ")} Frames differ between machines. Declare a face that has them from the project's files, or use one the motion ships.`,
|
|
735
|
+
time,
|
|
736
|
+
scene: sceneAt(time)
|
|
737
|
+
});
|
|
738
|
+
}
|
|
739
|
+
} catch (error) {
|
|
740
|
+
if (signal?.aborted) throw error;
|
|
741
|
+
review.issues.push({ id: "preview", kind: "runtime", severity: "error", text: await told(error) });
|
|
742
|
+
} finally {
|
|
743
|
+
await stage?.close();
|
|
744
|
+
}
|
|
745
|
+
return review;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// ../desktop/src/main/film/capture.ts
|
|
749
|
+
var import_node_child_process2 = require("node:child_process");
|
|
750
|
+
var import_node_crypto = require("node:crypto");
|
|
751
|
+
var import_promises4 = require("node:fs/promises");
|
|
752
|
+
var import_node_path5 = require("node:path");
|
|
753
|
+
|
|
754
|
+
// ../desktop/src/main/film/captions.ts
|
|
755
|
+
function srtTime(seconds) {
|
|
756
|
+
const ms = Math.max(0, Math.round(seconds * 1e3));
|
|
757
|
+
const pad = (n2, width = 2) => String(n2).padStart(width, "0");
|
|
758
|
+
return `${pad(Math.floor(ms / 36e5))}:${pad(Math.floor(ms / 6e4) % 60)}:${pad(Math.floor(ms / 1e3) % 60)},${pad(ms % 1e3, 3)}`;
|
|
759
|
+
}
|
|
760
|
+
function srt(film) {
|
|
761
|
+
const lines = film.scenes.flatMap((scene) => scene.lines).filter((line) => line.text.trim() && line.end > line.start);
|
|
762
|
+
if (!lines.length) return null;
|
|
763
|
+
return lines.map((line, i) => `${i + 1}
|
|
764
|
+
${srtTime(line.start)} --> ${srtTime(line.end)}
|
|
765
|
+
${line.text.trim().replace(/\r?\n+/g, "\n")}
|
|
766
|
+
`).join("\n");
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// ../desktop/src/main/film/capture.ts
|
|
770
|
+
var VIDEO = [
|
|
771
|
+
"-vf",
|
|
772
|
+
"scale=out_color_matrix=bt709:out_range=tv,format=yuv420p",
|
|
773
|
+
"-colorspace",
|
|
774
|
+
"bt709",
|
|
775
|
+
"-color_primaries",
|
|
776
|
+
"bt709",
|
|
777
|
+
"-color_trc",
|
|
778
|
+
"bt709",
|
|
779
|
+
"-color_range",
|
|
780
|
+
"tv",
|
|
781
|
+
"-c:v",
|
|
782
|
+
"libx264",
|
|
783
|
+
"-preset",
|
|
784
|
+
"medium",
|
|
785
|
+
"-crf",
|
|
786
|
+
"20",
|
|
787
|
+
"-profile:v",
|
|
788
|
+
"high",
|
|
789
|
+
"-level:v",
|
|
790
|
+
"4.1"
|
|
791
|
+
];
|
|
792
|
+
var write = (stream, chunk) => new Promise((done, fail) => {
|
|
793
|
+
stream.write(chunk, (error) => error ? fail(error) : done());
|
|
794
|
+
});
|
|
795
|
+
var subtitlesFile = (file) => `${file.replace(/\.mp4$/i, "")}.srt`;
|
|
796
|
+
var SEGMENT_FRAMES = 3e3;
|
|
797
|
+
async function segmentsName(output, version, film, frames) {
|
|
798
|
+
const hash = (0, import_node_crypto.createHash)("sha256").update(JSON.stringify([VIDEO, film.width, film.height, film.fps, frames]));
|
|
799
|
+
const files = (await (0, import_promises4.readdir)(output, { withFileTypes: true })).filter((entry) => entry.isFile() && (!/^film-\d+\.js$/.test(entry.name) || entry.name === `film-${version}.js`)).map((entry) => entry.name).sort();
|
|
800
|
+
for (const name of files) hash.update(`${name === `film-${version}.js` ? "film-n.js" : name}\0`).update(await (0, import_promises4.readFile)((0, import_node_path5.join)(output, name)));
|
|
801
|
+
return hash.digest("hex").slice(0, 16);
|
|
802
|
+
}
|
|
803
|
+
var run2 = (ffmpeg, args) => new Promise((done, fail) => {
|
|
804
|
+
const child = (0, import_node_child_process2.spawn)(ffmpeg, ["-y", "-loglevel", "error", ...args], { stdio: ["ignore", "ignore", "pipe"] });
|
|
805
|
+
let said = "";
|
|
806
|
+
child.stderr.on("data", (data) => said = (said + data).slice(-4e3));
|
|
807
|
+
child.on("error", fail);
|
|
808
|
+
child.on("close", (code) => code === 0 ? done() : fail(new Error(`ffmpeg exited ${code}: ${said.trim().split("\n").slice(-3).join(" / ")}`)));
|
|
809
|
+
});
|
|
810
|
+
async function exportFrames(dir, version, file, onProgress, signal, open, ffmpeg, { output = buildDir(dir), stages = 1, resume, segmentFrames = SEGMENT_FRAMES } = {}) {
|
|
811
|
+
const stage = await open(version);
|
|
812
|
+
const others = [];
|
|
813
|
+
const partial = `${file}.partial.mp4`;
|
|
814
|
+
const partialSubtitles = `${file}.partial.srt`;
|
|
815
|
+
const { film } = stage;
|
|
816
|
+
const frames = Math.round(film.seconds * film.fps);
|
|
817
|
+
const work = resume ? (0, import_node_path5.join)(resume, await segmentsName(output, version, film, frames)) : `${file}.partial-segments`;
|
|
818
|
+
let whole = false;
|
|
819
|
+
try {
|
|
820
|
+
await (0, import_promises4.mkdir)(work, { recursive: true });
|
|
821
|
+
const plan = [];
|
|
822
|
+
for (let s = 0; s < frames; s += segmentFrames) plan.push([s, Math.min(frames, s + segmentFrames)]);
|
|
823
|
+
const segment = ([s, e]) => (0, import_node_path5.join)(work, `${String(s).padStart(7, "0")}-${String(e).padStart(7, "0")}.mp4`);
|
|
824
|
+
const kept = new Set(await (0, import_promises4.readdir)(work));
|
|
825
|
+
let done = 0;
|
|
826
|
+
for (const [s, e] of plan) {
|
|
827
|
+
if (signal.aborted) throw new Error("The export was cancelled.");
|
|
828
|
+
const name = segment([s, e]);
|
|
829
|
+
if (!kept.has(name.slice(work.length + 1))) {
|
|
830
|
+
const wanted = Math.min(stages, e - s) - 1 - others.length;
|
|
831
|
+
if (wanted > 0) {
|
|
832
|
+
const opening = await Promise.allSettled(Array.from({ length: wanted }, () => open(version)));
|
|
833
|
+
for (const opened of opening) if (opened.status === "fulfilled") others.push(opened.value);
|
|
834
|
+
const refused = opening.find((opened) => opened.status === "rejected");
|
|
835
|
+
if (refused) throw refused.reason;
|
|
836
|
+
}
|
|
837
|
+
await drawSegment(
|
|
838
|
+
[stage, ...others].slice(0, Math.max(1, Math.min(stages, e - s))),
|
|
839
|
+
film,
|
|
840
|
+
s,
|
|
841
|
+
e,
|
|
842
|
+
`${name}.partial.mp4`,
|
|
843
|
+
ffmpeg,
|
|
844
|
+
signal,
|
|
845
|
+
(n2) => onProgress((done + n2) / frames)
|
|
846
|
+
);
|
|
847
|
+
await (0, import_promises4.rename)(`${name}.partial.mp4`, name);
|
|
848
|
+
}
|
|
849
|
+
done += e - s;
|
|
850
|
+
onProgress(done / frames);
|
|
851
|
+
}
|
|
852
|
+
let picture = segment(plan[0]);
|
|
853
|
+
if (plan.length > 1) {
|
|
854
|
+
const list = (0, import_node_path5.join)(work, "segments.txt");
|
|
855
|
+
await (0, import_promises4.writeFile)(list, plan.map((range) => `file '${segment(range).slice(work.length + 1)}'
|
|
856
|
+
`).join(""));
|
|
857
|
+
picture = (0, import_node_path5.join)(work, "picture.mp4");
|
|
858
|
+
await run2(ffmpeg, ["-f", "concat", "-safe", "0", "-i", list, "-c", "copy", picture]);
|
|
859
|
+
}
|
|
860
|
+
const seconds = frames / film.fps;
|
|
861
|
+
const sounds = await soundInputs(dir, ffmpeg, [...film.sounds, ...film.narration.map(spokenSound)], output);
|
|
862
|
+
const mix = await mixSounds(sounds, seconds, ffmpeg, work, film.narration);
|
|
863
|
+
const subtitles = srt(film);
|
|
864
|
+
if (subtitles) await (0, import_promises4.writeFile)(partialSubtitles, subtitles);
|
|
865
|
+
const track = subtitles && !film.captions;
|
|
866
|
+
const subtitleInput = 1 + (mix ? 1 : 0);
|
|
867
|
+
await run2(ffmpeg, [
|
|
868
|
+
"-i",
|
|
869
|
+
picture,
|
|
870
|
+
...mix ? [...MIX_FORMAT, "-i", mix] : [],
|
|
871
|
+
...track ? ["-i", partialSubtitles] : [],
|
|
872
|
+
"-map",
|
|
873
|
+
"0:v",
|
|
874
|
+
"-c:v",
|
|
875
|
+
"copy",
|
|
876
|
+
...mix ? ["-filter_complex", `[1:a]${mixFinish(seconds)}[aout]`, "-map", "[aout]", "-c:a", "aac", "-b:a", "192k"] : [],
|
|
877
|
+
...track ? ["-map", `${subtitleInput}:s`, "-c:s", "mov_text", "-metadata:s:s:0", "language=und"] : [],
|
|
878
|
+
"-movflags",
|
|
879
|
+
"+faststart",
|
|
880
|
+
partial
|
|
881
|
+
]);
|
|
882
|
+
await (0, import_promises4.rename)(partial, file);
|
|
883
|
+
if (subtitles) await (0, import_promises4.rename)(partialSubtitles, subtitlesFile(file));
|
|
884
|
+
whole = true;
|
|
885
|
+
} finally {
|
|
886
|
+
await Promise.allSettled([stage, ...others].map((photographer) => photographer.close()));
|
|
887
|
+
await (0, import_promises4.rm)(partial, { force: true });
|
|
888
|
+
await (0, import_promises4.rm)(partialSubtitles, { force: true });
|
|
889
|
+
if (resume && !whole) {
|
|
890
|
+
for (const name of await (0, import_promises4.readdir)(work).catch(() => [])) if (!/^\d{7}-\d{7}\.mp4$/.test(name)) await (0, import_promises4.rm)((0, import_node_path5.join)(work, name), { force: true });
|
|
891
|
+
} else await (0, import_promises4.rm)(work, { recursive: true, force: true });
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
async function drawSegment(drawing, film, s, e, file, ffmpeg, signal, onDrawn) {
|
|
895
|
+
const encoder = (0, import_node_child_process2.spawn)(
|
|
896
|
+
ffmpeg,
|
|
897
|
+
["-y", "-loglevel", "error", "-f", "image2pipe", "-framerate", String(film.fps), "-c:v", "png", "-i", "-", ...VIDEO, "-g", String(film.fps * 2), "-r", String(film.fps), "-frames:v", String(e - s), file],
|
|
898
|
+
{ stdio: ["pipe", "ignore", "pipe"] }
|
|
899
|
+
);
|
|
900
|
+
let stderr2 = "";
|
|
901
|
+
encoder.stderr.on("data", (data) => {
|
|
902
|
+
stderr2 = (stderr2 + data).slice(-4e3);
|
|
903
|
+
});
|
|
904
|
+
encoder.stdin.on("error", () => {
|
|
905
|
+
});
|
|
906
|
+
const finished = new Promise((done, fail) => {
|
|
907
|
+
encoder.on("error", fail);
|
|
908
|
+
encoder.on("close", (code) => code === 0 ? done() : fail(new Error(`ffmpeg exited ${code}: ${stderr2.trim().split("\n").slice(-3).join(" / ")}`)));
|
|
909
|
+
});
|
|
910
|
+
finished.catch(() => {
|
|
911
|
+
});
|
|
912
|
+
try {
|
|
913
|
+
let next = s;
|
|
914
|
+
let broken = null;
|
|
915
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
916
|
+
const turn = (i) => broken ? Promise.reject(broken) : i === next ? Promise.resolve() : new Promise((go, stop) => waiting.set(i, { go, stop }));
|
|
917
|
+
const draw = async (photographer, first) => {
|
|
918
|
+
for (let i = first; i < e; i += drawing.length) {
|
|
919
|
+
if (broken) throw broken;
|
|
920
|
+
if (signal.aborted) throw new Error("The export was cancelled.");
|
|
921
|
+
const png = await photographer.png(i / film.fps);
|
|
922
|
+
await turn(i);
|
|
923
|
+
if (broken) throw broken;
|
|
924
|
+
await write(encoder.stdin, png);
|
|
925
|
+
onDrawn(i + 1 - s);
|
|
926
|
+
next = i + 1;
|
|
927
|
+
waiting.get(next)?.go();
|
|
928
|
+
waiting.delete(next);
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
const drawn = await Promise.allSettled(
|
|
932
|
+
drawing.map(
|
|
933
|
+
(photographer, c) => draw(photographer, s + c).catch((error) => {
|
|
934
|
+
if (!broken) broken = error;
|
|
935
|
+
for (const waiter of waiting.values()) waiter.stop(broken);
|
|
936
|
+
waiting.clear();
|
|
937
|
+
throw error;
|
|
938
|
+
})
|
|
939
|
+
)
|
|
940
|
+
);
|
|
941
|
+
if (broken || drawn.some((result) => result.status === "rejected")) throw broken;
|
|
942
|
+
encoder.stdin.end();
|
|
943
|
+
} catch (error) {
|
|
944
|
+
encoder.kill("SIGKILL");
|
|
945
|
+
await finished.catch(() => {
|
|
946
|
+
});
|
|
947
|
+
await (0, import_promises4.rm)(file, { force: true });
|
|
948
|
+
throw error;
|
|
949
|
+
}
|
|
950
|
+
await finished;
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
// ffmpeg.ts
|
|
954
|
+
var import_node_child_process3 = require("node:child_process");
|
|
955
|
+
var import_node_fs3 = require("node:fs");
|
|
956
|
+
var import_node_path6 = require("node:path");
|
|
957
|
+
var NEEDS = {
|
|
958
|
+
encoder: ["libx264", "aac", "mov_text"],
|
|
959
|
+
decoder: ["png"],
|
|
960
|
+
filter: ["scale", "format", "adelay", "afade", "aformat", "alimiter", "aloop", "amix", "aresample", "asetpts", "atrim", "volume"]
|
|
961
|
+
};
|
|
962
|
+
function onPath(name, env = process.env, platform = process.platform) {
|
|
963
|
+
const extensions = platform === "win32" ? (env.PATHEXT ?? ".EXE").split(";").filter(Boolean) : [""];
|
|
964
|
+
for (const dir of (env.PATH ?? env.Path ?? "").split(import_node_path6.delimiter).filter(Boolean)) {
|
|
965
|
+
for (const extension of extensions) {
|
|
966
|
+
const file = (0, import_node_path6.join)(dir, name + extension.toLowerCase());
|
|
967
|
+
try {
|
|
968
|
+
if ((0, import_node_fs3.statSync)(file).isFile()) return file;
|
|
969
|
+
} catch {
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
return void 0;
|
|
975
|
+
}
|
|
976
|
+
function listed(output) {
|
|
977
|
+
const names2 = /* @__PURE__ */ new Set();
|
|
978
|
+
for (const line of output.split("\n")) {
|
|
979
|
+
const [flags, name] = line.trim().split(/\s+/);
|
|
980
|
+
if (flags && name && /^[A-Z.|]+$/.test(flags)) names2.add(name);
|
|
981
|
+
}
|
|
982
|
+
return names2;
|
|
983
|
+
}
|
|
984
|
+
function lacking(have) {
|
|
985
|
+
return Object.keys(NEEDS).flatMap((kind) => NEEDS[kind].filter((name) => !have[kind].has(name)).map((name) => `${kind} ${name}`));
|
|
986
|
+
}
|
|
987
|
+
function installHint(platform = process.platform) {
|
|
988
|
+
if (platform === "darwin") return "brew install ffmpeg";
|
|
989
|
+
if (platform === "win32") return "winget install --id Gyan.FFmpeg -e";
|
|
990
|
+
return "sudo apt-get install ffmpeg, or your distribution's ffmpeg package";
|
|
991
|
+
}
|
|
992
|
+
var listOf = (ffmpeg, kind) => new Promise(
|
|
993
|
+
(done, fail) => (0, import_node_child_process3.execFile)(
|
|
994
|
+
ffmpeg,
|
|
995
|
+
["-hide_banner", `-${kind}s`],
|
|
996
|
+
{ maxBuffer: 16 * 1024 * 1024, windowsHide: true },
|
|
997
|
+
(error, stdout) => error ? fail(new Error(`${ffmpeg} could not be run: ${error.message}`)) : done(listed(stdout))
|
|
998
|
+
)
|
|
999
|
+
);
|
|
1000
|
+
async function findFfmpeg() {
|
|
1001
|
+
const named = process.env.OMS_FFMPEG;
|
|
1002
|
+
const ffmpeg = named || onPath("ffmpeg");
|
|
1003
|
+
if (!ffmpeg) throw new Error(`oms renders with ffmpeg, which is not on the PATH. Install it (${installHint()}), or name one in OMS_FFMPEG.`);
|
|
1004
|
+
const [encoder, decoder, filter] = await Promise.all([listOf(ffmpeg, "encoder"), listOf(ffmpeg, "decoder"), listOf(ffmpeg, "filter")]);
|
|
1005
|
+
const gaps = lacking({ encoder, decoder, filter });
|
|
1006
|
+
if (gaps.length) {
|
|
1007
|
+
throw new Error(`The ffmpeg at ${ffmpeg} has no ${gaps.join(", ")}, which a render needs. Install a full build (${installHint()}), or name one in OMS_FFMPEG.`);
|
|
1008
|
+
}
|
|
1009
|
+
return ffmpeg;
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// chrome.ts
|
|
1013
|
+
var import_browsers = require("@puppeteer/browsers");
|
|
1014
|
+
var import_node_child_process4 = require("node:child_process");
|
|
1015
|
+
var import_node_crypto2 = require("node:crypto");
|
|
1016
|
+
var import_node_fs4 = require("node:fs");
|
|
1017
|
+
var import_promises5 = require("node:fs/promises");
|
|
1018
|
+
var import_node_os = require("node:os");
|
|
1019
|
+
var import_node_path7 = require("node:path");
|
|
1020
|
+
|
|
1021
|
+
// ../desktop/src/shared/preview.ts
|
|
1022
|
+
var seekScript = (t) => `window.__oms.seek(${Number(t)}).then(() => Promise.all([...document.images].map(image => image.decode()).concat(document.fonts.ready))).then(() => window.__omsError ?? null)`;
|
|
1023
|
+
var inspectScript = `(() => {
|
|
1024
|
+
const width = innerWidth, height = innerHeight;
|
|
1025
|
+
const generic = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-serif', 'ui-sans-serif', 'ui-monospace', 'ui-rounded', 'math', 'emoji', 'fangsong']);
|
|
1026
|
+
const bare = (family) => family.trim().replace(/^["']|["']$/g, '').toLowerCase();
|
|
1027
|
+
const loaded = new Set([...document.fonts].filter((face) => face.status === 'loaded').map((face) => bare(face.family)));
|
|
1028
|
+
const canvas = document.createElement('canvas');
|
|
1029
|
+
canvas.width = canvas.height = 64;
|
|
1030
|
+
const context = canvas.getContext('2d', { willReadFrequently: true });
|
|
1031
|
+
const pixels = (font, char) => {
|
|
1032
|
+
context.clearRect(0, 0, 64, 64);
|
|
1033
|
+
context.font = font;
|
|
1034
|
+
context.fillText(char, 8, 48);
|
|
1035
|
+
return context.getImageData(0, 0, 64, 64).data;
|
|
1036
|
+
};
|
|
1037
|
+
const drawn = new Map();
|
|
1038
|
+
// Whether the loaded faces draw a character: drawn in them before a generic face, it is the generic face's own glyph,
|
|
1039
|
+
// pixel for pixel, when they lack it. (Widths do not tell: every face draws a Chinese character one em wide.) On a
|
|
1040
|
+
// machine with no face for it at all, it is drawn as the first face's missing-glyph box instead, which differs from
|
|
1041
|
+
// the generic face's: the box an unassigned code point (U+0378) draws in the same faces.
|
|
1042
|
+
const covers = (style, faces, char) => {
|
|
1043
|
+
const key = style + '|' + faces + '|' + char;
|
|
1044
|
+
if (!drawn.has(key)) {
|
|
1045
|
+
const font = style + ' 40px ' + faces + ', monospace';
|
|
1046
|
+
if (!drawn.has(font)) drawn.set(font, pixels(font, '\\u0378'));
|
|
1047
|
+
const theirs = pixels(font, char), fallback = pixels(style + ' 40px monospace', char), box = drawn.get(font);
|
|
1048
|
+
drawn.set(key, (theirs.some((value, i) => value !== fallback[i]) || !fallback.some((value) => value)) && theirs.some((value, i) => value !== box[i]));
|
|
1049
|
+
}
|
|
1050
|
+
return drawn.get(key);
|
|
1051
|
+
};
|
|
1052
|
+
const outside = new Map(), unloaded = new Map();
|
|
1053
|
+
// Every text the film draws: in a layer, named by it; in the captions <Film captions> draws over everything, as
|
|
1054
|
+
// "captions"; anywhere else, as "film".
|
|
1055
|
+
const placeOf = (element) => {
|
|
1056
|
+
const layer = element.closest('[data-layer]');
|
|
1057
|
+
if (layer) return layer.getAttribute('data-layer');
|
|
1058
|
+
for (let e = element; e; e = e.parentElement) if (e.style && e.style.zIndex === '2147483647') return 'captions';
|
|
1059
|
+
return 'film';
|
|
1060
|
+
};
|
|
1061
|
+
{
|
|
1062
|
+
const walker = document.createTreeWalker(document.getElementById('root') || document.body, NodeFilter.SHOW_TEXT);
|
|
1063
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
1064
|
+
const text = node.textContent.replace(/\\s+/g, ' ').trim();
|
|
1065
|
+
const element = node.parentElement;
|
|
1066
|
+
if (!text || !element || element.closest('style, script') || !element.checkVisibility({ opacityProperty: true, visibilityProperty: true })) continue;
|
|
1067
|
+
const id = placeOf(element);
|
|
1068
|
+
const range = document.createRange();
|
|
1069
|
+
range.selectNodeContents(node);
|
|
1070
|
+
const box = range.getBoundingClientRect();
|
|
1071
|
+
if (!box.width || !box.height) continue;
|
|
1072
|
+
const edges = [box.left < -1 && 'left', box.top < -1 && 'top', box.right > width + 1 && 'right', box.bottom > height + 1 && 'bottom'].filter(Boolean);
|
|
1073
|
+
if (edges.length) outside.set(id + '|' + text, { layer: id, text: text.slice(0, 40), edges });
|
|
1074
|
+
const computed = getComputedStyle(element);
|
|
1075
|
+
const stack = computed.fontFamily.split(',').map((family) => family.trim()).filter(Boolean);
|
|
1076
|
+
const first = stack.findIndex((family) => !loaded.has(bare(family)));
|
|
1077
|
+
if (first < 0) continue;
|
|
1078
|
+
const family = stack[first].replace(/^["']|["']$/g, '');
|
|
1079
|
+
// The first face not loaded: it and every one after it, up to a loaded or generic face, are said at once, so a
|
|
1080
|
+
// stack of a Latin and a Chinese face, neither loaded, names both in one check rather than one each.
|
|
1081
|
+
if (first === 0) {
|
|
1082
|
+
for (const each of stack) {
|
|
1083
|
+
const name = each.replace(/^["']|["']$/g, '');
|
|
1084
|
+
if (generic.has(bare(name)) || loaded.has(bare(name))) break;
|
|
1085
|
+
unloaded.set(id + '|' + bare(name), { layer: id, family: name, chars: '' });
|
|
1086
|
+
}
|
|
1087
|
+
continue;
|
|
1088
|
+
}
|
|
1089
|
+
const style = computed.fontStyle + ' ' + computed.fontWeight;
|
|
1090
|
+
const faces = stack.slice(0, first).join(', ');
|
|
1091
|
+
const missed = [...new Set(text.replace(/\\s/g, ''))].filter((char) => !covers(style, faces, char));
|
|
1092
|
+
if (!missed.length) continue;
|
|
1093
|
+
const seen = unloaded.get(id + '|' + bare(family));
|
|
1094
|
+
const chars = [...new Set((seen ? seen.chars : '') + missed.join(''))].slice(0, 40).join('');
|
|
1095
|
+
unloaded.set(id + '|' + bare(family), { layer: id, family, chars });
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
// A layer draws something when any element in it, seen and of some size, holds text, is a picture or a shape, or
|
|
1099
|
+
// paints a ground, an image or a border.
|
|
1100
|
+
const PAINTED = new Set(['img', 'canvas', 'video', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon', 'ellipse', 'text', 'image', 'use']);
|
|
1101
|
+
const shown = new Set();
|
|
1102
|
+
for (const layer of document.querySelectorAll('[data-layer]')) {
|
|
1103
|
+
const id = layer.getAttribute('data-layer');
|
|
1104
|
+
if (shown.has(id)) continue;
|
|
1105
|
+
for (const element of [layer, ...layer.querySelectorAll('*')]) {
|
|
1106
|
+
if (!element.checkVisibility({ opacityProperty: true, visibilityProperty: true })) continue;
|
|
1107
|
+
const box = element.getBoundingClientRect();
|
|
1108
|
+
if (box.width < 1 || box.height < 1) continue;
|
|
1109
|
+
const style = getComputedStyle(element);
|
|
1110
|
+
const painted = PAINTED.has(element.tagName.toLowerCase()) ||
|
|
1111
|
+
[...element.childNodes].some((node) => node.nodeType === 3 && node.textContent.trim()) ||
|
|
1112
|
+
!/^(transparent|rgba\\(0, 0, 0, 0\\))$/.test(style.backgroundColor) || style.backgroundImage !== 'none' ||
|
|
1113
|
+
['Top', 'Right', 'Bottom', 'Left'].some((side) => parseFloat(style['border' + side + 'Width']) > 0 && style['border' + side + 'Style'] !== 'none');
|
|
1114
|
+
if (painted) { shown.add(id); break; }
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
return { outside: [...outside.values()], unloaded: [...unloaded.values()], shown: [...shown] };
|
|
1118
|
+
})()`;
|
|
1119
|
+
|
|
1120
|
+
// chrome.ts
|
|
1121
|
+
function chromeBuild(platform = process.platform, release = (0, import_node_os.release)()) {
|
|
1122
|
+
return platform === "darwin" && Number.parseInt(release, 10) < 22 ? "150.0.7871.124" : "158.0.8127.36";
|
|
1123
|
+
}
|
|
1124
|
+
var DIGESTS = {
|
|
1125
|
+
"158.0.8127.36": [
|
|
1126
|
+
"564ba9876826b3a3ce71f862a37c85ee7938191975afad9f427918db6b073e13",
|
|
1127
|
+
"32499804ce68213b7a3d5f622c8c94004522b02ed35bab7913495e6c8986c904",
|
|
1128
|
+
"2ba780aa9f4afc4f79f4d6c1b32eb0fb9c0217faaa88ac56b5c82facfb31742d",
|
|
1129
|
+
"ca7a3db192eb40cf690d8c338e5e15b62ebaaee4b02e0996521e22f6081c6db3",
|
|
1130
|
+
"dee5819f7bd47d82915bc0598a80288b7f09b9b3f819eef4008fdc208dc6f345"
|
|
1131
|
+
],
|
|
1132
|
+
"150.0.7871.124": [
|
|
1133
|
+
"8c1c8a8f68f53b66b2ca340bcf0d6b3f50f9961b3042b759cefdecc7d2eacd4b",
|
|
1134
|
+
"fc5a7041fc62b0740093077cb476cae232853a0b4272c6851add5f60ce11d1c6"
|
|
1135
|
+
]
|
|
1136
|
+
};
|
|
1137
|
+
var EXECUTABLE = {
|
|
1138
|
+
"darwin/arm64": ["chrome-headless-shell-mac-arm64", "chrome-headless-shell"],
|
|
1139
|
+
"darwin/x64": ["chrome-headless-shell-mac-x64", "chrome-headless-shell"],
|
|
1140
|
+
"linux/x64": ["chrome-headless-shell-linux64", "chrome-headless-shell"],
|
|
1141
|
+
"win32/ia32": ["chrome-headless-shell-win32", "chrome-headless-shell.exe"],
|
|
1142
|
+
"win32/x64": ["chrome-headless-shell-win64", "chrome-headless-shell.exe"]
|
|
1143
|
+
};
|
|
1144
|
+
var PUPPETEER_CACHE = (0, import_node_path7.join)((0, import_node_os.homedir)(), ".cache", "puppeteer");
|
|
1145
|
+
var hyperframesCache = () => (0, import_node_path7.join)(process.env.HYPERFRAMES_CACHE_DIR ? (0, import_node_path7.resolve)(process.env.HYPERFRAMES_CACHE_DIR) : (0, import_node_path7.join)((0, import_node_os.homedir)(), ".cache", "hyperframes"), "chrome");
|
|
1146
|
+
var RUNNING_WRITES = ["debug.log", "chrome_debug.log"];
|
|
1147
|
+
function filesUnder(folder, prefix = "") {
|
|
1148
|
+
const names2 = [];
|
|
1149
|
+
for (const entry of (0, import_node_fs4.readdirSync)(folder, { withFileTypes: true })) {
|
|
1150
|
+
const name = prefix + entry.name;
|
|
1151
|
+
if (entry.isFile()) names2.push(name);
|
|
1152
|
+
else if (!entry.isDirectory()) return void 0;
|
|
1153
|
+
else {
|
|
1154
|
+
const inner = filesUnder((0, import_node_path7.join)(folder, entry.name), `${name}/`);
|
|
1155
|
+
if (!inner) return void 0;
|
|
1156
|
+
names2.push(...inner);
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
return names2;
|
|
1160
|
+
}
|
|
1161
|
+
function headlessShellDigest(folder) {
|
|
1162
|
+
const names2 = filesUnder(folder)?.filter((name) => !RUNNING_WRITES.includes(name)).sort();
|
|
1163
|
+
if (!names2) return void 0;
|
|
1164
|
+
const lines = names2.map((name) => `${name}\0${(0, import_node_crypto2.createHash)("sha256").update((0, import_node_fs4.readFileSync)((0, import_node_path7.join)(folder, name))).digest("hex")}
|
|
1165
|
+
`);
|
|
1166
|
+
return (0, import_node_crypto2.createHash)("sha256").update(lines.join("")).digest("hex");
|
|
1167
|
+
}
|
|
1168
|
+
function pinned(binary, digests) {
|
|
1169
|
+
try {
|
|
1170
|
+
if (!(0, import_node_fs4.lstatSync)(binary).isFile()) return false;
|
|
1171
|
+
const digest = headlessShellDigest((0, import_node_path7.dirname)(binary));
|
|
1172
|
+
return digest !== void 0 && digests.includes(digest);
|
|
1173
|
+
} catch {
|
|
1174
|
+
return false;
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
function inCache(cacheDir, build2, digests = DIGESTS[build2] ?? [], platform = `${process.platform}/${process.arch}`) {
|
|
1178
|
+
const executable = EXECUTABLE[platform];
|
|
1179
|
+
const base = (0, import_node_path7.join)(cacheDir, "chrome-headless-shell");
|
|
1180
|
+
if (!executable || !(0, import_node_fs4.existsSync)(base)) return void 0;
|
|
1181
|
+
const version = (0, import_node_fs4.readdirSync)(base).find((name) => name.slice(name.indexOf("-") + 1) === build2);
|
|
1182
|
+
const binary = version && (0, import_node_path7.join)(base, version, ...executable);
|
|
1183
|
+
return binary && pinned(binary, digests) ? binary : void 0;
|
|
1184
|
+
}
|
|
1185
|
+
var SYSTEM_CHROMIUM = ["/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome", "/usr/bin/google-chrome-stable"];
|
|
1186
|
+
function systemChromium(paths = SYSTEM_CHROMIUM) {
|
|
1187
|
+
for (const path of paths) {
|
|
1188
|
+
try {
|
|
1189
|
+
const real = (0, import_node_fs4.realpathSync)(path);
|
|
1190
|
+
const owned = (file) => {
|
|
1191
|
+
const info = (0, import_node_fs4.statSync)(file);
|
|
1192
|
+
return info.uid === 0 && (info.mode & 18) === 0;
|
|
1193
|
+
};
|
|
1194
|
+
if ((0, import_node_fs4.statSync)(real).isFile() && owned(real) && owned((0, import_node_path7.dirname)(real))) return real;
|
|
1195
|
+
} catch {
|
|
1196
|
+
continue;
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
return void 0;
|
|
1200
|
+
}
|
|
1201
|
+
async function locked(lock, work) {
|
|
1202
|
+
await (0, import_promises5.mkdir)((0, import_node_path7.dirname)(lock), { recursive: true });
|
|
1203
|
+
for (; ; ) {
|
|
1204
|
+
try {
|
|
1205
|
+
await (0, import_promises5.mkdir)(lock);
|
|
1206
|
+
break;
|
|
1207
|
+
} catch (error) {
|
|
1208
|
+
if (error.code !== "EEXIST") throw error;
|
|
1209
|
+
}
|
|
1210
|
+
const since = await (0, import_promises5.stat)(lock).then((info) => Date.now() - info.mtimeMs, () => 0);
|
|
1211
|
+
if (since > 6e5) await (0, import_promises5.rm)(lock, { recursive: true, force: true });
|
|
1212
|
+
await new Promise((done) => setTimeout(done, 500));
|
|
1213
|
+
}
|
|
1214
|
+
try {
|
|
1215
|
+
return await work();
|
|
1216
|
+
} finally {
|
|
1217
|
+
await (0, import_promises5.rm)(lock, { recursive: true, force: true });
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
async function findChrome() {
|
|
1221
|
+
const named = process.env.OMS_CHROME;
|
|
1222
|
+
if (named) {
|
|
1223
|
+
if (!(0, import_node_fs4.existsSync)(named)) throw new Error(`OMS_CHROME names ${named}, which is not there.`);
|
|
1224
|
+
return named;
|
|
1225
|
+
}
|
|
1226
|
+
if (process.platform === "linux" && process.arch === "arm64") {
|
|
1227
|
+
const system = systemChromium();
|
|
1228
|
+
if (system) return system;
|
|
1229
|
+
throw new Error("Chrome has no headless build for Linux on Arm. Install Chromium with the system package manager (for example `sudo apt-get install chromium`), or name a Chrome in OMS_CHROME.");
|
|
1230
|
+
}
|
|
1231
|
+
const build2 = chromeBuild();
|
|
1232
|
+
const found = inCache(hyperframesCache(), build2) ?? inCache(PUPPETEER_CACHE, build2);
|
|
1233
|
+
if (found) return found;
|
|
1234
|
+
const platform = (0, import_browsers.detectBrowserPlatform)();
|
|
1235
|
+
if (!platform || !EXECUTABLE[`${process.platform}/${process.arch}`]) throw new Error(`No Chrome ${build2} for ${process.platform} ${process.arch}.`);
|
|
1236
|
+
return locked((0, import_node_path7.join)(PUPPETEER_CACHE, "oms-download.lock"), async () => {
|
|
1237
|
+
const again = inCache(PUPPETEER_CACHE, build2);
|
|
1238
|
+
if (again) return again;
|
|
1239
|
+
console.error(`Downloading Chrome ${build2} (about 100 MB) into ${PUPPETEER_CACHE}, once.`);
|
|
1240
|
+
const installed = await (0, import_browsers.install)({ browser: import_browsers.Browser.CHROMEHEADLESSSHELL, buildId: build2, cacheDir: PUPPETEER_CACHE, platform });
|
|
1241
|
+
if (!pinned(installed.executablePath, DIGESTS[build2] ?? [])) throw new Error(`The downloaded Chrome is not the build oms pins (${build2}).`);
|
|
1242
|
+
return installed.executablePath;
|
|
1243
|
+
});
|
|
1244
|
+
}
|
|
1245
|
+
var NO_SANDBOX = ["--no-sandbox", "--disable-setuid-sandbox", "--no-zygote"];
|
|
1246
|
+
var thisHost = () => ({
|
|
1247
|
+
platform: process.platform,
|
|
1248
|
+
env: process.env,
|
|
1249
|
+
uid: process.getuid?.(),
|
|
1250
|
+
exists: import_node_fs4.existsSync,
|
|
1251
|
+
read: (path) => {
|
|
1252
|
+
try {
|
|
1253
|
+
return (0, import_node_fs4.readFileSync)(path, "utf8").trim();
|
|
1254
|
+
} catch {
|
|
1255
|
+
return void 0;
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
});
|
|
1259
|
+
function sandboxWanted(host = thisHost()) {
|
|
1260
|
+
const named = host.env.OMS_CHROME_SANDBOX;
|
|
1261
|
+
if (named === "0" || named === "1") return named === "1";
|
|
1262
|
+
if (host.platform !== "linux") return true;
|
|
1263
|
+
return !(host.uid === 0 || ["AWS_LAMBDA_FUNCTION_NAME", "AWS_EXECUTION_ENV", "K_SERVICE", "CLOUD_RUN_JOB", "KUBERNETES_SERVICE_HOST"].some((name) => host.env[name]) || ["/.dockerenv", "/run/.containerenv"].some((path) => host.exists(path)) || host.read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns") === "1" || host.read("/proc/sys/kernel/unprivileged_userns_clone") === "0");
|
|
1264
|
+
}
|
|
1265
|
+
var warned = false;
|
|
1266
|
+
function warnUnsandboxed() {
|
|
1267
|
+
if (warned) return;
|
|
1268
|
+
warned = true;
|
|
1269
|
+
console.error("oms: Chrome runs without its sandbox on this host; set OMS_CHROME_SANDBOX=1 to require it.");
|
|
1270
|
+
}
|
|
1271
|
+
var Pipe = class {
|
|
1272
|
+
constructor(out, input) {
|
|
1273
|
+
this.out = out;
|
|
1274
|
+
input.on("data", (chunk) => {
|
|
1275
|
+
let at = chunk.indexOf(0);
|
|
1276
|
+
while (at >= 0) {
|
|
1277
|
+
this.chunks.push(chunk.subarray(0, at));
|
|
1278
|
+
const message2 = JSON.parse(Buffer.concat(this.chunks).toString("utf8"));
|
|
1279
|
+
this.chunks = [];
|
|
1280
|
+
this.receive(message2);
|
|
1281
|
+
chunk = chunk.subarray(at + 1);
|
|
1282
|
+
at = chunk.indexOf(0);
|
|
1283
|
+
}
|
|
1284
|
+
if (chunk.length) this.chunks.push(chunk);
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
out;
|
|
1288
|
+
next = 0;
|
|
1289
|
+
pending = /* @__PURE__ */ new Map();
|
|
1290
|
+
listeners = /* @__PURE__ */ new Set();
|
|
1291
|
+
chunks = [];
|
|
1292
|
+
closed = null;
|
|
1293
|
+
send(method, params = {}, sessionId) {
|
|
1294
|
+
if (this.closed) return Promise.reject(this.closed);
|
|
1295
|
+
const id = ++this.next;
|
|
1296
|
+
this.out.write(`${JSON.stringify({ id, method, params, sessionId })}\0`);
|
|
1297
|
+
return new Promise((done, fail) => this.pending.set(id, { method, done, fail }));
|
|
1298
|
+
}
|
|
1299
|
+
on(listener) {
|
|
1300
|
+
this.listeners.add(listener);
|
|
1301
|
+
}
|
|
1302
|
+
close(error) {
|
|
1303
|
+
this.closed = error;
|
|
1304
|
+
for (const { fail } of this.pending.values()) fail(error);
|
|
1305
|
+
this.pending.clear();
|
|
1306
|
+
}
|
|
1307
|
+
receive(message2) {
|
|
1308
|
+
if (message2.id === void 0) {
|
|
1309
|
+
for (const listener of this.listeners) listener(message2);
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
const call = this.pending.get(message2.id);
|
|
1313
|
+
if (!call) return;
|
|
1314
|
+
this.pending.delete(message2.id);
|
|
1315
|
+
if (message2.error) call.fail(new Error(`${call.method}: ${message2.error.message}`));
|
|
1316
|
+
else call.done(message2.result);
|
|
1317
|
+
}
|
|
1318
|
+
};
|
|
1319
|
+
async function start(binary, profile, sandbox, driven) {
|
|
1320
|
+
const args = [
|
|
1321
|
+
// Driven: a page's compositor draws a frame only when HeadlessExperimental.beginFrame asks for one.
|
|
1322
|
+
...driven ? ["--deterministic-mode"] : [],
|
|
1323
|
+
...(0, import_node_path7.basename)(binary).startsWith("chrome-headless-shell") ? [] : ["--headless"],
|
|
1324
|
+
...sandbox ? [] : NO_SANDBOX,
|
|
1325
|
+
"--remote-debugging-pipe",
|
|
1326
|
+
`--user-data-dir=${profile}`,
|
|
1327
|
+
"--no-first-run",
|
|
1328
|
+
"--no-default-browser-check",
|
|
1329
|
+
"--hide-scrollbars",
|
|
1330
|
+
"--mute-audio",
|
|
1331
|
+
"--force-color-profile=srgb",
|
|
1332
|
+
"--force-device-scale-factor=1",
|
|
1333
|
+
// Each frame rastered whole: rastering only what changed leaves a frame's pixels depending on the frame drawn before
|
|
1334
|
+
// it, so frames drawn by several Chromes, or in another order, would differ.
|
|
1335
|
+
"--disable-partial-raster",
|
|
1336
|
+
// WebGL in software where there is no GPU, as the Studio does (stage.ts allowSoftwareWebGL).
|
|
1337
|
+
"--enable-unsafe-swiftshader",
|
|
1338
|
+
// Nothing leaves the machine: every name fails to resolve and every request not answered from the film goes to a
|
|
1339
|
+
// proxy that is not there.
|
|
1340
|
+
"--host-resolver-rules=MAP * ~NOTFOUND",
|
|
1341
|
+
"--proxy-server=127.0.0.1:9",
|
|
1342
|
+
"--proxy-bypass-list=<-loopback>",
|
|
1343
|
+
"about:blank"
|
|
1344
|
+
];
|
|
1345
|
+
const child = (0, import_node_child_process4.spawn)(binary, args, { stdio: ["ignore", "ignore", "pipe", "pipe", "pipe"] });
|
|
1346
|
+
let printed = "";
|
|
1347
|
+
child.stderr.on("data", (data) => {
|
|
1348
|
+
printed = (printed + data.toString()).slice(-4e3);
|
|
1349
|
+
});
|
|
1350
|
+
const pipe = new Pipe(child.stdio[3], child.stdio[4]);
|
|
1351
|
+
const exited = new Promise(
|
|
1352
|
+
(_, fail) => child.once("exit", (code, signal) => {
|
|
1353
|
+
const error = new Error(`Chrome exited (${signal ?? code}) before it answered.
|
|
1354
|
+
${printed.trim()}`);
|
|
1355
|
+
pipe.close(error);
|
|
1356
|
+
fail(error);
|
|
1357
|
+
})
|
|
1358
|
+
);
|
|
1359
|
+
child.once("error", (error) => pipe.close(error));
|
|
1360
|
+
await Promise.race([pipe.send("Browser.getVersion"), exited]);
|
|
1361
|
+
return { child, pipe };
|
|
1362
|
+
}
|
|
1363
|
+
var FRAME_MS = 6e4;
|
|
1364
|
+
function timeout(promise, what) {
|
|
1365
|
+
let timer;
|
|
1366
|
+
return Promise.race([
|
|
1367
|
+
promise,
|
|
1368
|
+
new Promise((_, fail) => {
|
|
1369
|
+
timer = setTimeout(() => fail(new Error(`${what} took longer than ${FRAME_MS / 1e3} s.`)), FRAME_MS);
|
|
1370
|
+
})
|
|
1371
|
+
]).finally(() => clearTimeout(timer));
|
|
1372
|
+
}
|
|
1373
|
+
var ORIGIN = "https://film.invalid";
|
|
1374
|
+
var drivable = (binary, platform = process.platform) => platform === "linux" && (0, import_node_path7.basename)(binary).startsWith("chrome-headless-shell");
|
|
1375
|
+
var undriven = false;
|
|
1376
|
+
async function openChromeStage(binary, dir, output, studio2, profile) {
|
|
1377
|
+
if (!drivable(binary) || undriven) return openIn(binary, dir, output, studio2, profile, false);
|
|
1378
|
+
try {
|
|
1379
|
+
return await openIn(binary, dir, output, studio2, profile, true);
|
|
1380
|
+
} catch (driving) {
|
|
1381
|
+
const stage = await openIn(binary, dir, output, studio2, `${profile}-screenshots`, false);
|
|
1382
|
+
undriven = true;
|
|
1383
|
+
console.error(`oms: Chrome could not draw frames on demand here (${String(driving).split("\n")[0]}); it takes screenshots instead.`);
|
|
1384
|
+
return stage;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
async function openIn(binary, dir, output, studio2, profile, driven) {
|
|
1388
|
+
let sandbox = sandboxWanted();
|
|
1389
|
+
let started;
|
|
1390
|
+
try {
|
|
1391
|
+
started = await start(binary, profile, sandbox, driven);
|
|
1392
|
+
} catch (error) {
|
|
1393
|
+
if (!sandbox || process.env.OMS_CHROME_SANDBOX === "1" || !/sandbox|namespace/i.test(String(error))) throw error;
|
|
1394
|
+
sandbox = false;
|
|
1395
|
+
started = await start(binary, profile, sandbox, driven);
|
|
1396
|
+
}
|
|
1397
|
+
if (!sandbox) warnUnsandboxed();
|
|
1398
|
+
const { child, pipe } = started;
|
|
1399
|
+
const close = async () => {
|
|
1400
|
+
await pipe.send("Browser.close").catch(() => {
|
|
1401
|
+
});
|
|
1402
|
+
if (child.exitCode === null && child.signalCode === null) {
|
|
1403
|
+
const gone = new Promise((done) => child.once("exit", done));
|
|
1404
|
+
setTimeout(() => child.kill("SIGKILL"), 5e3).unref();
|
|
1405
|
+
await gone;
|
|
1406
|
+
}
|
|
1407
|
+
};
|
|
1408
|
+
try {
|
|
1409
|
+
const { targetId } = await pipe.send("Target.createTarget", { url: "about:blank", ...driven ? { enableBeginFrameControl: true } : {} });
|
|
1410
|
+
const { sessionId } = await pipe.send("Target.attachToTarget", { targetId, flatten: true });
|
|
1411
|
+
await pipe.send("Target.setDiscoverTargets", { discover: true });
|
|
1412
|
+
pipe.on((message2) => {
|
|
1413
|
+
const info = message2.params?.targetInfo;
|
|
1414
|
+
if (message2.method === "Target.targetCreated" && info?.openerId) void pipe.send("Target.closeTarget", { targetId: info.targetId }).catch(() => {
|
|
1415
|
+
});
|
|
1416
|
+
});
|
|
1417
|
+
pipe.on((message2) => {
|
|
1418
|
+
if (message2.method !== "Fetch.requestPaused" || message2.sessionId !== sessionId) return;
|
|
1419
|
+
const { requestId, request } = message2.params;
|
|
1420
|
+
void (async () => {
|
|
1421
|
+
const url = new URL(request.url);
|
|
1422
|
+
if (url.origin !== ORIGIN) return pipe.send("Fetch.failRequest", { requestId, errorReason: "BlockedByClient" }, sessionId);
|
|
1423
|
+
const found = await filmFile(dir, output, studio2, url.pathname);
|
|
1424
|
+
return pipe.send("Fetch.fulfillRequest", {
|
|
1425
|
+
requestId,
|
|
1426
|
+
responseCode: found ? 200 : 404,
|
|
1427
|
+
responseHeaders: [
|
|
1428
|
+
{ name: "content-type", value: found?.type ?? "text/plain" },
|
|
1429
|
+
{ name: "content-security-policy", value: filmPolicy(ORIGIN) },
|
|
1430
|
+
{ name: "cache-control", value: "no-store" },
|
|
1431
|
+
{ name: "access-control-allow-origin", value: "*" }
|
|
1432
|
+
],
|
|
1433
|
+
body: Buffer.from(found?.body ?? "Not found").toString("base64")
|
|
1434
|
+
}, sessionId);
|
|
1435
|
+
})().catch(() => pipe.send("Fetch.failRequest", { requestId, errorReason: "Failed" }, sessionId).catch(() => {
|
|
1436
|
+
}));
|
|
1437
|
+
});
|
|
1438
|
+
await pipe.send("Fetch.enable", { patterns: [{ urlPattern: "*" }] }, sessionId);
|
|
1439
|
+
const evaluate = async (expression) => {
|
|
1440
|
+
const reply = await pipe.send(
|
|
1441
|
+
"Runtime.evaluate",
|
|
1442
|
+
{ expression, awaitPromise: true, returnByValue: true },
|
|
1443
|
+
sessionId
|
|
1444
|
+
);
|
|
1445
|
+
if (reply.exceptionDetails) throw new Error(reply.exceptionDetails.exception?.description ?? reply.exceptionDetails.text);
|
|
1446
|
+
return reply.result.value;
|
|
1447
|
+
};
|
|
1448
|
+
const failed = () => evaluate("window.__omsError ?? null");
|
|
1449
|
+
await pipe.send("Emulation.setDeviceMetricsOverride", { width: 1920, height: 1080, deviceScaleFactor: 1, mobile: false }, sessionId);
|
|
1450
|
+
await timeout(pipe.send("Page.navigate", { url: `${ORIGIN}/?render=1&v=1` }, sessionId), "Loading the film");
|
|
1451
|
+
const film = await timeout(
|
|
1452
|
+
(async () => {
|
|
1453
|
+
for (; ; ) {
|
|
1454
|
+
const error = await failed();
|
|
1455
|
+
if (error) throw new Error(error);
|
|
1456
|
+
const info = await evaluate("window.__oms ? (({seek, ...film}) => film)(window.__oms) : null");
|
|
1457
|
+
if (info) return info;
|
|
1458
|
+
await new Promise((done) => setTimeout(done, 50));
|
|
1459
|
+
}
|
|
1460
|
+
})(),
|
|
1461
|
+
"Starting the film"
|
|
1462
|
+
);
|
|
1463
|
+
await pipe.send("Emulation.setDeviceMetricsOverride", { width: film.width, height: film.height, deviceScaleFactor: 1, mobile: false }, sessionId);
|
|
1464
|
+
await evaluate("document.fonts.ready.then(() => true)");
|
|
1465
|
+
let ticks = Number(process.hrtime.bigint() / 1000000n);
|
|
1466
|
+
const interval = 1e3 / film.fps;
|
|
1467
|
+
const beginFrame = async (screenshot) => {
|
|
1468
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
1469
|
+
ticks += interval;
|
|
1470
|
+
const drawn = await pipe.send("HeadlessExperimental.beginFrame", {
|
|
1471
|
+
frameTimeTicks: ticks,
|
|
1472
|
+
interval,
|
|
1473
|
+
...screenshot ? { screenshot: { format: "png", optimizeForSpeed: true } } : {}
|
|
1474
|
+
}, sessionId);
|
|
1475
|
+
if (!screenshot) return null;
|
|
1476
|
+
if (drawn.screenshotData) return Buffer.from(drawn.screenshotData, "base64");
|
|
1477
|
+
}
|
|
1478
|
+
throw new Error("Chrome drew no frame in five begin frames.");
|
|
1479
|
+
};
|
|
1480
|
+
if (driven) {
|
|
1481
|
+
await timeout(beginFrame(false), "Drawing the first frame");
|
|
1482
|
+
const error = await timeout(evaluate(seekScript(0)), "The frame at 0 s");
|
|
1483
|
+
if (error) throw new Error(error);
|
|
1484
|
+
await timeout(beginFrame(true), "Drawing the first frame");
|
|
1485
|
+
}
|
|
1486
|
+
return {
|
|
1487
|
+
film,
|
|
1488
|
+
inspect: () => timeout(evaluate(inspectScript), "Inspecting the frame"),
|
|
1489
|
+
async png(t) {
|
|
1490
|
+
const error = await timeout(evaluate(seekScript(t)), `The frame at ${t.toFixed(2)} s`);
|
|
1491
|
+
if (error) throw new Error(error);
|
|
1492
|
+
if (driven) return await timeout(beginFrame(true), `Photographing the frame at ${t.toFixed(2)} s`);
|
|
1493
|
+
const shot = await timeout(
|
|
1494
|
+
pipe.send("Page.captureScreenshot", { format: "png", optimizeForSpeed: true }, sessionId),
|
|
1495
|
+
`Photographing the frame at ${t.toFixed(2)} s`
|
|
1496
|
+
);
|
|
1497
|
+
return Buffer.from(shot.data, "base64");
|
|
1498
|
+
},
|
|
1499
|
+
close
|
|
1500
|
+
};
|
|
1501
|
+
} catch (error) {
|
|
1502
|
+
await close();
|
|
1503
|
+
throw error;
|
|
1504
|
+
}
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
// ../desktop/src/main/narration.ts
|
|
1508
|
+
var import_node_child_process5 = require("node:child_process");
|
|
1509
|
+
var import_node_crypto4 = require("node:crypto");
|
|
1510
|
+
var import_promises6 = require("node:fs/promises");
|
|
1511
|
+
var import_node_path8 = require("node:path");
|
|
1512
|
+
|
|
1513
|
+
// ../desktop/src/main/voice.ts
|
|
1514
|
+
var import_node_crypto3 = require("node:crypto");
|
|
1515
|
+
var VOICE_KINDS = ["azure", "elevenlabs", "minimax", "openai"];
|
|
1516
|
+
var VOICE_NAMES = { azure: "Azure", elevenlabs: "ElevenLabs", minimax: "MiniMax", openai: "OpenAI" };
|
|
1517
|
+
var NETWORK = { fetch: (...args) => fetch(...args), WebSocket };
|
|
1518
|
+
var LINE_MS = 9e4;
|
|
1519
|
+
var round = (t) => Math.round(t * 1e3) / 1e3;
|
|
1520
|
+
var UNSPACED = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Thai}]/u;
|
|
1521
|
+
function groupWords(pieces) {
|
|
1522
|
+
const words = [];
|
|
1523
|
+
let run5 = [];
|
|
1524
|
+
const flush = () => {
|
|
1525
|
+
const text = run5.map((p) => p.text).join("").trim();
|
|
1526
|
+
if (text) words.push({ text, start: round(run5[0].start), end: round(run5[run5.length - 1].end) });
|
|
1527
|
+
run5 = [];
|
|
1528
|
+
};
|
|
1529
|
+
for (const piece of pieces) {
|
|
1530
|
+
if (!piece.text.trim()) flush();
|
|
1531
|
+
else if (UNSPACED.test(piece.text)) {
|
|
1532
|
+
flush();
|
|
1533
|
+
run5 = [piece];
|
|
1534
|
+
flush();
|
|
1535
|
+
} else run5.push(piece);
|
|
1536
|
+
}
|
|
1537
|
+
flush();
|
|
1538
|
+
return words;
|
|
1539
|
+
}
|
|
1540
|
+
var escape = (text) => text.replace(/[<>&'"]/g, (c) => ({ "<": "<", ">": ">", "&": "&", "'": "'", '"': """ })[c]);
|
|
1541
|
+
var rate = (speed) => `${speed >= 1 ? "+" : ""}${Math.round((speed - 1) * 100)}%`;
|
|
1542
|
+
var message = (path, type, body, request) => `Path:${path}\r
|
|
1543
|
+
X-RequestId:${request}\r
|
|
1544
|
+
X-Timestamp:${(/* @__PURE__ */ new Date()).toISOString()}\r
|
|
1545
|
+
Content-Type:${type}\r
|
|
1546
|
+
\r
|
|
1547
|
+
${body}`;
|
|
1548
|
+
function azureAudio(frame) {
|
|
1549
|
+
const bytes = Buffer.from(frame);
|
|
1550
|
+
const length = bytes.readUInt16BE(0);
|
|
1551
|
+
const headers = bytes.subarray(2, 2 + length).toString("utf8");
|
|
1552
|
+
return { path: /Path:\s*([\w.]+)/i.exec(headers)?.[1] ?? "", audio: bytes.subarray(2 + length) };
|
|
1553
|
+
}
|
|
1554
|
+
function azureText(frame) {
|
|
1555
|
+
const at = frame.indexOf("\r\n\r\n");
|
|
1556
|
+
const headers = at < 0 ? frame : frame.slice(0, at);
|
|
1557
|
+
return { path: /Path:\s*([\w.]+)/i.exec(headers)?.[1] ?? "", body: at < 0 ? "" : frame.slice(at + 4) };
|
|
1558
|
+
}
|
|
1559
|
+
function azureWords(body) {
|
|
1560
|
+
const metadata = JSON.parse(body).Metadata ?? [];
|
|
1561
|
+
return metadata.filter((m) => m.Type === "WordBoundary" && m.Data?.text?.Text).map((m) => ({ text: m.Data.text.Text, start: round((m.Data.Offset ?? 0) / 1e7), end: round(((m.Data.Offset ?? 0) + (m.Data.Duration ?? 0)) / 1e7) }));
|
|
1562
|
+
}
|
|
1563
|
+
function azure(setup, voice3, text, speed, io) {
|
|
1564
|
+
const region = setup.region?.trim();
|
|
1565
|
+
if (!region || !/^[a-z0-9]+$/.test(region)) throw new Error("Azure needs its region, as eastasia or eastus: Models has it beside the key.");
|
|
1566
|
+
const lang = /^([a-z]{2,3}-[A-Z]{2})-/.exec(voice3)?.[1] ?? "en-US";
|
|
1567
|
+
const request = (0, import_node_crypto3.randomUUID)().replace(/-/g, "");
|
|
1568
|
+
return new Promise((done, fail) => {
|
|
1569
|
+
const socket = new io.WebSocket(
|
|
1570
|
+
`wss://${region}.tts.speech.microsoft.com/cognitiveservices/websocket/v1?X-ConnectionId=${(0, import_node_crypto3.randomUUID)().replace(/-/g, "")}`,
|
|
1571
|
+
{ headers: { "Ocp-Apim-Subscription-Key": setup.key } }
|
|
1572
|
+
);
|
|
1573
|
+
socket.binaryType = "arraybuffer";
|
|
1574
|
+
const audio = [];
|
|
1575
|
+
const words = [];
|
|
1576
|
+
let ended = false;
|
|
1577
|
+
const timer = setTimeout(() => finish(new Error("Azure did not finish speaking the line in time.")), LINE_MS);
|
|
1578
|
+
const finish = (error) => {
|
|
1579
|
+
if (ended) return;
|
|
1580
|
+
ended = true;
|
|
1581
|
+
clearTimeout(timer);
|
|
1582
|
+
socket.close();
|
|
1583
|
+
if (error) fail(error);
|
|
1584
|
+
else if (!audio.length) fail(new Error("Azure answered with no speech: check the voice\u2019s name."));
|
|
1585
|
+
else done({ audio: Buffer.concat(audio), words });
|
|
1586
|
+
};
|
|
1587
|
+
socket.onopen = () => {
|
|
1588
|
+
socket.send(message("speech.config", "application/json", JSON.stringify({ context: { system: { name: "SpeechSDK", version: "1.0.0", build: "JavaScript", lang: "JavaScript" } } }), request));
|
|
1589
|
+
socket.send(
|
|
1590
|
+
message(
|
|
1591
|
+
"synthesis.context",
|
|
1592
|
+
"application/json",
|
|
1593
|
+
JSON.stringify({
|
|
1594
|
+
synthesis: {
|
|
1595
|
+
audio: {
|
|
1596
|
+
metadataOptions: { bookmarkEnabled: false, punctuationBoundaryEnabled: false, sentenceBoundaryEnabled: false, wordBoundaryEnabled: true },
|
|
1597
|
+
outputFormat: "audio-24khz-48kbitrate-mono-mp3"
|
|
1598
|
+
},
|
|
1599
|
+
language: { autoDetection: false }
|
|
1600
|
+
}
|
|
1601
|
+
}),
|
|
1602
|
+
request
|
|
1603
|
+
)
|
|
1604
|
+
);
|
|
1605
|
+
socket.send(
|
|
1606
|
+
message(
|
|
1607
|
+
"ssml",
|
|
1608
|
+
"application/ssml+xml",
|
|
1609
|
+
`<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='${lang}'><voice name='${escape(voice3)}'><prosody rate='${rate(speed)}'>${escape(text)}</prosody></voice></speak>`,
|
|
1610
|
+
request
|
|
1611
|
+
)
|
|
1612
|
+
);
|
|
1613
|
+
};
|
|
1614
|
+
socket.onmessage = ({ data }) => {
|
|
1615
|
+
if (typeof data === "string") {
|
|
1616
|
+
const { path, body } = azureText(data);
|
|
1617
|
+
if (path === "audio.metadata") words.push(...azureWords(body));
|
|
1618
|
+
else if (path === "turn.end") finish();
|
|
1619
|
+
} else {
|
|
1620
|
+
const frame = azureAudio(data);
|
|
1621
|
+
if (frame.path === "audio" && frame.audio.length) audio.push(frame.audio);
|
|
1622
|
+
}
|
|
1623
|
+
};
|
|
1624
|
+
socket.onerror = () => finish(new Error("Azure refused the connection: check the key, and that the region is the resource\u2019s own."));
|
|
1625
|
+
socket.onclose = ({ code, reason }) => finish(new Error(`Azure closed the connection before the line was spoken (${code}${reason ? `: ${reason}` : ""}).`));
|
|
1626
|
+
});
|
|
1627
|
+
}
|
|
1628
|
+
async function answer(response, who) {
|
|
1629
|
+
const text = await response.text();
|
|
1630
|
+
if (!response.ok) throw new Error(`${who} answered ${response.status}: ${text.slice(0, 300) || response.statusText}`);
|
|
1631
|
+
try {
|
|
1632
|
+
return JSON.parse(text);
|
|
1633
|
+
} catch {
|
|
1634
|
+
throw new Error(`${who} answered with something that is not JSON.`);
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
function elevenLabsWords(alignment) {
|
|
1638
|
+
return groupWords(
|
|
1639
|
+
alignment.characters.map((text, i) => ({ text, start: alignment.character_start_times_seconds[i] ?? 0, end: alignment.character_end_times_seconds[i] ?? 0 }))
|
|
1640
|
+
);
|
|
1641
|
+
}
|
|
1642
|
+
async function elevenLabs(setup, voice3, text, speed, io) {
|
|
1643
|
+
const response = await io.fetch(`https://api.elevenlabs.io/v1/text-to-speech/${encodeURIComponent(voice3)}/with-timestamps?output_format=mp3_44100_128`, {
|
|
1644
|
+
method: "POST",
|
|
1645
|
+
headers: { "xi-api-key": setup.key, "Content-Type": "application/json" },
|
|
1646
|
+
// Its speed is 0.7 to 1.2; it refuses any other.
|
|
1647
|
+
body: JSON.stringify({ text, model_id: setup.model || "eleven_multilingual_v2", voice_settings: { speed: Math.min(1.2, Math.max(0.7, speed)) } })
|
|
1648
|
+
});
|
|
1649
|
+
const json = await answer(response, "ElevenLabs");
|
|
1650
|
+
if (!json.audio_base64) throw new Error("ElevenLabs answered with no speech.");
|
|
1651
|
+
return { audio: Buffer.from(json.audio_base64, "base64"), words: json.alignment ? elevenLabsWords(json.alignment) : [] };
|
|
1652
|
+
}
|
|
1653
|
+
function miniMaxWords(subtitles) {
|
|
1654
|
+
const entries = (Array.isArray(subtitles) ? subtitles : [subtitles]).flatMap(
|
|
1655
|
+
(s) => s?.timestamped_words ?? []
|
|
1656
|
+
);
|
|
1657
|
+
return groupWords(entries.map((e) => ({ text: e.word, start: e.time_begin / 1e3, end: e.time_end / 1e3 })));
|
|
1658
|
+
}
|
|
1659
|
+
async function miniMax(setup, voice3, text, speed, io) {
|
|
1660
|
+
const base = setup.region === "china" ? "https://api.minimaxi.com" : "https://api.minimax.io";
|
|
1661
|
+
const group = setup.groupId ? `?GroupId=${encodeURIComponent(setup.groupId)}` : "";
|
|
1662
|
+
const response = await io.fetch(`${base}/v1/t2a_v2${group}`, {
|
|
1663
|
+
method: "POST",
|
|
1664
|
+
headers: { Authorization: `Bearer ${setup.key}`, "Content-Type": "application/json" },
|
|
1665
|
+
body: JSON.stringify({
|
|
1666
|
+
model: setup.model || "speech-2.8-hd",
|
|
1667
|
+
text,
|
|
1668
|
+
stream: false,
|
|
1669
|
+
output_format: "url",
|
|
1670
|
+
subtitle_enable: true,
|
|
1671
|
+
subtitle_type: "word",
|
|
1672
|
+
voice_setting: { voice_id: voice3, speed: Math.min(2, Math.max(0.5, speed)), vol: 1, pitch: 0 },
|
|
1673
|
+
audio_setting: { format: "mp3", sample_rate: 32e3, bitrate: 128e3, channel: 1 }
|
|
1674
|
+
})
|
|
1675
|
+
});
|
|
1676
|
+
const json = await answer(response, "MiniMax");
|
|
1677
|
+
if (json.base_resp?.status_code !== 0) throw new Error(`MiniMax refused the line: ${json.base_resp?.status_msg ?? "no reason given"}.`);
|
|
1678
|
+
if (!json.data?.audio || !/^https:\/\//.test(json.data.audio)) throw new Error("MiniMax answered with no speech.");
|
|
1679
|
+
const audio = Buffer.from(await (await io.fetch(json.data.audio)).arrayBuffer());
|
|
1680
|
+
const subtitles = json.data.subtitle_file && /^https:\/\//.test(json.data.subtitle_file) ? await (await io.fetch(json.data.subtitle_file)).json() : null;
|
|
1681
|
+
return { audio, words: subtitles ? miniMaxWords(subtitles) : [] };
|
|
1682
|
+
}
|
|
1683
|
+
function openAiWords(transcript) {
|
|
1684
|
+
return (transcript.words ?? []).filter((w) => w.word.trim()).map((w) => ({ text: w.word.trim(), start: round(w.start), end: round(w.end) }));
|
|
1685
|
+
}
|
|
1686
|
+
async function openAi(setup, voice3, text, speed, io) {
|
|
1687
|
+
const headers = { Authorization: `Bearer ${setup.key}` };
|
|
1688
|
+
const response = await io.fetch("https://api.openai.com/v1/audio/speech", {
|
|
1689
|
+
method: "POST",
|
|
1690
|
+
headers: { ...headers, "Content-Type": "application/json" },
|
|
1691
|
+
body: JSON.stringify({ model: setup.model || "gpt-4o-mini-tts", voice: voice3, input: text, speed: Math.min(4, Math.max(0.25, speed)), response_format: "mp3" })
|
|
1692
|
+
});
|
|
1693
|
+
if (!response.ok) throw new Error(`OpenAI answered ${response.status}: ${(await response.text()).slice(0, 300)}`);
|
|
1694
|
+
const audio = Buffer.from(await response.arrayBuffer());
|
|
1695
|
+
const form = new FormData();
|
|
1696
|
+
form.append("file", new Blob([new Uint8Array(audio)], { type: "audio/mpeg" }), "line.mp3");
|
|
1697
|
+
form.append("model", "whisper-1");
|
|
1698
|
+
form.append("response_format", "verbose_json");
|
|
1699
|
+
form.append("timestamp_granularities[]", "word");
|
|
1700
|
+
const transcript = await answer(
|
|
1701
|
+
await io.fetch("https://api.openai.com/v1/audio/transcriptions", { method: "POST", headers, body: form }),
|
|
1702
|
+
"OpenAI"
|
|
1703
|
+
);
|
|
1704
|
+
return { audio, words: openAiWords(transcript) };
|
|
1705
|
+
}
|
|
1706
|
+
function speak(setup, voice3, text, speed = 1, io = NETWORK) {
|
|
1707
|
+
if (!text.trim()) throw new Error("A line with no words has nothing to say.");
|
|
1708
|
+
switch (setup.kind) {
|
|
1709
|
+
case "azure":
|
|
1710
|
+
return azure(setup, voice3, text, speed, io);
|
|
1711
|
+
case "elevenlabs":
|
|
1712
|
+
return elevenLabs(setup, voice3, text, speed, io);
|
|
1713
|
+
case "minimax":
|
|
1714
|
+
return miniMax(setup, voice3, text, speed, io);
|
|
1715
|
+
case "openai":
|
|
1716
|
+
return openAi(setup, voice3, text, speed, io);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
var OPENAI_VOICES = ["alloy", "ash", "ballad", "coral", "echo", "fable", "nova", "onyx", "sage", "shimmer", "verse"];
|
|
1720
|
+
async function voicesOf(setup, io = NETWORK) {
|
|
1721
|
+
switch (setup.kind) {
|
|
1722
|
+
case "azure": {
|
|
1723
|
+
const list = await answer(
|
|
1724
|
+
await io.fetch(`https://${setup.region}.tts.speech.microsoft.com/cognitiveservices/voices/list`, { headers: { "Ocp-Apim-Subscription-Key": setup.key } }),
|
|
1725
|
+
"Azure"
|
|
1726
|
+
);
|
|
1727
|
+
return list.map((v) => ({ id: v.ShortName, name: `${v.LocalName ?? v.DisplayName ?? v.ShortName}${v.Gender ? ` \xB7 ${v.Gender}` : ""}`, language: v.Locale }));
|
|
1728
|
+
}
|
|
1729
|
+
case "elevenlabs": {
|
|
1730
|
+
const list = await answer(
|
|
1731
|
+
await io.fetch("https://api.elevenlabs.io/v1/voices", { headers: { "xi-api-key": setup.key } }),
|
|
1732
|
+
"ElevenLabs"
|
|
1733
|
+
);
|
|
1734
|
+
return (list.voices ?? []).map((v) => ({ id: v.voice_id, name: v.name, language: v.labels?.language }));
|
|
1735
|
+
}
|
|
1736
|
+
case "minimax": {
|
|
1737
|
+
const base = setup.region === "china" ? "https://api.minimaxi.com" : "https://api.minimax.io";
|
|
1738
|
+
const list = await answer(
|
|
1739
|
+
await io.fetch(`${base}/v1/get_voice`, {
|
|
1740
|
+
method: "POST",
|
|
1741
|
+
headers: { Authorization: `Bearer ${setup.key}`, "Content-Type": "application/json" },
|
|
1742
|
+
body: JSON.stringify({ voice_type: "system" })
|
|
1743
|
+
}),
|
|
1744
|
+
"MiniMax"
|
|
1745
|
+
);
|
|
1746
|
+
return (list.system_voice ?? []).map((v) => ({ id: v.voice_id, name: v.voice_name ?? v.voice_id }));
|
|
1747
|
+
}
|
|
1748
|
+
case "openai":
|
|
1749
|
+
return OPENAI_VOICES.map((id) => ({ id, name: id[0].toUpperCase() + id.slice(1) }));
|
|
1750
|
+
}
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
// ../desktop/src/main/narration.ts
|
|
1754
|
+
var VOICE_DIR = "voice";
|
|
1755
|
+
var LINES = "lines.json";
|
|
1756
|
+
var CLIP = /^[0-9a-f]{16}\.(mp3|json)$/;
|
|
1757
|
+
function voiceOf(voice3) {
|
|
1758
|
+
const at = voice3?.indexOf(":") ?? -1;
|
|
1759
|
+
const kind = voice3?.slice(0, at);
|
|
1760
|
+
if (!voice3 || at < 0 || !VOICE_KINDS.includes(kind)) {
|
|
1761
|
+
throw new Error(
|
|
1762
|
+
voice3 ? `<Film voice="${voice3}">: the Studio speaks through ${VOICE_KINDS.map((k) => VOICE_NAMES[k]).join(", ")}, as voice="azure:zh-CN-XiaoxiaoNeural".` : 'The film names no voice: give its <Film> one, as voice="azure:zh-CN-XiaoxiaoNeural".'
|
|
1763
|
+
);
|
|
1764
|
+
}
|
|
1765
|
+
return { kind, name: voice3.slice(at + 1) };
|
|
1766
|
+
}
|
|
1767
|
+
var clipKey = (voice3, model, text) => (0, import_node_crypto4.createHash)("sha256").update(`${voice3}
|
|
1768
|
+
${model ?? ""}
|
|
1769
|
+
${text}`).digest("hex").slice(0, 16);
|
|
1770
|
+
function normalised(ffmpeg, from, to, span) {
|
|
1771
|
+
const cut = span ? ["-ss", span[0].toFixed(3), "-to", span[1].toFixed(3)] : [];
|
|
1772
|
+
return new Promise(
|
|
1773
|
+
(done, fail) => (0, import_node_child_process5.execFile)(
|
|
1774
|
+
ffmpeg,
|
|
1775
|
+
["-y", "-hide_banner", "-loglevel", "error", ...cut, "-i", from, "-vn", "-af", "loudnorm=I=-16:TP=-1.5:LRA=11", "-ar", "48000", "-c:a", "libmp3lame", "-b:a", "128k", to],
|
|
1776
|
+
{ timeout: 12e4, windowsHide: true },
|
|
1777
|
+
(error, _out, stderr2) => error ? fail(new Error(`The speech could not be levelled: ${String(stderr2).trim().split("\n").pop()}`)) : done()
|
|
1778
|
+
)
|
|
1779
|
+
);
|
|
1780
|
+
}
|
|
1781
|
+
async function voiceFilm(dir, film, setupFor, ffmpeg, onLine = () => {
|
|
1782
|
+
}, speech = (setup, voice3, text) => speak(setup, voice3, text)) {
|
|
1783
|
+
const { kind, name } = voiceOf(film.voice);
|
|
1784
|
+
const lines = film.scenes.flatMap((scene) => scene.lines).filter((line) => line.text.trim());
|
|
1785
|
+
if (!lines.length) throw new Error("The film has no lines to speak: write what each scene says as its <Line>s.");
|
|
1786
|
+
const setup = await setupFor(kind);
|
|
1787
|
+
const folder = (0, import_node_path8.join)(dir, VOICE_DIR);
|
|
1788
|
+
await (0, import_promises6.mkdir)(folder, { recursive: true });
|
|
1789
|
+
const kept = new Set((await (0, import_promises6.readdir)(folder)).filter((file) => CLIP.test(file)));
|
|
1790
|
+
const narration = { voice: film.voice, lines: {} };
|
|
1791
|
+
const outcome = { spoken: 0, kept: 0, characters: 0, seconds: 0 };
|
|
1792
|
+
for (const [i, line] of lines.entries()) {
|
|
1793
|
+
const key = clipKey(film.voice, setup.model, line.text);
|
|
1794
|
+
narration.lines[line.id] = key;
|
|
1795
|
+
if (kept.has(`${key}.mp3`) && kept.has(`${key}.json`)) {
|
|
1796
|
+
outcome.kept++;
|
|
1797
|
+
} else {
|
|
1798
|
+
const spoken = await speech(setup, name, line.text);
|
|
1799
|
+
const raw = (0, import_node_path8.join)(folder, `${key}.raw.mp3`);
|
|
1800
|
+
await (0, import_promises6.writeFile)(raw, spoken.audio);
|
|
1801
|
+
try {
|
|
1802
|
+
await normalised(ffmpeg, raw, (0, import_node_path8.join)(folder, `${key}.partial.mp3`));
|
|
1803
|
+
} finally {
|
|
1804
|
+
await (0, import_promises6.rm)(raw, { force: true });
|
|
1805
|
+
}
|
|
1806
|
+
await (0, import_promises6.rename)((0, import_node_path8.join)(folder, `${key}.partial.mp3`), (0, import_node_path8.join)(folder, `${key}.mp3`));
|
|
1807
|
+
const seconds = await mediaSeconds(ffmpeg, (0, import_node_path8.join)(folder, `${key}.mp3`));
|
|
1808
|
+
const clip = { text: line.text, voice: film.voice, seconds, words: spoken.words.map((w) => ({ ...w, end: Math.min(w.end, seconds) })) };
|
|
1809
|
+
await (0, import_promises6.writeFile)((0, import_node_path8.join)(folder, `${key}.json`), `${JSON.stringify(clip, null, 2)}
|
|
1810
|
+
`);
|
|
1811
|
+
outcome.spoken++;
|
|
1812
|
+
outcome.characters += line.text.length;
|
|
1813
|
+
outcome.seconds += seconds;
|
|
1814
|
+
}
|
|
1815
|
+
onLine(i + 1, lines.length);
|
|
1816
|
+
}
|
|
1817
|
+
await keepNarration(folder, narration);
|
|
1818
|
+
return outcome;
|
|
1819
|
+
}
|
|
1820
|
+
async function keepNarration(folder, narration) {
|
|
1821
|
+
await (0, import_promises6.writeFile)((0, import_node_path8.join)(folder, LINES), `${JSON.stringify(narration, null, 2)}
|
|
1822
|
+
`);
|
|
1823
|
+
const used = new Set(Object.values(narration.lines));
|
|
1824
|
+
for (const file of await (0, import_promises6.readdir)(folder)) if (CLIP.test(file) && !used.has(file.slice(0, 16))) await (0, import_promises6.rm)((0, import_node_path8.join)(folder, file), { force: true });
|
|
1825
|
+
}
|
|
1826
|
+
|
|
1827
|
+
// ../desktop/src/main/recording.ts
|
|
1828
|
+
var import_node_child_process6 = require("node:child_process");
|
|
1829
|
+
var import_node_crypto5 = require("node:crypto");
|
|
1830
|
+
var import_node_fs5 = require("node:fs");
|
|
1831
|
+
var import_promises7 = require("node:fs/promises");
|
|
1832
|
+
var import_node_os2 = require("node:os");
|
|
1833
|
+
var import_node_path9 = require("node:path");
|
|
1834
|
+
var TRANSCRIBERS = ["minimax", "openai", "elevenlabs"];
|
|
1835
|
+
var NETWORK2 = { fetch: (...args) => fetch(...args), WebSocket };
|
|
1836
|
+
var CHUNK_SECONDS = 300;
|
|
1837
|
+
var HEARD_ENOUGH = 0.75;
|
|
1838
|
+
var round2 = (t) => Math.round(t * 1e3) / 1e3;
|
|
1839
|
+
function languageOf(text) {
|
|
1840
|
+
if (/[\p{Script=Hiragana}\p{Script=Katakana}]/u.test(text)) return "ja";
|
|
1841
|
+
if (/\p{Script=Hangul}/u.test(text)) return "ko";
|
|
1842
|
+
if (/\p{Script=Han}/u.test(text)) return "zh";
|
|
1843
|
+
return "en";
|
|
1844
|
+
}
|
|
1845
|
+
async function answer2(response, who) {
|
|
1846
|
+
if (!response.ok) throw new Error(`${who} could not transcribe the recording: ${response.status} ${(await response.text()).slice(0, 300)}`);
|
|
1847
|
+
return await response.json();
|
|
1848
|
+
}
|
|
1849
|
+
async function transcribe(setup, flac, language, io = NETWORK2) {
|
|
1850
|
+
const form = new FormData();
|
|
1851
|
+
const file = new Blob([new Uint8Array(flac)], { type: "audio/flac" });
|
|
1852
|
+
switch (setup.kind) {
|
|
1853
|
+
case "minimax": {
|
|
1854
|
+
const base = setup.region === "china" ? "https://api.minimaxi.com" : "https://api.minimax.io";
|
|
1855
|
+
form.set("file", file, "take.flac");
|
|
1856
|
+
form.set("model", "asr-1.0");
|
|
1857
|
+
form.set("response_format", "verbose_json");
|
|
1858
|
+
form.set("timestamp_level", "word");
|
|
1859
|
+
const group = setup.groupId ? `&GroupId=${encodeURIComponent(setup.groupId)}` : "";
|
|
1860
|
+
const json = await answer2(
|
|
1861
|
+
await io.fetch(`${base}/v1/speech_to_text?language=${encodeURIComponent(language)}${group}`, { method: "POST", headers: { Authorization: `Bearer ${setup.key}` }, body: form }),
|
|
1862
|
+
"MiniMax"
|
|
1863
|
+
);
|
|
1864
|
+
if (json.base_resp?.status_code) throw new Error(`MiniMax could not transcribe the recording: ${json.base_resp.status_msg ?? json.base_resp.status_code}.`);
|
|
1865
|
+
if (!Array.isArray(json.segments)) throw new Error("MiniMax gave no words for the recording.");
|
|
1866
|
+
return json.segments.filter((w) => w.text?.trim()).map((w) => ({ text: w.text.trim(), start: round2(w.start), end: round2(w.end) }));
|
|
1867
|
+
}
|
|
1868
|
+
case "openai": {
|
|
1869
|
+
form.set("file", file, "take.flac");
|
|
1870
|
+
form.set("model", "whisper-1");
|
|
1871
|
+
form.set("language", language);
|
|
1872
|
+
form.set("response_format", "verbose_json");
|
|
1873
|
+
form.append("timestamp_granularities[]", "word");
|
|
1874
|
+
const json = await answer2(
|
|
1875
|
+
await io.fetch("https://api.openai.com/v1/audio/transcriptions", { method: "POST", headers: { Authorization: `Bearer ${setup.key}` }, body: form }),
|
|
1876
|
+
"OpenAI"
|
|
1877
|
+
);
|
|
1878
|
+
return (json.words ?? []).filter((w) => w.word.trim()).map((w) => ({ text: w.word.trim(), start: round2(w.start), end: round2(w.end) }));
|
|
1879
|
+
}
|
|
1880
|
+
case "elevenlabs": {
|
|
1881
|
+
form.set("file", file, "take.flac");
|
|
1882
|
+
form.set("model_id", "scribe_v1");
|
|
1883
|
+
form.set("language_code", language);
|
|
1884
|
+
form.set("timestamps_granularity", "word");
|
|
1885
|
+
const json = await answer2(
|
|
1886
|
+
await io.fetch("https://api.elevenlabs.io/v1/speech-to-text", { method: "POST", headers: { "xi-api-key": setup.key }, body: form }),
|
|
1887
|
+
"ElevenLabs"
|
|
1888
|
+
);
|
|
1889
|
+
return (json.words ?? []).filter((w) => (w.type ?? "word") === "word" && w.text.trim()).map((w) => ({ text: w.text.trim(), start: round2(w.start), end: round2(w.end) }));
|
|
1890
|
+
}
|
|
1891
|
+
case "azure":
|
|
1892
|
+
throw new Error(`${VOICE_NAMES.azure} does not transcribe a recording here: use ${TRANSCRIBERS.map((k) => VOICE_NAMES[k]).join(", ")}.`);
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
var SPOKEN = /[\p{L}\p{N}]/u;
|
|
1896
|
+
var folded = (c) => c.normalize("NFKC").toLowerCase();
|
|
1897
|
+
var UNSPACED2 = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Thai}]/u;
|
|
1898
|
+
function captionWords(text) {
|
|
1899
|
+
const words = [];
|
|
1900
|
+
let lead = "";
|
|
1901
|
+
let open = false;
|
|
1902
|
+
for (const char of text) {
|
|
1903
|
+
if (/\s/.test(char)) {
|
|
1904
|
+
open = false;
|
|
1905
|
+
continue;
|
|
1906
|
+
}
|
|
1907
|
+
if (!SPOKEN.test(char)) {
|
|
1908
|
+
const last2 = words.at(-1);
|
|
1909
|
+
if (last2) last2.text += char;
|
|
1910
|
+
else lead += char;
|
|
1911
|
+
continue;
|
|
1912
|
+
}
|
|
1913
|
+
const unspaced = UNSPACED2.test(char);
|
|
1914
|
+
const last = words.at(-1);
|
|
1915
|
+
if (open && last && !unspaced && !UNSPACED2.test(last.spoken.at(-1) ?? "")) {
|
|
1916
|
+
last.text += char;
|
|
1917
|
+
last.spoken.push(folded(char));
|
|
1918
|
+
} else {
|
|
1919
|
+
words.push({ text: lead + char, spoken: [folded(char)] });
|
|
1920
|
+
lead = "";
|
|
1921
|
+
}
|
|
1922
|
+
open = !unspaced;
|
|
1923
|
+
}
|
|
1924
|
+
return words;
|
|
1925
|
+
}
|
|
1926
|
+
var MOST_PAIRS = 6e7;
|
|
1927
|
+
function alignLines(lines, heard) {
|
|
1928
|
+
const said = [];
|
|
1929
|
+
heard.forEach((word, w) => {
|
|
1930
|
+
const chars = [...word.text].filter((c) => SPOKEN.test(c)).map(folded);
|
|
1931
|
+
chars.forEach((char, k) => {
|
|
1932
|
+
const step2 = (word.end - word.start) / chars.length;
|
|
1933
|
+
said.push({ char, start: word.start + k * step2, end: word.start + (k + 1) * step2, word: w });
|
|
1934
|
+
});
|
|
1935
|
+
});
|
|
1936
|
+
const written = [];
|
|
1937
|
+
const words = lines.map((line, l) => {
|
|
1938
|
+
const ws = captionWords(line.text);
|
|
1939
|
+
ws.forEach((w, i) => w.spoken.forEach((char) => written.push({ char, line: l, word: i })));
|
|
1940
|
+
return ws;
|
|
1941
|
+
});
|
|
1942
|
+
const n2 = written.length;
|
|
1943
|
+
const m = said.length;
|
|
1944
|
+
if (!m) throw new Error("Nothing was heard in the recording.");
|
|
1945
|
+
if (n2 * m > MOST_PAIRS) throw new Error("The recording and the script are too long to match at once: record and import the film in parts.");
|
|
1946
|
+
const step = new Uint8Array((n2 + 1) * (m + 1));
|
|
1947
|
+
let before = new Uint32Array(m + 1);
|
|
1948
|
+
let row2 = new Uint32Array(m + 1);
|
|
1949
|
+
for (let j = 0; j <= m; j++) before[j] = j, step[j] = 2;
|
|
1950
|
+
for (let i = 1; i <= n2; i++) {
|
|
1951
|
+
row2[0] = i;
|
|
1952
|
+
step[i * (m + 1)] = 1;
|
|
1953
|
+
for (let j = 1; j <= m; j++) {
|
|
1954
|
+
const change = before[j - 1] + (written[i - 1].char === said[j - 1].char ? 0 : 1);
|
|
1955
|
+
const skip = before[j] + 1;
|
|
1956
|
+
const extra = row2[j - 1] + 1;
|
|
1957
|
+
const best = Math.min(change, skip, extra);
|
|
1958
|
+
row2[j] = best;
|
|
1959
|
+
step[i * (m + 1) + j] = best === change ? 0 : best === skip ? 1 : 2;
|
|
1960
|
+
}
|
|
1961
|
+
[before, row2] = [row2, before];
|
|
1962
|
+
}
|
|
1963
|
+
const match = new Int32Array(n2).fill(-1);
|
|
1964
|
+
const same = new Uint8Array(n2);
|
|
1965
|
+
for (let i = n2, j = m; i > 0 || j > 0; ) {
|
|
1966
|
+
const s = step[i * (m + 1) + j];
|
|
1967
|
+
if (i > 0 && j > 0 && s === 0) {
|
|
1968
|
+
match[i - 1] = j - 1;
|
|
1969
|
+
same[i - 1] = written[i - 1].char === said[j - 1].char ? 1 : 0;
|
|
1970
|
+
i--;
|
|
1971
|
+
j--;
|
|
1972
|
+
} else if (i > 0 && (j === 0 || s === 1)) i--;
|
|
1973
|
+
else j--;
|
|
1974
|
+
}
|
|
1975
|
+
const start2 = new Float64Array(n2);
|
|
1976
|
+
const end = new Float64Array(n2);
|
|
1977
|
+
for (let i = 0; i < n2; i++) if (match[i] >= 0) start2[i] = said[match[i]].start, end[i] = said[match[i]].end;
|
|
1978
|
+
for (let i = 0; i < n2; i++) {
|
|
1979
|
+
if (match[i] >= 0) continue;
|
|
1980
|
+
let a = i - 1;
|
|
1981
|
+
while (a >= 0 && match[a] < 0) a--;
|
|
1982
|
+
let b = i + 1;
|
|
1983
|
+
while (b < n2 && match[b] < 0) b++;
|
|
1984
|
+
const from = a >= 0 ? end[a] : b < n2 ? start2[b] : 0;
|
|
1985
|
+
const to = b < n2 ? start2[b] : from;
|
|
1986
|
+
const share = (to - from) / (b - a);
|
|
1987
|
+
start2[i] = from + share * (i - a - 1);
|
|
1988
|
+
end[i] = start2[i] + share;
|
|
1989
|
+
}
|
|
1990
|
+
const heardBy = lines.map((_, l) => written.map((w, i) => w.line === l ? match[i] : -1).filter((j) => j >= 0));
|
|
1991
|
+
const spell = (chars) => chars.map((c, k) => (k && c.word !== chars[k - 1].word && !UNSPACED2.test(c.char) && !UNSPACED2.test(chars[k - 1].char) ? " " : "") + c.char).join("");
|
|
1992
|
+
const aside = (from, to) => {
|
|
1993
|
+
const left = said.slice(from, to);
|
|
1994
|
+
return left.length ? { text: spell(left), at: round2(left[0].start) } : null;
|
|
1995
|
+
};
|
|
1996
|
+
return lines.map((line, l) => {
|
|
1997
|
+
const own = written.map((w, i) => ({ ...w, i })).filter((w) => w.line === l);
|
|
1998
|
+
const first = own[0]?.i ?? 0;
|
|
1999
|
+
const last = own.at(-1)?.i ?? 0;
|
|
2000
|
+
const heardIn = own.filter((w) => same[w.i]).length;
|
|
2001
|
+
const from = Math.max(-1, ...heardBy.slice(0, l).flat()) + 1;
|
|
2002
|
+
const to = Math.min(m, ...heardBy.slice(l + 1).flat());
|
|
2003
|
+
const changes = [];
|
|
2004
|
+
let run5 = null;
|
|
2005
|
+
let prev = -1;
|
|
2006
|
+
const close = () => {
|
|
2007
|
+
if (run5) changes.push({ written: spell(run5.written), heard: spell(run5.heard) });
|
|
2008
|
+
run5 = null;
|
|
2009
|
+
};
|
|
2010
|
+
for (const c of own) {
|
|
2011
|
+
const j = match[c.i];
|
|
2012
|
+
if (j >= 0 && prev >= 0 && j > prev + 1) (run5 ??= { written: [], heard: [] }).heard.push(...said.slice(prev + 1, j));
|
|
2013
|
+
if (j >= 0 && same[c.i]) {
|
|
2014
|
+
close();
|
|
2015
|
+
prev = j;
|
|
2016
|
+
continue;
|
|
2017
|
+
}
|
|
2018
|
+
run5 ??= { written: [], heard: [] };
|
|
2019
|
+
run5.written.push({ char: c.char, word: c.word });
|
|
2020
|
+
if (j >= 0) run5.heard.push(said[j]), prev = j;
|
|
2021
|
+
}
|
|
2022
|
+
close();
|
|
2023
|
+
const mine = heardBy[l];
|
|
2024
|
+
return {
|
|
2025
|
+
id: line.id,
|
|
2026
|
+
text: line.text,
|
|
2027
|
+
start: round2(start2[first]),
|
|
2028
|
+
end: round2(end[last]),
|
|
2029
|
+
words: words[l].map((w, k) => {
|
|
2030
|
+
const chars = own.filter((c) => c.word === k);
|
|
2031
|
+
return { text: w.text, start: round2(start2[chars[0].i]), end: round2(end[chars.at(-1).i]) };
|
|
2032
|
+
}),
|
|
2033
|
+
heard: own.length ? heardIn / own.length : 0,
|
|
2034
|
+
said: spell(said.slice(from, to)),
|
|
2035
|
+
changes,
|
|
2036
|
+
before: mine.length ? aside(from, mine[0]) : null,
|
|
2037
|
+
after: mine.length ? aside(mine.at(-1) + 1, to) : null
|
|
2038
|
+
};
|
|
2039
|
+
});
|
|
2040
|
+
}
|
|
2041
|
+
var run3 = (ffmpeg, args) => new Promise(
|
|
2042
|
+
(done, fail) => (0, import_node_child_process6.execFile)(
|
|
2043
|
+
ffmpeg,
|
|
2044
|
+
["-y", "-hide_banner", "-loglevel", "error", ...args],
|
|
2045
|
+
{ timeout: 3e5, windowsHide: true },
|
|
2046
|
+
(error, _out, stderr2) => error ? fail(new Error(`ffmpeg could not read the recording: ${String(stderr2).trim().split("\n").pop() || error.message}`)) : done()
|
|
2047
|
+
)
|
|
2048
|
+
);
|
|
2049
|
+
async function voiceRecording(dir, film, file, setup, ffmpeg, cache, onStep = () => {
|
|
2050
|
+
}, io = NETWORK2) {
|
|
2051
|
+
if (!film.voice?.startsWith("recording:")) throw new Error(`A recording narrates a film whose voice names it: give its <Film> voice="recording:take"${film.voice ? ` instead of "${film.voice}"` : ""}.`);
|
|
2052
|
+
const lines = film.scenes.flatMap((scene) => scene.lines).filter((line) => line.text.trim() && captionWords(line.text).length);
|
|
2053
|
+
if (!lines.length) throw new Error("The film has no lines to match the recording to: write what each scene says as its <Line>s.");
|
|
2054
|
+
if (!(0, import_node_fs5.existsSync)(file)) throw new Error(`There is no recording at ${file}.`);
|
|
2055
|
+
const hash = (0, import_node_crypto5.createHash)("sha256").update(await (0, import_promises7.readFile)(file)).digest("hex");
|
|
2056
|
+
const language = languageOf(lines.map((line) => line.text).join(""));
|
|
2057
|
+
const transcript = (0, import_node_path9.join)(cache, `${hash.slice(0, 32)}-${setup.kind}-${language}.json`);
|
|
2058
|
+
let heard;
|
|
2059
|
+
const cached2 = (0, import_node_fs5.existsSync)(transcript);
|
|
2060
|
+
if (cached2) heard = JSON.parse(await (0, import_promises7.readFile)(transcript, "utf8"));
|
|
2061
|
+
else {
|
|
2062
|
+
const seconds = await mediaSeconds(ffmpeg, file);
|
|
2063
|
+
const work = await (0, import_promises7.mkdtemp)((0, import_node_path9.join)((0, import_node_os2.tmpdir)(), "oms-recording-"));
|
|
2064
|
+
heard = [];
|
|
2065
|
+
try {
|
|
2066
|
+
for (let offset = 0; offset < seconds; offset += CHUNK_SECONDS) {
|
|
2067
|
+
onStep(`Transcribing ${Math.round(offset)}\u2013${Math.round(Math.min(seconds, offset + CHUNK_SECONDS))} s of ${Math.round(seconds)} s`);
|
|
2068
|
+
const flac = (0, import_node_path9.join)(work, "part.flac");
|
|
2069
|
+
await run3(ffmpeg, ["-ss", String(offset), "-t", String(CHUNK_SECONDS), "-i", file, "-vn", "-ac", "1", "-ar", "16000", "-c:a", "flac", flac]);
|
|
2070
|
+
for (const word of await transcribe(setup, await (0, import_promises7.readFile)(flac), language, io))
|
|
2071
|
+
heard.push({ text: word.text, start: round2(word.start + offset), end: round2(word.end + offset) });
|
|
2072
|
+
}
|
|
2073
|
+
} finally {
|
|
2074
|
+
await (0, import_promises7.rm)(work, { recursive: true, force: true });
|
|
2075
|
+
}
|
|
2076
|
+
await (0, import_promises7.mkdir)(cache, { recursive: true });
|
|
2077
|
+
await (0, import_promises7.writeFile)(`${transcript}.partial`, JSON.stringify(heard));
|
|
2078
|
+
await (0, import_promises7.rename)(`${transcript}.partial`, transcript);
|
|
2079
|
+
}
|
|
2080
|
+
const fits = alignLines(lines, heard);
|
|
2081
|
+
const unheard = fits.filter((fit) => fit.heard < HEARD_ENOUGH);
|
|
2082
|
+
if (unheard.length)
|
|
2083
|
+
throw new Error(
|
|
2084
|
+
`The recording does not read ${unheard.length === 1 ? "this line" : "these lines"} as written, so nothing was cut:
|
|
2085
|
+
${unheard.map((fit) => `- ${fit.id}: written "${fit.text}", heard "${fit.said || "(nothing)"}" (${Math.round(fit.heard * 100)}% as written)`).join("\n")}
|
|
2086
|
+
Record ${unheard.length === 1 ? "it" : "them"} again as written, or write the lines as they were said.`
|
|
2087
|
+
);
|
|
2088
|
+
const folder = (0, import_node_path9.join)(dir, VOICE_DIR);
|
|
2089
|
+
await (0, import_promises7.mkdir)(folder, { recursive: true });
|
|
2090
|
+
const narration = { voice: film.voice, lines: {} };
|
|
2091
|
+
let total = 0;
|
|
2092
|
+
for (const [i, fit] of fits.entries()) {
|
|
2093
|
+
onStep(`Cutting line ${i + 1} of ${fits.length}`);
|
|
2094
|
+
const from = Math.max(i ? (fits[i - 1].end + fit.start) / 2 : 0, fit.start - 0.12);
|
|
2095
|
+
const to = Math.min(i < fits.length - 1 ? (fit.end + fits[i + 1].start) / 2 : Infinity, fit.end + 0.2);
|
|
2096
|
+
const key = clipKey(film.voice, `take:${hash.slice(0, 16)}`, fit.text);
|
|
2097
|
+
narration.lines[fit.id] = key;
|
|
2098
|
+
await normalised(ffmpeg, file, (0, import_node_path9.join)(folder, `${key}.partial.mp3`), [from, to]);
|
|
2099
|
+
await (0, import_promises7.rename)((0, import_node_path9.join)(folder, `${key}.partial.mp3`), (0, import_node_path9.join)(folder, `${key}.mp3`));
|
|
2100
|
+
const seconds = await mediaSeconds(ffmpeg, (0, import_node_path9.join)(folder, `${key}.mp3`));
|
|
2101
|
+
const clip = {
|
|
2102
|
+
text: fit.text,
|
|
2103
|
+
voice: film.voice,
|
|
2104
|
+
seconds,
|
|
2105
|
+
words: fit.words.map((w) => ({ text: w.text, start: round2(Math.max(0, w.start - from)), end: round2(Math.min(seconds, w.end - from)) }))
|
|
2106
|
+
};
|
|
2107
|
+
await (0, import_promises7.writeFile)((0, import_node_path9.join)(folder, `${key}.json`), `${JSON.stringify(clip, null, 2)}
|
|
2108
|
+
`);
|
|
2109
|
+
total += seconds;
|
|
2110
|
+
}
|
|
2111
|
+
await keepNarration(folder, narration);
|
|
2112
|
+
const characters = fits.reduce((sum, fit) => sum + captionWords(fit.text).reduce((n2, w) => n2 + w.spoken.length, 0), 0);
|
|
2113
|
+
return {
|
|
2114
|
+
lines: fits.length,
|
|
2115
|
+
seconds: round2(total),
|
|
2116
|
+
heard: fits.reduce((sum, fit) => sum + fit.heard * captionWords(fit.text).reduce((n2, w) => n2 + w.spoken.length, 0), 0) / characters,
|
|
2117
|
+
transcriber: setup.kind,
|
|
2118
|
+
cached: cached2,
|
|
2119
|
+
changed: fits.filter((fit) => fit.changes.length).map((fit) => ({ id: fit.id, changes: fit.changes })),
|
|
2120
|
+
asides: [fits[0].before, ...fits.map((fit) => fit.after)].filter((a) => a !== null)
|
|
2121
|
+
};
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
// web.ts
|
|
2125
|
+
var import_node_child_process7 = require("node:child_process");
|
|
2126
|
+
var import_node_crypto6 = require("node:crypto");
|
|
2127
|
+
var import_node_fs6 = require("node:fs");
|
|
2128
|
+
var import_promises8 = require("node:fs/promises");
|
|
2129
|
+
var import_node_http = require("node:http");
|
|
2130
|
+
var import_node_path10 = require("node:path");
|
|
2131
|
+
var dataUrl = (type, bytes) => `data:${type};base64,${bytes.toString("base64")}`;
|
|
2132
|
+
var embedded = (value) => JSON.stringify(value).replace(/</g, "\\u003c");
|
|
2133
|
+
var escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
2134
|
+
var scriptText = (text) => text.replace(/<\/(script)/gi, "<\\/$1").replace(/<!--/g, "<\\!--");
|
|
2135
|
+
var hashOf = (text) => `'sha256-${(0, import_node_crypto6.createHash)("sha256").update(text, "utf8").digest("base64")}'`;
|
|
2136
|
+
async function inlineFiles(script, css, files, projectFile) {
|
|
2137
|
+
for (const { name, bytes } of files) script = script.split(JSON.stringify(`build/${name}`)).join(JSON.stringify(dataUrl(TYPES[(0, import_node_path10.extname)(name).toLowerCase()], bytes)));
|
|
2138
|
+
const urls = [...css.matchAll(/url\((['"]?)\/project\/([^'")]+)\1\)/g)];
|
|
2139
|
+
for (const [whole, , path] of urls) {
|
|
2140
|
+
const bytes = await projectFile(decodeURIComponent(path));
|
|
2141
|
+
if (!bytes) throw new Error(`A motion's face is not in the project: ${path}.`);
|
|
2142
|
+
css = css.replace(whole, `url(${dataUrl(TYPES[(0, import_node_path10.extname)(path).toLowerCase()] ?? "font/woff2", bytes)})`);
|
|
2143
|
+
}
|
|
2144
|
+
return { script, css };
|
|
2145
|
+
}
|
|
2146
|
+
function framePage(core, film, css, voice3) {
|
|
2147
|
+
const bundle = scriptText(`window.__omsInline = () => {
|
|
2148
|
+
${film}
|
|
2149
|
+
;return __omsFilm;};`);
|
|
2150
|
+
const preview2 = scriptText(core);
|
|
2151
|
+
const hashes = [hashOf(bundle), hashOf(preview2)];
|
|
2152
|
+
const policy = [
|
|
2153
|
+
"default-src 'none'",
|
|
2154
|
+
`script-src ${hashes.join(" ")}`,
|
|
2155
|
+
"style-src 'unsafe-inline'",
|
|
2156
|
+
"img-src data: blob:",
|
|
2157
|
+
"font-src data:",
|
|
2158
|
+
"media-src data: blob:",
|
|
2159
|
+
"form-action 'none'",
|
|
2160
|
+
"base-uri 'none'"
|
|
2161
|
+
].join("; ");
|
|
2162
|
+
const html = `<!doctype html>
|
|
2163
|
+
<html><head><meta charset="utf-8">
|
|
2164
|
+
<meta http-equiv="Content-Security-Policy" content="${policy}">
|
|
2165
|
+
<style>html,body{margin:0;width:100%;height:100%;overflow:hidden;background:transparent}</style>
|
|
2166
|
+
<style>${css.replace(/<\/(style)/gi, "<\\/$1")}</style>
|
|
2167
|
+
</head><body><div id="root"></div><script type="application/json" id="oms-voice">${embedded(voice3 ?? null)}</script><script>${bundle}</script><script>${preview2}</script></body></html>
|
|
2168
|
+
`;
|
|
2169
|
+
return { html, hashes };
|
|
2170
|
+
}
|
|
2171
|
+
var playerPage = (shown, frameHashes) => `<!doctype html>
|
|
2172
|
+
<html lang="en"><head><meta charset="utf-8">
|
|
2173
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
2174
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self' ${frameHashes.join(" ")}; style-src 'unsafe-inline'; media-src 'self' data: blob:; connect-src 'self'; img-src 'self' data: blob:; font-src data:; base-uri 'none'; form-action 'none'">
|
|
2175
|
+
<title>${escapeHtml(shown.title)}</title>
|
|
2176
|
+
<style>
|
|
2177
|
+
html, body { margin: 0; height: 100%; overflow: hidden; background: #000; }
|
|
2178
|
+
#player, .shell { position: fixed; inset: 0; }
|
|
2179
|
+
.shell.idle.playing { cursor: none; }
|
|
2180
|
+
.frame { position: absolute; left: 50%; top: 50%; transform-origin: 50% 50%; overflow: hidden; }
|
|
2181
|
+
.frame iframe { display: block; border: 0; background: transparent; }
|
|
2182
|
+
.cover { position: absolute; inset: 0; cursor: pointer; }
|
|
2183
|
+
button { font: inherit; color: inherit; }
|
|
2184
|
+
button:focus-visible, .scrub:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
|
|
2185
|
+
[hidden] { display: none !important; }
|
|
2186
|
+
.bar { position: absolute; left: 0; right: 0; bottom: 0; padding: 36px 14px 8px; display: flex; flex-direction: column; gap: 4px;
|
|
2187
|
+
background: linear-gradient(transparent, rgba(0, 0, 0, 0.62)); color: #fff; font: 500 13px/1 system-ui, -apple-system, 'Segoe UI', sans-serif;
|
|
2188
|
+
opacity: 1; transition: opacity 0.25s ease; }
|
|
2189
|
+
.shell.idle.playing .bar { opacity: 0; pointer-events: none; }
|
|
2190
|
+
.row { display: flex; align-items: center; gap: 4px; }
|
|
2191
|
+
.row .gap { flex: 1; }
|
|
2192
|
+
.row button { display: grid; place-items: center; width: 36px; height: 36px; padding: 0; border: 0; border-radius: 8px; background: transparent; cursor: pointer; }
|
|
2193
|
+
.row button:hover { background: rgba(255, 255, 255, 0.16); }
|
|
2194
|
+
.time { margin-left: 6px; font-variant-numeric: tabular-nums; }
|
|
2195
|
+
.time span { opacity: 0.7; }
|
|
2196
|
+
.scrub { --p: 0%; width: 100%; height: 16px; margin: 0; background: transparent; cursor: pointer; -webkit-appearance: none; appearance: none; }
|
|
2197
|
+
.scrub::-webkit-slider-runnable-track { height: 4px; border-radius: 2px; background: linear-gradient(90deg, #fff var(--p), rgba(255, 255, 255, 0.32) var(--p)); transition: height 0.12s; }
|
|
2198
|
+
.scrub:hover::-webkit-slider-runnable-track { height: 6px; }
|
|
2199
|
+
.scrub::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; margin-top: -5px; border: 0; border-radius: 50%; background: #fff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4); }
|
|
2200
|
+
.scrub:hover::-webkit-slider-thumb { margin-top: -4px; }
|
|
2201
|
+
.scrub::-moz-range-track { height: 4px; border-radius: 2px; background: rgba(255, 255, 255, 0.32); }
|
|
2202
|
+
.scrub::-moz-range-progress { height: 4px; border-radius: 2px; background: #fff; }
|
|
2203
|
+
.scrub::-moz-range-thumb { width: 14px; height: 14px; border: 0; border-radius: 50%; background: #fff; }
|
|
2204
|
+
.big { position: absolute; left: 50%; top: 50%; width: 76px; height: 76px; margin: -38px 0 0 -38px; display: grid; place-items: center; padding: 0 0 0 4px;
|
|
2205
|
+
border: 1px solid rgba(255, 255, 255, 0.25); border-radius: 50%; background: rgba(0, 0, 0, 0.5); color: #fff; cursor: pointer;
|
|
2206
|
+
-webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px); transition: transform 0.15s ease, background 0.15s ease; }
|
|
2207
|
+
.big:hover { transform: scale(1.06); background: rgba(0, 0, 0, 0.65); }
|
|
2208
|
+
.big svg { width: 34px; height: 34px; }
|
|
2209
|
+
.chip { position: absolute; top: 12px; right: 12px; display: flex; align-items: center; gap: 6px; height: 34px; padding: 0 12px 0 10px; border: 0; border-radius: 17px;
|
|
2210
|
+
background: rgba(0, 0, 0, 0.6); color: #fff; font: 500 13px/1 system-ui, sans-serif; cursor: pointer; -webkit-backdrop-filter: blur(6px); backdrop-filter: blur(6px); }
|
|
2211
|
+
.chip svg { width: 18px; height: 18px; }
|
|
2212
|
+
.spin { position: absolute; left: 50%; top: 50%; width: 40px; height: 40px; margin: -20px 0 0 -20px; border: 3px solid rgba(255, 255, 255, 0.25);
|
|
2213
|
+
border-top-color: #fff; border-radius: 50%; animation: spin 0.8s linear infinite; pointer-events: none; }
|
|
2214
|
+
@keyframes spin { to { transform: rotate(360deg); } }
|
|
2215
|
+
.notice { position: absolute; top: 12px; left: 12px; max-width: min(520px, calc(100% - 24px)); padding: 10px 12px; border-radius: 8px;
|
|
2216
|
+
background: rgba(0, 0, 0, 0.72); color: #fff; font: 500 13px/1.4 system-ui, sans-serif; }
|
|
2217
|
+
</style></head>
|
|
2218
|
+
<body><div id="player"></div><script type="application/json" id="oms-film">${embedded(shown)}</script><script src="player.js"></script></body></html>
|
|
2219
|
+
`;
|
|
2220
|
+
async function narrationOf(dir) {
|
|
2221
|
+
const read = async (name) => {
|
|
2222
|
+
const file = await safePreviewFile(dir, `voice/${name}`, true).catch(() => null);
|
|
2223
|
+
return file ? JSON.parse(await (0, import_promises8.readFile)(file, "utf8")) : null;
|
|
2224
|
+
};
|
|
2225
|
+
const narration = await read("lines.json");
|
|
2226
|
+
if (!narration) return null;
|
|
2227
|
+
const lines = {};
|
|
2228
|
+
for (const [id, key] of Object.entries(narration.lines ?? {})) {
|
|
2229
|
+
if (!/^[0-9a-f]{16}$/.test(key)) continue;
|
|
2230
|
+
const clip = await read(`${key}.json`);
|
|
2231
|
+
if (clip) lines[id] = { key, ...clip };
|
|
2232
|
+
}
|
|
2233
|
+
return { voice: narration.voice, lines };
|
|
2234
|
+
}
|
|
2235
|
+
var run4 = (ffmpeg, args) => new Promise(
|
|
2236
|
+
(done, fail) => (0, import_node_child_process7.execFile)(
|
|
2237
|
+
ffmpeg,
|
|
2238
|
+
["-hide_banner", "-loglevel", "error", ...args],
|
|
2239
|
+
{ timeout: 6e5, windowsHide: true },
|
|
2240
|
+
(error, _out, stderr2) => error ? fail(new Error(`ffmpeg could not encode the soundtrack: ${String(stderr2).trim() || error.message}`)) : done()
|
|
2241
|
+
)
|
|
2242
|
+
);
|
|
2243
|
+
async function writePlayer(dir, output, film, out, { scripts: scripts2, work, ffmpeg, title, live = false }) {
|
|
2244
|
+
if ((0, import_node_fs6.existsSync)(out) && (await (0, import_promises8.readdir)(out)).length) throw new Error(`${out} is not empty: give the player a new folder.`);
|
|
2245
|
+
await (0, import_promises8.mkdir)(out, { recursive: true });
|
|
2246
|
+
const built = (await (0, import_promises8.readdir)(output, { withFileTypes: true })).filter((entry) => entry.isFile()).map((entry) => entry.name);
|
|
2247
|
+
const imported = built.filter((name) => !/^film(-\d+)?\.js$/.test(name) && name !== FACES && TYPES[(0, import_node_path10.extname)(name).toLowerCase()] && !TYPES[(0, import_node_path10.extname)(name).toLowerCase()].startsWith("audio/"));
|
|
2248
|
+
const files = await Promise.all(imported.map(async (name) => ({ name, bytes: await (0, import_promises8.readFile)((0, import_node_path10.join)(output, name)) })));
|
|
2249
|
+
const css = (0, import_node_fs6.existsSync)((0, import_node_path10.join)(output, FACES)) ? await (0, import_promises8.readFile)((0, import_node_path10.join)(output, FACES), "utf8") : "";
|
|
2250
|
+
const projectFile = async (path) => {
|
|
2251
|
+
const file = await safePreviewFile(dir, path, true).catch(() => null);
|
|
2252
|
+
return file ? (0, import_promises8.readFile)(file) : null;
|
|
2253
|
+
};
|
|
2254
|
+
const inlined = await inlineFiles(await (0, import_promises8.readFile)((0, import_node_path10.join)(output, "film-1.js"), "utf8"), css, files, projectFile);
|
|
2255
|
+
const bundle = inlined.script.replace(/\n\/\/# sourceMappingURL=data:[^\n]*\n?$/, "\n");
|
|
2256
|
+
const frame = framePage(await (0, import_promises8.readFile)(scripts2.core, "utf8"), bundle, inlined.css, await narrationOf(dir));
|
|
2257
|
+
await (0, import_promises8.writeFile)((0, import_node_path10.join)(out, "frame.js"), `window.__omsFrame = ${JSON.stringify(frame.html)};
|
|
2258
|
+
`);
|
|
2259
|
+
await (0, import_promises8.copyFile)(scripts2.player, (0, import_node_path10.join)(out, "player.js"));
|
|
2260
|
+
const seconds = Math.round(film.seconds * film.fps) / film.fps;
|
|
2261
|
+
const sounds = [...film.sounds, ...film.narration.map(spokenSound)];
|
|
2262
|
+
let soundtrack = false;
|
|
2263
|
+
if (sounds.length) {
|
|
2264
|
+
const encoder = await ffmpeg();
|
|
2265
|
+
await (0, import_promises8.mkdir)(work, { recursive: true });
|
|
2266
|
+
const mix = await mixSounds(await soundInputs(dir, encoder, sounds, output), seconds, encoder, work, film.narration);
|
|
2267
|
+
if (mix) {
|
|
2268
|
+
await run4(encoder, [...MIX_FORMAT, "-i", mix, "-af", mixFinish(seconds), "-c:a", "aac", "-b:a", "160k", "-movflags", "+faststart", (0, import_node_path10.join)(out, "soundtrack.mp4")]);
|
|
2269
|
+
soundtrack = true;
|
|
2270
|
+
}
|
|
2271
|
+
}
|
|
2272
|
+
await (0, import_promises8.writeFile)((0, import_node_path10.join)(out, "index.html"), playerPage({ seconds, width: film.width, height: film.height, fps: film.fps, title, sound: soundtrack, live }, frame.hashes));
|
|
2273
|
+
return { soundtrack };
|
|
2274
|
+
}
|
|
2275
|
+
function servePlayer(root, port) {
|
|
2276
|
+
const watchers = /* @__PURE__ */ new Set();
|
|
2277
|
+
const server = (0, import_node_http.createServer)(async (request, response) => {
|
|
2278
|
+
const path = decodeURIComponent(new URL(request.url ?? "/", "http://localhost").pathname);
|
|
2279
|
+
if (path === "/__built") {
|
|
2280
|
+
response.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-store" });
|
|
2281
|
+
response.write(": built\n\n");
|
|
2282
|
+
watchers.add(response);
|
|
2283
|
+
request.on("close", () => watchers.delete(response));
|
|
2284
|
+
return;
|
|
2285
|
+
}
|
|
2286
|
+
const file = within(root(), path === "/" ? "index.html" : path.slice(1));
|
|
2287
|
+
const info = file ? await (0, import_promises8.stat)(file).catch(() => null) : null;
|
|
2288
|
+
if (!file || !info?.isFile()) {
|
|
2289
|
+
response.writeHead(404, { "content-type": "text/plain" }).end("Not found");
|
|
2290
|
+
return;
|
|
2291
|
+
}
|
|
2292
|
+
const type = (0, import_node_path10.extname)(file) === ".html" ? "text/html; charset=utf-8" : TYPES[(0, import_node_path10.extname)(file).toLowerCase()] ?? "application/octet-stream";
|
|
2293
|
+
const body = await (0, import_promises8.readFile)(file);
|
|
2294
|
+
const range = /^bytes=(\d*)-(\d*)$/.exec(request.headers.range ?? "");
|
|
2295
|
+
const headers = { "content-type": type, "cache-control": "no-store", "accept-ranges": "bytes" };
|
|
2296
|
+
if (range && (range[1] || range[2])) {
|
|
2297
|
+
const start2 = range[1] ? Number(range[1]) : Math.max(0, body.length - Number(range[2]));
|
|
2298
|
+
const end = range[1] && range[2] ? Math.min(Number(range[2]), body.length - 1) : body.length - 1;
|
|
2299
|
+
if (start2 > end || start2 >= body.length) {
|
|
2300
|
+
response.writeHead(416, { ...headers, "content-range": `bytes */${body.length}` }).end();
|
|
2301
|
+
return;
|
|
2302
|
+
}
|
|
2303
|
+
response.writeHead(206, { ...headers, "content-range": `bytes ${start2}-${end}/${body.length}`, "content-length": end - start2 + 1 }).end(body.subarray(start2, end + 1));
|
|
2304
|
+
return;
|
|
2305
|
+
}
|
|
2306
|
+
response.writeHead(200, { ...headers, "content-length": body.length }).end(body);
|
|
2307
|
+
});
|
|
2308
|
+
server.listen(port, "127.0.0.1");
|
|
2309
|
+
return { server, built: () => watchers.forEach((watcher) => watcher.write("data: built\n\n")) };
|
|
2310
|
+
}
|
|
2311
|
+
function watchProject(dir, changed) {
|
|
2312
|
+
let timer;
|
|
2313
|
+
const watcher = (0, import_node_fs6.watch)(dir, { recursive: true }, (_event, name) => {
|
|
2314
|
+
const first = String(name ?? "").split(/[\\/]/)[0];
|
|
2315
|
+
if (first === STATE_DIR || first === ".git" || first === "node_modules") return;
|
|
2316
|
+
clearTimeout(timer);
|
|
2317
|
+
timer = setTimeout(changed, 300);
|
|
2318
|
+
});
|
|
2319
|
+
return () => {
|
|
2320
|
+
clearTimeout(timer);
|
|
2321
|
+
watcher.close();
|
|
2322
|
+
};
|
|
2323
|
+
}
|
|
2324
|
+
var removeBuilt = (folder) => (0, import_promises8.rm)(folder, { recursive: true, force: true });
|
|
2325
|
+
|
|
2326
|
+
// ../desktop/src/main/oms-file.ts
|
|
2327
|
+
var import_promises9 = require("node:fs/promises");
|
|
2328
|
+
var import_node_path11 = require("node:path");
|
|
2329
|
+
var import_node_zlib = require("node:zlib");
|
|
2330
|
+
var OMS_EXTENSION = ".oms";
|
|
2331
|
+
var MOST_BYTES = 1024 ** 3;
|
|
2332
|
+
var MOST_FILES = 2e4;
|
|
2333
|
+
var SKIPPED = /* @__PURE__ */ new Set([".git", "node_modules", STATE_DIR, ".DS_Store", "Thumbs.db"]);
|
|
2334
|
+
var EXPORTS = /^[^/]+\.(mp4|srt|png|oms)$/i;
|
|
2335
|
+
async function packedFiles(dir, prefix = "") {
|
|
2336
|
+
const found = [];
|
|
2337
|
+
const entries = (await (0, import_promises9.readdir)((0, import_node_path11.join)(dir, prefix), { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
2338
|
+
for (const entry of entries) {
|
|
2339
|
+
const path = `${prefix}${entry.name}`;
|
|
2340
|
+
if (SKIPPED.has(entry.name) || EXPORTS.test(path)) continue;
|
|
2341
|
+
if (entry.isSymbolicLink()) throw new Error(`${path} is a link: a packed film holds the project's own files, so copy it in instead.`);
|
|
2342
|
+
if (entry.isDirectory()) found.push(...await packedFiles(dir, `${path}/`));
|
|
2343
|
+
else if (entry.isFile()) found.push(path);
|
|
2344
|
+
}
|
|
2345
|
+
return found;
|
|
2346
|
+
}
|
|
2347
|
+
function field(header, at, width, value) {
|
|
2348
|
+
header.write(typeof value === "number" ? value.toString(8).padStart(width - 1, "0") : value, at, width, "utf8");
|
|
2349
|
+
}
|
|
2350
|
+
async function packProject(dir) {
|
|
2351
|
+
const paths = await packedFiles(dir);
|
|
2352
|
+
if (!paths.includes("film.tsx")) throw new Error(`${dir} holds no film.tsx: name the project folder.`);
|
|
2353
|
+
if (paths.length > MOST_FILES) throw new Error(`The project holds ${paths.length} files, more than ${MOST_FILES}.`);
|
|
2354
|
+
const blocks = [];
|
|
2355
|
+
let total = 0;
|
|
2356
|
+
for (const path of paths) {
|
|
2357
|
+
const data = await (0, import_promises9.readFile)((0, import_node_path11.join)(dir, path));
|
|
2358
|
+
total += data.length;
|
|
2359
|
+
if (total > MOST_BYTES) throw new Error(`The project holds more than ${MOST_BYTES / 1024 ** 3} GB: leave its large media out of the folder.`);
|
|
2360
|
+
const header = Buffer.alloc(512);
|
|
2361
|
+
let [prefix, name] = ["", path];
|
|
2362
|
+
if (Buffer.byteLength(path) > 100) {
|
|
2363
|
+
const cut = path.lastIndexOf("/");
|
|
2364
|
+
[prefix, name] = [path.slice(0, cut), path.slice(cut + 1)];
|
|
2365
|
+
if (cut < 0 || Buffer.byteLength(prefix) > 155 || Buffer.byteLength(name) > 100) throw new Error(`${path}: the path is too long to pack.`);
|
|
2366
|
+
}
|
|
2367
|
+
field(header, 0, 100, name);
|
|
2368
|
+
field(header, 100, 8, 420);
|
|
2369
|
+
field(header, 108, 8, 0);
|
|
2370
|
+
field(header, 116, 8, 0);
|
|
2371
|
+
field(header, 124, 12, data.length);
|
|
2372
|
+
field(header, 136, 12, 0);
|
|
2373
|
+
header.fill(" ", 148, 156);
|
|
2374
|
+
header.write("0", 156);
|
|
2375
|
+
header.write("ustar\x0000", 257, 8, "latin1");
|
|
2376
|
+
field(header, 345, 155, prefix);
|
|
2377
|
+
let sum = 0;
|
|
2378
|
+
for (const byte of header) sum += byte;
|
|
2379
|
+
header.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148, 8, "latin1");
|
|
2380
|
+
blocks.push(header, data, Buffer.alloc((512 - data.length % 512) % 512));
|
|
2381
|
+
}
|
|
2382
|
+
blocks.push(Buffer.alloc(1024));
|
|
2383
|
+
return { bytes: (0, import_node_zlib.gzipSync)(Buffer.concat(blocks), { level: 9 }), files: paths.length };
|
|
2384
|
+
}
|
|
2385
|
+
|
|
2386
|
+
// ../desktop/src/main/film/effects.ts
|
|
2387
|
+
var import_node_fs7 = require("node:fs");
|
|
2388
|
+
var import_promises10 = require("node:fs/promises");
|
|
2389
|
+
var import_node_path12 = require("node:path");
|
|
2390
|
+
|
|
2391
|
+
// ../../node_modules/.pnpm/@motionhub+runtime@0.8.1_react@19.3.1/node_modules/@motionhub/runtime/sound.js
|
|
2392
|
+
var ROLES = ["land", "move", "draw", "count", "cut", "out"];
|
|
2393
|
+
var VOICES = ["click", "thump", "tone", "pluck", "swish", "scratch", "chime", "marimba", "square", "squares", "swell", "keys", "noise"];
|
|
2394
|
+
var KIT = ["kick", "hat", "rim", "bass", "arp", "pluck", "chip", "pad", "room"];
|
|
2395
|
+
var mulberry = (seed) => () => {
|
|
2396
|
+
seed = seed + 1831565813 >>> 0;
|
|
2397
|
+
let t = seed;
|
|
2398
|
+
t = Math.imul(t ^ t >>> 15, t | 1);
|
|
2399
|
+
t ^= t + Math.imul(t ^ t >>> 7, t | 61);
|
|
2400
|
+
return ((t ^ t >>> 14) >>> 0) / 4294967296;
|
|
2401
|
+
};
|
|
2402
|
+
function synth(rate2, seed = 7) {
|
|
2403
|
+
const rand = mulberry(seed);
|
|
2404
|
+
const gauss = () => {
|
|
2405
|
+
let u = 0;
|
|
2406
|
+
while (!u) u = rand();
|
|
2407
|
+
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * rand());
|
|
2408
|
+
};
|
|
2409
|
+
const n2 = (s) => Math.max(1, Math.round(s * rate2));
|
|
2410
|
+
const biquad = (x, type, f) => {
|
|
2411
|
+
const w = 2 * Math.PI * Math.min(f, rate2 * 0.45) / rate2, c = Math.cos(w), a = Math.sin(w) / (2 * Math.SQRT1_2);
|
|
2412
|
+
const [b0, b1, b2] = type === "low" ? [(1 - c) / 2, 1 - c, (1 - c) / 2] : [(1 + c) / 2, -(1 + c), (1 + c) / 2];
|
|
2413
|
+
const a0 = 1 + a, a1 = -2 * c, a2 = 1 - a;
|
|
2414
|
+
const y = new Float32Array(x.length);
|
|
2415
|
+
let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
|
|
2416
|
+
for (let i = 0; i < x.length; i++) {
|
|
2417
|
+
const v = (b0 * x[i] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2) / a0;
|
|
2418
|
+
x2 = x1;
|
|
2419
|
+
x1 = x[i];
|
|
2420
|
+
y2 = y1;
|
|
2421
|
+
y1 = v;
|
|
2422
|
+
y[i] = v;
|
|
2423
|
+
}
|
|
2424
|
+
return y;
|
|
2425
|
+
};
|
|
2426
|
+
const band = (x, lo, hi) => biquad(biquad(biquad(biquad(x, "high", lo), "high", lo), "low", hi), "low", hi);
|
|
2427
|
+
const noise = (s) => Float32Array.from({ length: n2(s) }, gauss);
|
|
2428
|
+
const env = (len, attack = 2e-3, decay = 0.2, curve = 4) => Float32Array.from({ length: len }, (_, i) => {
|
|
2429
|
+
const t = i / rate2;
|
|
2430
|
+
return Math.min(1, t / Math.max(attack, 1e-4)) * Math.exp(-curve * t / Math.max(decay, 1e-4));
|
|
2431
|
+
});
|
|
2432
|
+
const mul = (x, y) => x.map((v, i) => v * (typeof y === "number" ? y : y[i] ?? 0));
|
|
2433
|
+
const shape = (len, f) => Float32Array.from({ length: len }, (_, i) => f(i / Math.max(1, len - 1)));
|
|
2434
|
+
const tone = (freq, s, partials = [[1, 1]], decay = 0.6, attack = 3e-3, glide = 0) => {
|
|
2435
|
+
const len = n2(s), out = new Float32Array(len), e = env(len, attack, s * 4, 0);
|
|
2436
|
+
let phase = 0;
|
|
2437
|
+
for (let i = 0; i < len; i++) {
|
|
2438
|
+
const t = i / rate2;
|
|
2439
|
+
phase += 2 * Math.PI * freq * (1 - glide * Math.min(t / s, 1)) / rate2;
|
|
2440
|
+
let v = 0;
|
|
2441
|
+
for (const [r, g] of partials) v += g * Math.sin(r * phase) * Math.exp(-t * r / Math.max(decay, 1e-3));
|
|
2442
|
+
out[i] = v * e[i];
|
|
2443
|
+
}
|
|
2444
|
+
return out;
|
|
2445
|
+
};
|
|
2446
|
+
const V = {
|
|
2447
|
+
click: ({ lo = 2e3, hi = 8e3, len = 0.025 }) => {
|
|
2448
|
+
const x = band(noise(len), lo, hi);
|
|
2449
|
+
return mul(x, env(x.length, 5e-4, len * 0.4));
|
|
2450
|
+
},
|
|
2451
|
+
thump: ({ freq = 70, len = 0.35, drop = 0.5 }) => tone(freq, len, [[1, 1], [2, 0.15]], len * 0.5, 1e-3, drop),
|
|
2452
|
+
tone: ({ freq = 440, len = 0.2, decay = 0.08, partials = [[1, 1], [2, 0.3]] }) => tone(freq, len, partials, decay, 5e-4),
|
|
2453
|
+
pluck: ({ freq = 440, len = 0.9, bright = 0.5 }) => {
|
|
2454
|
+
const len_ = n2(len), period = Math.max(2, Math.round(rate2 / freq)), buf = Float32Array.from({ length: period }, () => (rand() * 2 - 1) * bright + (rand() * 2 - 1) * (1 - bright) * 0.3);
|
|
2455
|
+
const out = new Float32Array(len_);
|
|
2456
|
+
for (let i = 0; i < len_; i++) {
|
|
2457
|
+
const k = i % period;
|
|
2458
|
+
out[i] = buf[k];
|
|
2459
|
+
buf[k] = 0.4985 * (buf[k] + buf[(k + 1) % period]);
|
|
2460
|
+
}
|
|
2461
|
+
return out;
|
|
2462
|
+
},
|
|
2463
|
+
swish: ({ lo = 300, hi = 3e3, rise = 0.5 }, dur) => {
|
|
2464
|
+
const x = band(noise(Math.max(dur, 0.25)), lo, hi);
|
|
2465
|
+
return mul(x, shape(x.length, (t) => (t < rise ? t / rise : (1 - t) / (1 - rise)) ** 1.6));
|
|
2466
|
+
},
|
|
2467
|
+
scratch: ({ lo = 1800, hi = 6e3 }, dur) => {
|
|
2468
|
+
const x = band(noise(Math.max(dur, 0.25)), lo, hi);
|
|
2469
|
+
let ph = 0;
|
|
2470
|
+
return x.map((v, i) => {
|
|
2471
|
+
ph += 2 * Math.PI * (18 + rand() * 22) / rate2;
|
|
2472
|
+
const t = i / x.length;
|
|
2473
|
+
return v * (0.55 + 0.45 * Math.abs(Math.sin(ph))) * Math.min(1, Math.min(t, 1 - t) * 12);
|
|
2474
|
+
});
|
|
2475
|
+
},
|
|
2476
|
+
chime: ({ freq = 1046, len = 1.2 }) => tone(freq, len, [[1, 1], [2.76, 0.4], [5.4, 0.2], [8.9, 0.08]], len * 0.45),
|
|
2477
|
+
marimba: ({ freq = 392, len = 0.6 }) => tone(freq, len, [[1, 1], [4, 0.25], [9.2, 0.06]], len * 0.35, 1e-3),
|
|
2478
|
+
square: ({ freq = 880, len = 0.08 }) => {
|
|
2479
|
+
const l = n2(len), e = env(l, 1e-3, len, 2);
|
|
2480
|
+
return Float32Array.from({ length: l }, (_, i) => Math.sign(Math.sin(2 * Math.PI * freq * i / rate2)) * e[i] * 0.5);
|
|
2481
|
+
},
|
|
2482
|
+
squares: ({ freqs = [440, 554, 659], len = 0.06 }) => concat(freqs.map((freq) => V.square({ freq, len }))),
|
|
2483
|
+
swell: ({ freq = 110 }, dur) => {
|
|
2484
|
+
const s = Math.max(dur, 0.6), l = n2(s), ph = [rand(), rand(), rand(), rand()].map((v) => v * 6);
|
|
2485
|
+
return Float32Array.from({ length: l }, (_, i) => {
|
|
2486
|
+
const t = i / rate2;
|
|
2487
|
+
const v = [[1, 1], [1.5, 0.5], [2, 0.35], [3, 0.12]].reduce((a, [r, g], k) => a + Math.sin(2 * Math.PI * freq * r * t + ph[k]) * g, 0);
|
|
2488
|
+
return v * Math.sin(Math.PI * Math.min(t / s, 1)) ** 2;
|
|
2489
|
+
});
|
|
2490
|
+
},
|
|
2491
|
+
keys: (_, dur) => {
|
|
2492
|
+
const s = Math.max(dur, 0.2), out = new Float32Array(n2(s + 0.1));
|
|
2493
|
+
for (let t = 0; t < s; t += 0.07 + rand() * 0.04) {
|
|
2494
|
+
const x = V.click({ lo: 2500, hi: 8e3, len: 0.018 }), at = n2(t), g = 0.6 + rand() * 0.4;
|
|
2495
|
+
for (let i = 0; i < x.length && at + i < out.length; i++) out[at + i] += x[i] * g;
|
|
2496
|
+
}
|
|
2497
|
+
return out;
|
|
2498
|
+
},
|
|
2499
|
+
noise: ({ lo = 300, hi = 3e3, len, fade = "hit" }, dur) => {
|
|
2500
|
+
const s = len ?? Math.max(dur, 0.1), x = band(noise(s), lo, hi);
|
|
2501
|
+
return mul(x, fade === "hit" ? env(x.length, 2e-3, s * 0.4) : fade === "out" ? shape(x.length, (t) => 1 - t) : shape(x.length, (t) => Math.sin(Math.PI * t)));
|
|
2502
|
+
}
|
|
2503
|
+
};
|
|
2504
|
+
const concat = (parts) => {
|
|
2505
|
+
const out = new Float32Array(parts.reduce((a, p) => a + p.length, 0));
|
|
2506
|
+
let at = 0;
|
|
2507
|
+
for (const p of parts) {
|
|
2508
|
+
out.set(p, at);
|
|
2509
|
+
at += p.length;
|
|
2510
|
+
}
|
|
2511
|
+
return out;
|
|
2512
|
+
};
|
|
2513
|
+
return { V, n: n2, band, noise, env, tone };
|
|
2514
|
+
}
|
|
2515
|
+
var peak = (x) => x.reduce((m, v) => Math.max(m, Math.abs(v)), 1e-9);
|
|
2516
|
+
var add = (out, x, at, g) => {
|
|
2517
|
+
for (let i = 0; i < x.length && at + i < out.length; i++) if (at + i >= 0) out[at + i] += x[i] * g;
|
|
2518
|
+
};
|
|
2519
|
+
function voice(S, spec, dur) {
|
|
2520
|
+
const layers = [].concat(spec);
|
|
2521
|
+
const parts = layers.map((l) => {
|
|
2522
|
+
const make = S.V[l.voice];
|
|
2523
|
+
if (!make) throw new Error(`no voice "${l.voice}": one of ${VOICES.join(", ")}`);
|
|
2524
|
+
const x = make(l, dur);
|
|
2525
|
+
return [x, l.gain ?? 1];
|
|
2526
|
+
});
|
|
2527
|
+
const out = new Float32Array(Math.max(...parts.map(([x]) => x.length)));
|
|
2528
|
+
for (const [x, g] of parts) add(out, x, 0, g / peak(x));
|
|
2529
|
+
return out;
|
|
2530
|
+
}
|
|
2531
|
+
function bed(S, rate2, seconds, { bpm = 90, root = 147, kit = [] }) {
|
|
2532
|
+
const out = new Float32Array(Math.ceil((seconds + 1) * rate2)), beat = 60 / bpm, scale = [0, 3, 5, 7, 10, 12];
|
|
2533
|
+
const put = (x, t, g) => add(out, x, Math.round(t * rate2), g);
|
|
2534
|
+
const has = (k) => kit.includes(k);
|
|
2535
|
+
for (let s = 0; s * beat / 2 < seconds; s++) {
|
|
2536
|
+
const t = s * beat / 2, on = s % 2 === 0, step = s % 8;
|
|
2537
|
+
if (has("kick") && (step === 0 || step === 4)) put(S.V.thump({ freq: 55, len: 0.4, drop: 0.6 }), t, 0.7);
|
|
2538
|
+
if (has("hat") && !on) put(S.V.click({ lo: 6e3, hi: 14e3, len: 0.03 }), t, 0.18);
|
|
2539
|
+
if (has("rim") && (step === 2 || step === 6)) put(S.V.click({ lo: 900, hi: 4e3, len: 0.04 }), t, 0.35);
|
|
2540
|
+
if (has("bass") && step === 0) put(S.tone(root / 2, beat * 3.5, [[1, 1], [2, 0.2]], beat * 3), t, 0.35);
|
|
2541
|
+
if (has("arp") && on) put(S.V.marimba({ freq: root * 2 ** (scale[s / 2 % scale.length | 0] / 12) * 2, len: beat }), t, 0.12);
|
|
2542
|
+
if (has("pluck") && [0, 3, 6].includes(step)) put(S.V.pluck({ freq: root * 2 ** (scale[s * 5 % scale.length] / 12) * 2, len: beat * 2 }), t, 0.2);
|
|
2543
|
+
if (has("chip") && on) put(S.V.square({ freq: root * 2 ** (scale[(s / 2 | 0) % 4] / 12) * 2, len: beat * 0.4 }), t, 0.1);
|
|
2544
|
+
}
|
|
2545
|
+
if (has("pad")) for (let k = 0; k * beat * 8 < seconds; k++) put(S.V.swell({ freq: root * [1, 1.2, 0.84, 1.12][k % 4] }, beat * 8), k * beat * 8, 0.1);
|
|
2546
|
+
if (has("room")) put(S.band(S.noise(seconds + 1), 80, 1200), 0, 0.05);
|
|
2547
|
+
return out.subarray(0, Math.ceil(seconds * rate2));
|
|
2548
|
+
}
|
|
2549
|
+
function renderSound({ seconds, cues = [], sound, rate: rate2 = 44100 }) {
|
|
2550
|
+
const S = synth(rate2);
|
|
2551
|
+
const len = Math.ceil(seconds * rate2), hits = new Float32Array(len + rate2 * 4);
|
|
2552
|
+
for (const c of cues) {
|
|
2553
|
+
const spec = sound.roles?.[c.role];
|
|
2554
|
+
if (!spec || c.at >= seconds) continue;
|
|
2555
|
+
const x = voice(S, spec, c.dur ?? 0);
|
|
2556
|
+
add(hits, x, Math.round(c.at * rate2), { land: 0.8, move: 0.9, draw: 0.8, count: 0.8, cut: 0.6, out: 0.5 }[c.role] ?? 0.7);
|
|
2557
|
+
}
|
|
2558
|
+
const b = bed(S, rate2, seconds, sound), h = peak(hits.subarray(0, len)), p = peak(b);
|
|
2559
|
+
const out = new Float32Array(len), fadeIn = 0.25 * rate2, fadeOut = 1.5 * rate2;
|
|
2560
|
+
for (let i = 0; i < len; i++) {
|
|
2561
|
+
let v = hits[i] / h * 0.9 + b[i] / p * (sound.bed ?? 0.45);
|
|
2562
|
+
if (i < fadeIn) v *= i / fadeIn;
|
|
2563
|
+
if (i > len - fadeOut) v *= ((len - i) / fadeOut) ** 2;
|
|
2564
|
+
out[i] = Math.tanh(v * 1.2) / Math.tanh(1.2);
|
|
2565
|
+
}
|
|
2566
|
+
const top = peak(out);
|
|
2567
|
+
for (let i = 0; i < len; i++) out[i] *= 0.8 / top;
|
|
2568
|
+
return out;
|
|
2569
|
+
}
|
|
2570
|
+
function soundIssues(sound) {
|
|
2571
|
+
const issues = [];
|
|
2572
|
+
if (!sound || typeof sound !== "object") return ["sound.json is an object: {bpm, root, kit, roles}"];
|
|
2573
|
+
if (sound.bpm !== void 0 && !(sound.bpm >= 40 && sound.bpm <= 200)) issues.push("bpm is 40 to 200");
|
|
2574
|
+
if (sound.root !== void 0 && !(sound.root >= 40 && sound.root <= 2e3)) issues.push("root is a note in Hz, 40 to 2000");
|
|
2575
|
+
for (const k of [].concat(sound.kit ?? [])) if (!KIT.includes(k)) issues.push(`kit has no "${k}": ${KIT.join(", ")}`);
|
|
2576
|
+
for (const [role, spec] of Object.entries(sound.roles ?? {})) {
|
|
2577
|
+
if (!ROLES.includes(role)) issues.push(`roles has no "${role}": ${ROLES.join(", ")}`);
|
|
2578
|
+
for (const l of [].concat(spec)) if (!VOICES.includes(l?.voice)) issues.push(`${role} has no voice "${l?.voice}": ${VOICES.join(", ")}`);
|
|
2579
|
+
}
|
|
2580
|
+
return issues;
|
|
2581
|
+
}
|
|
2582
|
+
|
|
2583
|
+
// ../desktop/src/main/film/effects.ts
|
|
2584
|
+
var RATE2 = 44100;
|
|
2585
|
+
function parseCues(text) {
|
|
2586
|
+
const cues = text.split(/[\s,]+/).filter(Boolean).map((written) => {
|
|
2587
|
+
const [at, role, dur, extra] = written.split(":");
|
|
2588
|
+
const cue = { at: Number(at), role };
|
|
2589
|
+
if (dur !== void 0) cue.dur = Number(dur);
|
|
2590
|
+
if (extra !== void 0 || !at || !(cue.at >= 0) || !Number.isFinite(cue.at) || !ROLES.includes(cue.role) || cue.dur !== void 0 && !(cue.dur > 0 && Number.isFinite(cue.dur)))
|
|
2591
|
+
throw new Error(`"${written}" is no cue: write at:role or at:role:dur, with at and dur in seconds and role one of ${ROLES.join(", ")}.`);
|
|
2592
|
+
return cue;
|
|
2593
|
+
});
|
|
2594
|
+
if (!cues.length) throw new Error('No cues: write them as at:role, separated by commas, as "1.2:land, 3.4:move:0.6".');
|
|
2595
|
+
return cues.sort((a, b) => a.at - b.at);
|
|
2596
|
+
}
|
|
2597
|
+
var DEFAULT_SOUND = {
|
|
2598
|
+
roles: {
|
|
2599
|
+
land: [{ voice: "thump", freq: 70, len: 0.35, drop: 0.5 }, { voice: "click", lo: 1500, hi: 6e3, len: 0.03, gain: 0.5 }],
|
|
2600
|
+
move: { voice: "swish", lo: 300, hi: 3e3, rise: 0.5 },
|
|
2601
|
+
draw: { voice: "scratch", lo: 1800, hi: 6e3 },
|
|
2602
|
+
count: { voice: "marimba", freq: 784, len: 0.4 },
|
|
2603
|
+
cut: { voice: "click", lo: 2e3, hi: 9e3, len: 0.03 },
|
|
2604
|
+
out: { voice: "swish", lo: 200, hi: 1500, rise: 0.2 }
|
|
2605
|
+
}
|
|
2606
|
+
};
|
|
2607
|
+
var DEFAULT_SOUND_ID = "oms";
|
|
2608
|
+
async function motionSounds(dir) {
|
|
2609
|
+
const root = (0, import_node_path12.join)(dir, "motions");
|
|
2610
|
+
const found = [];
|
|
2611
|
+
const names2 = async (at) => (await (0, import_promises10.readdir)(at, { withFileTypes: true }).catch(() => [])).filter((e) => e.isDirectory()).map((e) => e.name);
|
|
2612
|
+
for (const name of await names2(root)) {
|
|
2613
|
+
const ids = name.startsWith("@") ? (await names2((0, import_node_path12.join)(root, name))).map((slug2) => `${name}/${slug2}`) : [name];
|
|
2614
|
+
for (const id of ids) {
|
|
2615
|
+
const file = (0, import_node_path12.join)(root, id, "react", "sound.json");
|
|
2616
|
+
if ((0, import_node_fs7.existsSync)(file)) found.push({ id, file });
|
|
2617
|
+
}
|
|
2618
|
+
}
|
|
2619
|
+
return found.sort((a, b) => a.id.localeCompare(b.id));
|
|
2620
|
+
}
|
|
2621
|
+
var levels = (samples) => {
|
|
2622
|
+
let peak2 = 0;
|
|
2623
|
+
let sum = 0;
|
|
2624
|
+
for (const value of samples) {
|
|
2625
|
+
peak2 = Math.max(peak2, Math.abs(value));
|
|
2626
|
+
sum += value * value;
|
|
2627
|
+
}
|
|
2628
|
+
const db = (x) => x > 0 ? 20 * Math.log10(x) : -Infinity;
|
|
2629
|
+
return { peak: db(peak2), rms: db(Math.sqrt(sum / Math.max(1, samples.length))) };
|
|
2630
|
+
};
|
|
2631
|
+
var SILENT_DB = -60;
|
|
2632
|
+
async function effectsTrack(dir, cues, seconds, id) {
|
|
2633
|
+
if (!(seconds > 0) || !Number.isFinite(seconds)) throw new Error("The track needs a length in seconds: the film's, as `oms check` gives it.");
|
|
2634
|
+
const sounds = await motionSounds(dir);
|
|
2635
|
+
const chosen = id ? sounds.find((s) => s.id === id) : sounds.length === 1 ? sounds[0] : sounds.length ? void 0 : { id: DEFAULT_SOUND_ID, file: "" };
|
|
2636
|
+
if (!chosen) {
|
|
2637
|
+
const have = sounds.map((s) => s.id).join(", ") || "none";
|
|
2638
|
+
throw new Error(id ? `The project holds no motion ${id} with a sound (react/sound.json); those with one: ${have}.` : `Name the motion whose sound to use: ${have}.`);
|
|
2639
|
+
}
|
|
2640
|
+
const sound = chosen.file ? JSON.parse(await (0, import_promises10.readFile)(chosen.file, "utf8")) : DEFAULT_SOUND;
|
|
2641
|
+
const issues = soundIssues(sound);
|
|
2642
|
+
if (issues.length) throw new Error(`${chosen.id}'s sound.json: ${issues.join("; ")}`);
|
|
2643
|
+
const late = cues.filter((cue) => cue.at >= seconds);
|
|
2644
|
+
if (late.length) throw new Error(`Cue at ${late[0].at} s is past the track's ${seconds} s.`);
|
|
2645
|
+
const roles = ROLES.filter((role) => sound.roles[role]);
|
|
2646
|
+
const unknown = cues.filter((cue) => !sound.roles[cue.role]);
|
|
2647
|
+
if (unknown.length)
|
|
2648
|
+
throw new Error(`${chosen.id}'s sound has no ${[...new Set(unknown.map((cue) => cue.role))].join(", ")}: its roles are ${roles.join(", ")}. Use one of them for ${unknown.map((cue) => `${cue.at}:${cue.role}`).join(", ")}.`);
|
|
2649
|
+
const samples = renderSound({ seconds, cues, sound, rate: RATE2 });
|
|
2650
|
+
const hits = sound.bed ? renderSound({ seconds, cues, sound: { ...sound, bed: 0 }, rate: RATE2 }) : samples;
|
|
2651
|
+
const starts = [...new Set(cues.map((cue) => cue.at))].sort((x, y) => x - y);
|
|
2652
|
+
const window = (cue) => {
|
|
2653
|
+
const next = starts.find((at) => at > cue.at) ?? Infinity;
|
|
2654
|
+
const end = Math.min(cue.at + Math.max(cue.dur ?? 0, 0.33), Math.max(next, cue.at + 0.05));
|
|
2655
|
+
return hits.subarray(Math.floor(cue.at * RATE2), Math.min(hits.length, Math.ceil(end * RATE2)));
|
|
2656
|
+
};
|
|
2657
|
+
const whole = levels(samples);
|
|
2658
|
+
const report = {
|
|
2659
|
+
motion: chosen.id,
|
|
2660
|
+
roles,
|
|
2661
|
+
peak: whole.peak,
|
|
2662
|
+
rms: whole.rms,
|
|
2663
|
+
cues: cues.map((cue) => {
|
|
2664
|
+
const { peak: peak2 } = levels(window(cue));
|
|
2665
|
+
return { ...cue, peak: peak2, silent: peak2 < SILENT_DB };
|
|
2666
|
+
})
|
|
2667
|
+
};
|
|
2668
|
+
return { motion: chosen.id, wav: wav16(samples, RATE2), report };
|
|
2669
|
+
}
|
|
2670
|
+
function wav16(samples, rate2) {
|
|
2671
|
+
const data = Buffer.alloc(samples.length * 2);
|
|
2672
|
+
for (let i = 0; i < samples.length; i++) data.writeInt16LE(Math.round(Math.max(-1, Math.min(1, samples[i])) * 32767), i * 2);
|
|
2673
|
+
const header = Buffer.alloc(44);
|
|
2674
|
+
header.write("RIFF", 0);
|
|
2675
|
+
header.writeUInt32LE(36 + data.length, 4);
|
|
2676
|
+
header.write("WAVEfmt ", 8);
|
|
2677
|
+
header.writeUInt32LE(16, 16);
|
|
2678
|
+
header.writeUInt16LE(1, 20);
|
|
2679
|
+
header.writeUInt16LE(1, 22);
|
|
2680
|
+
header.writeUInt32LE(rate2, 24);
|
|
2681
|
+
header.writeUInt32LE(rate2 * 2, 28);
|
|
2682
|
+
header.writeUInt16LE(2, 32);
|
|
2683
|
+
header.writeUInt16LE(16, 34);
|
|
2684
|
+
header.write("data", 36);
|
|
2685
|
+
header.writeUInt32LE(data.length, 40);
|
|
2686
|
+
return Buffer.concat([header, data]);
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
// font.ts
|
|
2690
|
+
var import_promises11 = require("node:fs/promises");
|
|
2691
|
+
var import_node_path13 = require("node:path");
|
|
2692
|
+
var TEXT = /\.(tsx|ts|jsx|js|json|md)$/i;
|
|
2693
|
+
var SKIPPED2 = /* @__PURE__ */ new Set(["node_modules", ".git", ".motion-studio", "media"]);
|
|
2694
|
+
var MOST = 3e3;
|
|
2695
|
+
async function projectCharacters(dir) {
|
|
2696
|
+
const chars = /* @__PURE__ */ new Set();
|
|
2697
|
+
for (let c = 32; c < 127; c++) chars.add(String.fromCharCode(c));
|
|
2698
|
+
const walk = async (at) => {
|
|
2699
|
+
for (const entry of await (0, import_promises11.readdir)(at, { withFileTypes: true }).catch(() => [])) {
|
|
2700
|
+
if (SKIPPED2.has(entry.name)) continue;
|
|
2701
|
+
const path = (0, import_node_path13.join)(at, entry.name);
|
|
2702
|
+
if (entry.isDirectory()) await walk(path);
|
|
2703
|
+
else if (TEXT.test(entry.name)) {
|
|
2704
|
+
for (const char of await (0, import_promises11.readFile)(path, "utf8")) if (char.codePointAt(0) >= 32) chars.add(char);
|
|
2705
|
+
}
|
|
2706
|
+
}
|
|
2707
|
+
};
|
|
2708
|
+
await walk(dir);
|
|
2709
|
+
return [...chars].sort((a, b) => a.codePointAt(0) - b.codePointAt(0)).join("");
|
|
2710
|
+
}
|
|
2711
|
+
function faces(css) {
|
|
2712
|
+
return [...css.matchAll(/@font-face\s*\{([^}]*)\}/g)].map(([, body]) => ({
|
|
2713
|
+
weight: Number(/font-weight:\s*(\d+)/.exec(body)?.[1] ?? 400),
|
|
2714
|
+
style: /font-style:\s*(\w+)/.exec(body)?.[1] ?? "normal",
|
|
2715
|
+
url: /src:\s*url\(([^)]+)\)/.exec(body)?.[1] ?? ""
|
|
2716
|
+
})).filter((face) => face.url.startsWith("https://fonts.gstatic.com/"));
|
|
2717
|
+
}
|
|
2718
|
+
function names(font) {
|
|
2719
|
+
const found = /* @__PURE__ */ new Map();
|
|
2720
|
+
const tables = font.readUInt16BE(4);
|
|
2721
|
+
for (let i = 0; i < tables; i++) {
|
|
2722
|
+
const at = 12 + i * 16;
|
|
2723
|
+
if (font.toString("latin1", at, at + 4) !== "name") continue;
|
|
2724
|
+
const table = font.readUInt32BE(at + 8);
|
|
2725
|
+
const count = font.readUInt16BE(table + 2);
|
|
2726
|
+
const strings = table + font.readUInt16BE(table + 4);
|
|
2727
|
+
for (let r = 0; r < count; r++) {
|
|
2728
|
+
const record2 = table + 6 + r * 12;
|
|
2729
|
+
const [platform, , language, id, length, offset] = [0, 2, 4, 6, 8, 10].map((o) => font.readUInt16BE(record2 + o));
|
|
2730
|
+
const bytes = font.subarray(strings + offset, strings + offset + length);
|
|
2731
|
+
const text = platform === 3 ? Buffer.from(bytes).swap16().toString("utf16le") : platform === 1 ? bytes.toString("latin1") : "";
|
|
2732
|
+
if (text && (!found.has(id) || platform === 3 && language === 1033)) found.set(id, text);
|
|
2733
|
+
}
|
|
2734
|
+
}
|
|
2735
|
+
return found;
|
|
2736
|
+
}
|
|
2737
|
+
var slug = (family) => family.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
2738
|
+
async function takeFont(dir, family, weights, ofl, get = (url) => fetch(url, { signal: AbortSignal.timeout(6e4) })) {
|
|
2739
|
+
if (!family.trim() || !weights.length || weights.some((w) => !Number.isInteger(w) || w < 1 || w > 1e3)) throw new Error('Name a family and weights from 1 to 1000, as --family "Noto Sans SC" --weights 400,700.');
|
|
2740
|
+
const text = await projectCharacters(dir);
|
|
2741
|
+
if ([...text].length > MOST) throw new Error(`The project writes ${[...text].length} different characters, more than ${MOST}: oms font cuts a face for a film's words, not a whole script.`);
|
|
2742
|
+
const query = `family=${encodeURIComponent(family.trim()).replace(/%20/g, "+")}:wght@${[...new Set(weights)].sort((a, b) => a - b).join(";")}&text=${encodeURIComponent(text)}`;
|
|
2743
|
+
const response = await get(`https://fonts.googleapis.com/css2?${query}`);
|
|
2744
|
+
if (!response.ok)
|
|
2745
|
+
throw new Error(response.status === 400 ? `Google Fonts has no family "${family}" in weights ${weights.join(", ")}: see fonts.google.com for its name and weights.` : `Google Fonts answered ${response.status} for "${family}".`);
|
|
2746
|
+
const found = faces(await response.text()).filter((face) => face.style === "normal");
|
|
2747
|
+
const missing = weights.filter((w) => !found.some((face) => face.weight === w));
|
|
2748
|
+
if (missing.length) throw new Error(`Google Fonts has "${family}" but not in weight ${missing.join(", ")}.`);
|
|
2749
|
+
const fonts = (0, import_node_path13.join)(dir, "media", "fonts");
|
|
2750
|
+
await (0, import_promises11.mkdir)(fonts, { recursive: true });
|
|
2751
|
+
const files = [];
|
|
2752
|
+
let licence = "";
|
|
2753
|
+
let open = false;
|
|
2754
|
+
for (const face of found) {
|
|
2755
|
+
const file = await get(face.url);
|
|
2756
|
+
if (!file.ok) throw new Error(`Google Fonts answered ${file.status} for ${family} ${face.weight}.`);
|
|
2757
|
+
const bytes = Buffer.from(await file.arrayBuffer());
|
|
2758
|
+
if (!licence) {
|
|
2759
|
+
const record2 = names(bytes);
|
|
2760
|
+
const copyright = record2.get(0) ?? `${family}: no copyright in the font.`;
|
|
2761
|
+
const terms = `${record2.get(13) ?? ""}
|
|
2762
|
+
${record2.get(14) ?? ""}`.trim();
|
|
2763
|
+
open = /open font license|scripts\.sil\.org\/ofl|openfontlicense\.org/i.test(terms);
|
|
2764
|
+
licence = open ? `${copyright}
|
|
2765
|
+
|
|
2766
|
+
${ofl}` : `${copyright}
|
|
2767
|
+
|
|
2768
|
+
${terms || "The font names no licence: check its terms on fonts.google.com before publishing a film with it."}
|
|
2769
|
+
`;
|
|
2770
|
+
}
|
|
2771
|
+
const name = `${slug(family)}-${face.weight}.ttf`;
|
|
2772
|
+
await (0, import_promises11.writeFile)((0, import_node_path13.join)(fonts, name), bytes);
|
|
2773
|
+
files.push(`media/fonts/${name}`);
|
|
2774
|
+
}
|
|
2775
|
+
await (0, import_promises11.writeFile)((0, import_node_path13.join)(fonts, `${slug(family)}-LICENSE.txt`), licence);
|
|
2776
|
+
files.push(`media/fonts/${slug(family)}-LICENSE.txt`);
|
|
2777
|
+
return { files, characters: [...text].length, licence: open ? "SIL Open Font License 1.1" : "see its licence file" };
|
|
2778
|
+
}
|
|
2779
|
+
|
|
2780
|
+
// worker.ts
|
|
2781
|
+
var OFL = (0, import_node_path14.join)(__dirname, "OFL.txt");
|
|
2782
|
+
var studio = (0, import_node_path14.join)(__dirname, "resources", "preview");
|
|
2783
|
+
async function opener(dir, scratch) {
|
|
2784
|
+
const output = (0, import_node_path14.join)(scratch, "build");
|
|
2785
|
+
const build2 = await buildFilmOnce(dir, output);
|
|
2786
|
+
let opened = 0;
|
|
2787
|
+
const where = async (error) => new Error(await located(error instanceof Error ? error.message : String(error), (0, import_node_path14.join)(output, `film-${build2.version}.js`), dir));
|
|
2788
|
+
const open = async () => openChromeStage(await findChrome(), dir, output, studio, (0, import_node_path14.join)(scratch, `profile-${opened++}`)).catch(async (error) => Promise.reject(await where(error)));
|
|
2789
|
+
return { build: build2, output, open, where };
|
|
2790
|
+
}
|
|
2791
|
+
var renderStages = (cores = (0, import_node_os3.availableParallelism)(), free = (0, import_node_os3.freemem)()) => Math.max(1, Math.min(cores, Math.floor(free / 15e8), 8));
|
|
2792
|
+
async function check(dir, scratch) {
|
|
2793
|
+
const { build: build2, output, open } = await opener(dir, scratch);
|
|
2794
|
+
const review = await reviewBuild(build2, open, void 0, { bundle: (0, import_node_path14.join)(output, `film-${build2.version}.js`), dir });
|
|
2795
|
+
const lines = (review.film?.scenes ?? []).flatMap((scene) => scene.lines.map((line) => ({ ...line, scene: scene.id }))).filter((line) => line.text.trim());
|
|
2796
|
+
const unvoiced = lines.filter((line) => !line.voiced);
|
|
2797
|
+
if (review.film?.voice && unvoiced.length)
|
|
2798
|
+
review.issues.push({ id: "unvoiced", kind: "export", severity: "warning", text: `Not yet spoken in ${review.film.voice}: ${unvoiced.map((line) => `"${line.text}"`).join(" ")}. oms voice speaks them.` });
|
|
2799
|
+
for (const line of lines)
|
|
2800
|
+
if (line.over)
|
|
2801
|
+
review.issues.push({ id: `voice-over-${line.id}`, kind: "layout", severity: "warning", text: `"${line.text}" is cut ${Math.round(line.over * 10) / 10} s short by what follows it: give it more room, or fewer words.`, time: line.start, scene: line.scene });
|
|
2802
|
+
for (const sound of review.film?.sounds ?? []) {
|
|
2803
|
+
try {
|
|
2804
|
+
await soundFile(dir, sound.src, output);
|
|
2805
|
+
} catch (error) {
|
|
2806
|
+
review.issues.push({ id: "sound-" + sound.src, kind: "export", severity: "error", text: String(error) });
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
return review;
|
|
2810
|
+
}
|
|
2811
|
+
var RENDERS = (0, import_node_path14.join)((0, import_node_os3.homedir)(), ".cache", "oms", "renders");
|
|
2812
|
+
var KEPT_MS = 7 * 24 * 36e5;
|
|
2813
|
+
async function render(dir, scratch, file, onProgress, signal) {
|
|
2814
|
+
const { build: build2, output, open } = await opener(dir, scratch);
|
|
2815
|
+
if (!build2.ok) throw new Error(build2.errors.join("\n"));
|
|
2816
|
+
const ffmpeg = await findFfmpeg();
|
|
2817
|
+
const resume = (0, import_node_path14.join)(RENDERS, (0, import_node_crypto7.createHash)("sha256").update(await findChrome()).digest("hex").slice(0, 12));
|
|
2818
|
+
for (const chrome of await (0, import_promises12.readdir)(RENDERS).catch(() => []))
|
|
2819
|
+
for (const kept of await (0, import_promises12.readdir)((0, import_node_path14.join)(RENDERS, chrome)).catch(() => [])) {
|
|
2820
|
+
const at = (0, import_node_path14.join)(RENDERS, chrome, kept);
|
|
2821
|
+
if (Date.now() - (await (0, import_promises12.stat)(at)).mtimeMs > KEPT_MS) await (0, import_promises12.rm)(at, { recursive: true, force: true });
|
|
2822
|
+
}
|
|
2823
|
+
await exportFrames(dir, build2.version, file, onProgress, signal, open, ffmpeg, { output, stages: renderStages(), resume });
|
|
2824
|
+
}
|
|
2825
|
+
var scripts = { core: (0, import_node_path14.join)(studio, "core.js"), player: (0, import_node_path14.join)(__dirname, "player.js") };
|
|
2826
|
+
async function filmOf(open) {
|
|
2827
|
+
const stage = await open();
|
|
2828
|
+
try {
|
|
2829
|
+
return stage.film;
|
|
2830
|
+
} finally {
|
|
2831
|
+
await stage.close();
|
|
2832
|
+
}
|
|
2833
|
+
}
|
|
2834
|
+
async function pack(dir, out) {
|
|
2835
|
+
if (!out.toLowerCase().endsWith(OMS_EXTENSION)) throw new Error(`Name a film file ending in ${OMS_EXTENSION}.`);
|
|
2836
|
+
const { bytes, files } = await packProject(dir);
|
|
2837
|
+
const partial = `${out}.partial`;
|
|
2838
|
+
await (0, import_promises12.writeFile)(partial, bytes);
|
|
2839
|
+
await (0, import_promises12.rename)(partial, out);
|
|
2840
|
+
return { files, bytes: bytes.length };
|
|
2841
|
+
}
|
|
2842
|
+
async function player(dir, scratch, out) {
|
|
2843
|
+
const { build: build2, output, open } = await opener(dir, scratch);
|
|
2844
|
+
if (!build2.ok) throw new Error(build2.errors.join("\n"));
|
|
2845
|
+
const film = await filmOf(open);
|
|
2846
|
+
return writePlayer(dir, output, film, out, { scripts, work: (0, import_node_path14.join)(scratch, "mix"), ffmpeg: findFfmpeg, title: (0, import_node_path14.basename)((0, import_node_path14.resolve)(dir)) });
|
|
2847
|
+
}
|
|
2848
|
+
async function preview(dir, scratch, port, say) {
|
|
2849
|
+
let n2 = 0;
|
|
2850
|
+
let served = "";
|
|
2851
|
+
const buildOnce = async () => {
|
|
2852
|
+
const at = (0, import_node_path14.join)(scratch, `build-${++n2}`);
|
|
2853
|
+
const { build: build2, output, open } = await opener(dir, at);
|
|
2854
|
+
if (!build2.ok) throw new Error(build2.errors.join("\n"));
|
|
2855
|
+
const out = (0, import_node_path14.join)(at, "player");
|
|
2856
|
+
await writePlayer(dir, output, await filmOf(open), out, { scripts, work: (0, import_node_path14.join)(at, "mix"), ffmpeg: findFfmpeg, title: (0, import_node_path14.basename)((0, import_node_path14.resolve)(dir)), live: true });
|
|
2857
|
+
return { at, out };
|
|
2858
|
+
};
|
|
2859
|
+
const first = await buildOnce();
|
|
2860
|
+
served = first.out;
|
|
2861
|
+
let last = first.at;
|
|
2862
|
+
const { server, built } = servePlayer(() => served, port);
|
|
2863
|
+
await new Promise((done, fail) => server.once("listening", done).once("error", fail));
|
|
2864
|
+
let busy = Promise.resolve();
|
|
2865
|
+
const stop = watchProject(dir, () => {
|
|
2866
|
+
busy = busy.then(async () => {
|
|
2867
|
+
try {
|
|
2868
|
+
const next = await buildOnce();
|
|
2869
|
+
served = next.out;
|
|
2870
|
+
await removeBuilt(last);
|
|
2871
|
+
last = next.at;
|
|
2872
|
+
built();
|
|
2873
|
+
say("Built again.");
|
|
2874
|
+
} catch (error) {
|
|
2875
|
+
say(`The film did not build; still playing the last one that did:
|
|
2876
|
+
${error instanceof Error ? error.message : String(error)}`);
|
|
2877
|
+
}
|
|
2878
|
+
});
|
|
2879
|
+
});
|
|
2880
|
+
return async () => {
|
|
2881
|
+
stop();
|
|
2882
|
+
await busy;
|
|
2883
|
+
await new Promise((done) => server.close(done));
|
|
2884
|
+
};
|
|
2885
|
+
}
|
|
2886
|
+
var VOICE_ENV = {
|
|
2887
|
+
minimax: { key: "MINIMAX_API_KEY", also: "MINIMAX_GROUP_ID if the account has one, MINIMAX_REGION=china (or MINIMAX_BASE_URL=https://api.minimaxi.com) for an account on minimaxi.com, MINIMAX_TTS_MODEL" },
|
|
2888
|
+
elevenlabs: { key: "ELEVENLABS_API_KEY", also: "ELEVENLABS_MODEL" },
|
|
2889
|
+
openai: { key: "OPENAI_API_KEY", also: "OPENAI_TTS_MODEL" },
|
|
2890
|
+
azure: { key: "AZURE_SPEECH_KEY", also: "AZURE_SPEECH_REGION, which it needs" }
|
|
2891
|
+
};
|
|
2892
|
+
function voiceSetup(kind, env = process.env) {
|
|
2893
|
+
const { key, also } = VOICE_ENV[kind];
|
|
2894
|
+
const value = env[key]?.trim();
|
|
2895
|
+
if (!value) throw new Error(`${VOICE_NAMES[kind]} speaks with the key in ${key} (and ${also}): set it in the environment oms runs in. oms reads keys from there only and writes them nowhere.`);
|
|
2896
|
+
switch (kind) {
|
|
2897
|
+
case "minimax": {
|
|
2898
|
+
const china = env.MINIMAX_REGION?.trim() === "china" || /(^|\/\/)api\.minimaxi\.com/.test(env.MINIMAX_BASE_URL?.trim() ?? "");
|
|
2899
|
+
return { kind, key: value, groupId: env.MINIMAX_GROUP_ID?.trim() || void 0, region: china ? "china" : "global", model: env.MINIMAX_TTS_MODEL?.trim() || void 0 };
|
|
2900
|
+
}
|
|
2901
|
+
case "elevenlabs":
|
|
2902
|
+
return { kind, key: value, model: env.ELEVENLABS_MODEL?.trim() || void 0 };
|
|
2903
|
+
case "openai":
|
|
2904
|
+
return { kind, key: value, model: env.OPENAI_TTS_MODEL?.trim() || void 0 };
|
|
2905
|
+
case "azure": {
|
|
2906
|
+
const region = env.AZURE_SPEECH_REGION?.trim();
|
|
2907
|
+
if (!region) throw new Error("Azure speaks in a region: set AZURE_SPEECH_REGION (as eastasia) beside AZURE_SPEECH_KEY.");
|
|
2908
|
+
return { kind, key: value, region };
|
|
2909
|
+
}
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
async function voice2(dir, scratch, onLine) {
|
|
2913
|
+
const { build: build2, open } = await opener(dir, scratch);
|
|
2914
|
+
if (!build2.ok) throw new Error(build2.errors.join("\n"));
|
|
2915
|
+
const film = await filmOf(open);
|
|
2916
|
+
if (!film.voice) throw new Error('The film names no voice: give its <Film> one, as voice="minimax:Chinese (Mandarin)_News_Anchor".');
|
|
2917
|
+
return voiceFilm(dir, film, async (kind) => voiceSetup(kind), await findFfmpeg(), onLine);
|
|
2918
|
+
}
|
|
2919
|
+
var TRANSCRIPTS = (0, import_node_path14.join)((0, import_node_os3.homedir)(), ".cache", "oms", "transcripts");
|
|
2920
|
+
async function record(dir, scratch, file, kind, onStep) {
|
|
2921
|
+
const by = kind ?? TRANSCRIBERS.find((k) => process.env[VOICE_ENV[k].key]?.trim());
|
|
2922
|
+
if (!by) throw new Error(`A recording is transcribed by MiniMax, OpenAI or ElevenLabs, with its key in ${TRANSCRIBERS.map((k) => VOICE_ENV[k].key).join(", ")}: set one in the environment oms runs in.`);
|
|
2923
|
+
if (!TRANSCRIBERS.includes(by)) throw new Error(`${VOICE_NAMES[by]} does not transcribe a recording here: use ${TRANSCRIBERS.join(", ")}.`);
|
|
2924
|
+
const { build: build2, open } = await opener(dir, scratch);
|
|
2925
|
+
if (!build2.ok) throw new Error(build2.errors.join("\n"));
|
|
2926
|
+
return voiceRecording(dir, await filmOf(open), file, voiceSetup(by), await findFfmpeg(), TRANSCRIPTS, onStep);
|
|
2927
|
+
}
|
|
2928
|
+
function recordingReport(done, file) {
|
|
2929
|
+
const quote = (text) => `"${text}"`;
|
|
2930
|
+
const change = ({ written, heard }) => !written ? `added ${quote(heard)}` : !heard ? `${quote(written)} not heard` : `${quote(written)} heard as ${quote(heard)}`;
|
|
2931
|
+
const by = VOICE_NAMES[done.transcriber];
|
|
2932
|
+
const report = [
|
|
2933
|
+
done.cached ? `Used the transcript kept from an earlier import of this take (by ${by}): nothing was paid.` : `Transcribed by ${by}.`,
|
|
2934
|
+
`Cut ${done.lines} line${done.lines === 1 ? "" : "s"} (${done.seconds.toFixed(1)} s of speech) from ${file} into voice/, ${Math.round(done.heard * 100)}% of the script heard as written.`
|
|
2935
|
+
];
|
|
2936
|
+
if (done.changed.length)
|
|
2937
|
+
report.push(
|
|
2938
|
+
"Read otherwise than written, and cut all the same: each caption shows the written words, timed by what was said.",
|
|
2939
|
+
...done.changed.map((line) => `- ${line.id}: ${line.changes.map(change).join("; ")}`),
|
|
2940
|
+
"A transcriber may spell a homophone or a number its own way: listen where unsure. For a caption that shows what was said, write the line as it was said and run this again (the transcript is kept, so nothing is paid)."
|
|
2941
|
+
);
|
|
2942
|
+
if (done.asides.length) report.push(`Said between the lines, and in no clip: ${done.asides.map((aside) => `${quote(aside.text)} at ${aside.at.toFixed(1)} s`).join(", ")}.`);
|
|
2943
|
+
report.push("Run oms check: each line now lasts as long as it was said.");
|
|
2944
|
+
return report;
|
|
2945
|
+
}
|
|
2946
|
+
var voices = (kind) => voicesOf(voiceSetup(kind));
|
|
2947
|
+
async function still(dir, scratch, seconds) {
|
|
2948
|
+
const { build: build2, open, where } = await opener(dir, scratch);
|
|
2949
|
+
if (!build2.ok) throw new Error(build2.errors.join("\n"));
|
|
2950
|
+
const stage = await open();
|
|
2951
|
+
try {
|
|
2952
|
+
if (!(seconds >= 0 && seconds < stage.film.seconds)) throw new Error(`Time must be in [0, ${stage.film.seconds}) seconds.`);
|
|
2953
|
+
return await stage.png(seconds).catch(async (error) => Promise.reject(await where(error)));
|
|
2954
|
+
} finally {
|
|
2955
|
+
await stage.close();
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
2959
|
+
0 && (module.exports = {
|
|
2960
|
+
OFL,
|
|
2961
|
+
VOICE_ENV,
|
|
2962
|
+
check,
|
|
2963
|
+
effectsTrack,
|
|
2964
|
+
motionWords,
|
|
2965
|
+
pack,
|
|
2966
|
+
parseCues,
|
|
2967
|
+
player,
|
|
2968
|
+
preview,
|
|
2969
|
+
record,
|
|
2970
|
+
recordingReport,
|
|
2971
|
+
render,
|
|
2972
|
+
renderStages,
|
|
2973
|
+
searchMotions,
|
|
2974
|
+
still,
|
|
2975
|
+
takeFont,
|
|
2976
|
+
useMotion,
|
|
2977
|
+
voice,
|
|
2978
|
+
voiceSetup,
|
|
2979
|
+
voices
|
|
2980
|
+
});
|