drone-path 0.13.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/README.md +20 -74
  2. package/THIRD-PARTY-NOTICES.md +3 -82
  3. package/bin/drone-path.mjs +0 -0
  4. package/dist/archive-cli.d.ts +1 -0
  5. package/dist/archive-cli.js +50 -0
  6. package/dist/archive-query-cli.d.ts +3 -0
  7. package/dist/archive-query-cli.js +128 -0
  8. package/dist/cli.d.ts +14 -0
  9. package/dist/cli.js +19 -12
  10. package/dist/version.d.ts +1 -0
  11. package/package.json +22 -68
  12. package/CHANGELOG.md +0 -349
  13. package/app/ipc.d.mts +0 -44
  14. package/app/ipc.mjs +0 -237
  15. package/app/main.mjs +0 -369
  16. package/app/preload.cjs +0 -36
  17. package/app/update-policy.d.mts +0 -6
  18. package/app/update-policy.mjs +0 -6
  19. package/app/update.d.mts +0 -10
  20. package/app/update.mjs +0 -54
  21. package/dist/appassets.js +0 -35
  22. package/dist/apppaths.js +0 -20
  23. package/dist/appsession.js +0 -121
  24. package/dist/appstate.js +0 -101
  25. package/dist/assets.js +0 -60
  26. package/dist/buildinfo.js +0 -64
  27. package/dist/cammeta-decode.js +0 -237
  28. package/dist/cammeta.js +0 -92
  29. package/dist/changeset-gate.js +0 -39
  30. package/dist/config.js +0 -631
  31. package/dist/configfile.js +0 -86
  32. package/dist/decimate.js +0 -84
  33. package/dist/desktop-i18n/generated/catalogs.js +0 -1230
  34. package/dist/desktop-i18n/messages.js +0 -47
  35. package/dist/errors.js +0 -34
  36. package/dist/exec-tool.js +0 -13
  37. package/dist/exportjob.js +0 -90
  38. package/dist/ffmpeg-tools.js +0 -56
  39. package/dist/ffmpeg.js +0 -98
  40. package/dist/frametime.js +0 -32
  41. package/dist/geo.js +0 -60
  42. package/dist/logging.js +0 -1
  43. package/dist/manual/anchors.js +0 -17
  44. package/dist/manual/build.js +0 -67
  45. package/dist/manual/cliref.js +0 -34
  46. package/dist/manual/links.js +0 -59
  47. package/dist/manual/markdown.js +0 -98
  48. package/dist/manual/model.js +0 -1
  49. package/dist/manual/module.js +0 -5
  50. package/dist/manual/nav.js +0 -11
  51. package/dist/manual/reference.js +0 -18
  52. package/dist/paths.js +0 -16
  53. package/dist/pipeline.js +0 -402
  54. package/dist/plan.js +0 -106
  55. package/dist/png.js +0 -32
  56. package/dist/protobuf-wire.js +0 -102
  57. package/dist/range.js +0 -50
  58. package/dist/recordings.js +0 -55
  59. package/dist/render-page.js +0 -85
  60. package/dist/render.js +0 -268
  61. package/dist/renderer/boot.js +0 -7
  62. package/dist/renderer/dom.js +0 -179
  63. package/dist/renderer/framemath.js +0 -30
  64. package/dist/renderer/scene.js +0 -388
  65. package/dist/renderer/theme.js +0 -82
  66. package/dist/renderer/tilesources.js +0 -38
  67. package/dist/renderer/trail.js +0 -42
  68. package/dist/restyle.js +0 -16
  69. package/dist/serve.js +0 -27
  70. package/dist/srt.js +0 -98
  71. package/dist/telemetry-json-schema.js +0 -18
  72. package/dist/telemetry-json.js +0 -126
  73. package/dist/telemetry-math.js +0 -267
  74. package/dist/telemetry-summary.js +0 -19
  75. package/dist/telemetry.js +0 -95
  76. package/dist/tilecache.js +0 -21
  77. package/dist/tiles.js +0 -155
  78. package/dist/track-format.js +0 -13
  79. package/dist/track-geojson.js +0 -44
  80. package/dist/track-gpx.js +0 -34
  81. package/dist/track-kml.js +0 -47
  82. package/dist/track-kmz.js +0 -68
  83. package/dist/track-write.js +0 -41
  84. package/dist/track.js +0 -79
package/dist/png.js DELETED
@@ -1,32 +0,0 @@
1
- import zlib from 'node:zlib';
2
- function pngChunk(type, data) {
3
- const len = Buffer.alloc(4);
4
- len.writeUInt32BE(data.length);
5
- const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
6
- const crc = Buffer.alloc(4);
7
- crc.writeUInt32BE(zlib.crc32(body));
8
- return Buffer.concat([len, body, crc]);
9
- }
10
- export function solidPng(hexColor, size = 256) {
11
- const r = Number.parseInt(hexColor.slice(1, 3), 16);
12
- const g = Number.parseInt(hexColor.slice(3, 5), 16);
13
- const b = Number.parseInt(hexColor.slice(5, 7), 16);
14
- const row = Buffer.alloc(1 + size * 3);
15
- for (let x = 0; x < size; x++) {
16
- row[1 + x * 3] = r;
17
- row[2 + x * 3] = g;
18
- row[3 + x * 3] = b;
19
- }
20
- const raw = Buffer.concat(Array.from({ length: size }, () => row));
21
- const ihdr = Buffer.alloc(13);
22
- ihdr.writeUInt32BE(size, 0);
23
- ihdr.writeUInt32BE(size, 4);
24
- ihdr[8] = 8; // bit depth
25
- ihdr[9] = 2; // color type RGB
26
- return Buffer.concat([
27
- Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
28
- pngChunk('IHDR', ihdr),
29
- pngChunk('IDAT', zlib.deflateSync(raw)),
30
- pngChunk('IEND', Buffer.alloc(0)),
31
- ]);
32
- }
@@ -1,102 +0,0 @@
1
- const MAX_VARINT_BYTES = 10;
2
- function readVarint(buf, pos, end) {
3
- let value = 0n;
4
- let shift = 0n;
5
- let i = pos;
6
- while (i < end && i - pos < MAX_VARINT_BYTES) {
7
- const byte = buf[i++];
8
- value |= BigInt(byte & 0x7f) << shift;
9
- if ((byte & 0x80) === 0)
10
- return { value, next: i };
11
- shift += 7n;
12
- }
13
- return null;
14
- }
15
- function signedVarint(value) {
16
- return Number(BigInt.asIntN(64, value));
17
- }
18
- export function parseProtoFields(buf, start, end) {
19
- const fields = new Map();
20
- let pos = start;
21
- while (pos < end) {
22
- const key = readVarint(buf, pos, end);
23
- if (!key)
24
- break;
25
- const fieldNumber = Number(key.value >> 3n);
26
- const wireType = Number(key.value & 7n);
27
- pos = key.next;
28
- const field = readValue(buf, pos, end, wireType, fieldNumber);
29
- if (!field)
30
- break; // groups / unknown wire types / truncation: stop this level
31
- pos = field.next;
32
- pushField(fields, fieldNumber, field.protoField);
33
- }
34
- return fields;
35
- }
36
- function readValue(buf, pos, end, wireType, fieldNumber) {
37
- const base = { wireType, fieldNumber };
38
- if (wireType === 0) {
39
- const v = readVarint(buf, pos, end);
40
- return v && { protoField: { ...base, varintValue: v.value }, next: v.next };
41
- }
42
- if (wireType === 1) {
43
- if (pos + 8 > end)
44
- return null;
45
- return {
46
- protoField: { ...base, doubleValue: buf.readDoubleLE(pos) },
47
- next: pos + 8,
48
- };
49
- }
50
- if (wireType === 2) {
51
- const len = readVarint(buf, pos, end);
52
- if (!len)
53
- return null;
54
- const payloadStart = len.next;
55
- const n = Number(len.value);
56
- if (payloadStart + n > end)
57
- return null;
58
- return {
59
- protoField: { ...base, bytesSpan: [payloadStart, payloadStart + n] },
60
- next: payloadStart + n,
61
- };
62
- }
63
- if (wireType === 5) {
64
- if (pos + 4 > end)
65
- return null;
66
- return {
67
- protoField: { ...base, floatValue: buf.readFloatLE(pos) },
68
- next: pos + 4,
69
- };
70
- }
71
- return null;
72
- }
73
- function pushField(fields, fieldNumber, field) {
74
- const existing = fields.get(fieldNumber);
75
- if (existing)
76
- existing.push(field);
77
- else
78
- fields.set(fieldNumber, [field]);
79
- }
80
- export function firstSubMessage(buf, fields, fieldNumber) {
81
- const field = fields.get(fieldNumber)?.[0];
82
- if (!field?.bytesSpan)
83
- return null;
84
- const [start, end] = field.bytesSpan;
85
- return parseProtoFields(buf, start, end);
86
- }
87
- export function firstVarintField(fields, fieldNumber) {
88
- const value = fields.get(fieldNumber)?.[0]?.varintValue;
89
- return value !== undefined ? signedVarint(value) : null;
90
- }
91
- export function firstFloatField(fields, fieldNumber) {
92
- const value = fields.get(fieldNumber)?.[0]?.floatValue;
93
- return value ?? null;
94
- }
95
- export function firstDoubleField(fields, fieldNumber) {
96
- const value = fields.get(fieldNumber)?.[0]?.doubleValue;
97
- return value ?? null;
98
- }
99
- export function firstStringField(buf, fields, fieldNumber) {
100
- const span = fields.get(fieldNumber)?.[0]?.bytesSpan;
101
- return span ? buf.toString('utf8', span[0], span[1]) : null;
102
- }
package/dist/range.js DELETED
@@ -1,50 +0,0 @@
1
- export function parseByteRange(header, size) {
2
- if (header === undefined)
3
- return null;
4
- const text = Array.isArray(header) ? header[0] : header;
5
- const m = /^bytes=(\d*)-(\d*)$/.exec(text.trim());
6
- if (!m)
7
- return null;
8
- const from = m[1];
9
- const to = m[2];
10
- if (from === '' && to === '')
11
- return null;
12
- let start;
13
- let end;
14
- if (from === '') {
15
- const suffix = Number(to);
16
- if (!Number.isFinite(suffix) || suffix <= 0)
17
- return 'unsatisfiable';
18
- start = Math.max(0, size - suffix);
19
- end = size - 1;
20
- }
21
- else {
22
- start = Number(from);
23
- end = to === '' ? size - 1 : Number(to);
24
- if (!Number.isFinite(start) || !Number.isFinite(end))
25
- return null;
26
- }
27
- if (start > end || start >= size)
28
- return 'unsatisfiable';
29
- return { start, end: Math.min(end, size - 1) };
30
- }
31
- export function planByteRange(header, size, mime) {
32
- const range = parseByteRange(header, size);
33
- if (range === 'unsatisfiable') {
34
- return {
35
- status: 416,
36
- headers: { 'Content-Range': `bytes */${size}`, 'Content-Type': 'text/plain' },
37
- body: 'range not satisfiable',
38
- };
39
- }
40
- const headers = {
41
- 'Content-Type': mime,
42
- 'Accept-Ranges': 'bytes',
43
- 'Cache-Control': 'no-store',
44
- 'Content-Length': String(range === null ? size : range.end - range.start + 1),
45
- };
46
- if (range === null)
47
- return { status: 200, headers };
48
- headers['Content-Range'] = `bytes ${range.start}-${range.end}/${size}`;
49
- return { status: 206, headers, span: range };
50
- }
@@ -1,55 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- export function isRecordingName(name) {
4
- return name.toLowerCase().endsWith('.mp4');
5
- }
6
- export function videoBaseName(filePath) {
7
- return path.basename(filePath).replace(/\.[^.]+$/, '');
8
- }
9
- export function findSrtSidecar(videoPath) {
10
- const dir = path.dirname(videoPath);
11
- const base = videoBaseName(videoPath);
12
- for (const f of fs.readdirSync(dir)) {
13
- if (f.toLowerCase() === `${base.toLowerCase()}.srt`) {
14
- return path.join(dir, f);
15
- }
16
- }
17
- return null;
18
- }
19
- function listMp4(dir, recurse) {
20
- const found = [];
21
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
22
- const full = path.join(dir, entry.name);
23
- if (entry.isDirectory()) {
24
- if (recurse)
25
- found.push(...listMp4(full, recurse));
26
- }
27
- else if (entry.isFile() && isRecordingName(entry.name)) {
28
- found.push(full);
29
- }
30
- }
31
- return found;
32
- }
33
- export function collectRecordings(inputs, opts) {
34
- const files = [];
35
- for (const item of inputs) {
36
- const full = path.resolve(item);
37
- if (!fs.existsSync(full))
38
- throw new Error(`input not found: ${item}`);
39
- const st = fs.statSync(full);
40
- if (st.isDirectory()) {
41
- files.push(...listMp4(full, opts.recurse));
42
- }
43
- else if (isRecordingName(full)) {
44
- files.push(full);
45
- }
46
- else {
47
- throw new Error(`not an .mp4 recording: ${full}`);
48
- }
49
- }
50
- const unique = [...new Set(files.map((f) => path.resolve(f)))].sort((a, b) => a.localeCompare(b, 'en'));
51
- if (unique.length === 0) {
52
- throw new Error('no .mp4 recordings found in the given input');
53
- }
54
- return unique;
55
- }
@@ -1,85 +0,0 @@
1
- import { hasAltitude, resolveHudLayout } from './config.js';
2
- import { decimateTrack } from './decimate.js';
3
- import { unproject } from './geo.js';
4
- import { planIntroOutroFrames, planView } from './plan.js';
5
- import { TILE_SOURCES } from './renderer/tilesources.js';
6
- export function planPageOpts(opts) {
7
- const { bbox, width, height, config, source, frames, planned, previous } = opts;
8
- const overview = planned?.overview ?? planView(bbox, width, height, config);
9
- const introOutro = planned?.introOutro ?? planIntroOutroFrames(config, source);
10
- const hud = planned?.hud ?? resolveHudLayout(config.hud, hasAltitude(frames.alt));
11
- const decimated = previous && previous.zoom === overview.zoom
12
- ? previous.decimated
13
- : decimateTrack(frames.lat, frames.lon, overview.zoom);
14
- return {
15
- width,
16
- height,
17
- style: config.style,
18
- trailColor: config.trailColor,
19
- view: config.view,
20
- center: unproject(overview.centerPx.x, overview.centerPx.y, overview.zoom),
21
- zoom: overview.zoom,
22
- attribution: TILE_SOURCES[config.style].attribution,
23
- introN: introOutro.introN,
24
- outroN: introOutro.outroN,
25
- lat: frames.lat,
26
- lon: frames.lon,
27
- alt: frames.alt,
28
- speed: frames.speed,
29
- headingDeg: frames.headingDeg,
30
- hud,
31
- decimated,
32
- };
33
- }
34
- export function buildSceneData(opts, tileBase) {
35
- const { width, height, style, trailColor, view, center, zoom, attribution, lat, lon, alt, speed, headingDeg, hud, decimated, introN = 0, outroN = 0, } = opts;
36
- return {
37
- style,
38
- trailColor,
39
- tileUrl: tileBase + '/' + style + '/{z}/{x}/{y}.png',
40
- view,
41
- width,
42
- height,
43
- zoom,
44
- center: { lat: center.lat, lon: center.lon },
45
- attribution,
46
- introN,
47
- outroN,
48
- lat, lon, alt, speed, headingDeg,
49
- hud,
50
- trailLat: decimated.lat,
51
- trailLon: decimated.lon,
52
- trailFrame: decimated.frame,
53
- };
54
- }
55
- function bootScript(dataJson) {
56
- return `import { bootScene } from '/renderer/boot.js';
57
- var D = window.__DATA = ${dataJson};
58
- var scene = bootScene(document.getElementById('scene-host'), D, window.L);
59
- window.__setFrame = function (i) { return scene.setFrame(i); };
60
- window.__relayout = function () { scene.relayout(); };
61
- scene.ready.then(function () { window.__READY = true; });`;
62
- }
63
- export function buildPageHtml(opts) {
64
- const data = buildSceneData(opts, '/tiles');
65
- // "</" must not appear verbatim: the JSON is inlined into a <script> tag.
66
- const json = JSON.stringify(data).replace(/</g, '\\u003c');
67
- return `<!DOCTYPE html>
68
- <html>
69
- <head>
70
- <meta charset="utf-8">
71
- <title>flight map</title>
72
- <link rel="stylesheet" href="/leaflet/leaflet.css">
73
- <style>
74
- html, body { margin: 0; padding: 0; overflow: hidden; background: ${TILE_SOURCES[opts.style].bg}; }
75
- </style>
76
- </head>
77
- <body>
78
- <div id="scene-host"></div>
79
- <script src="/leaflet/leaflet.js"></script>
80
- <script type="module">
81
- ${bootScript(json)}
82
- </script>
83
- </body>
84
- </html>`;
85
- }
package/dist/render.js DELETED
@@ -1,268 +0,0 @@
1
- import http from 'node:http';
2
- import { spawn } from 'node:child_process';
3
- import { once } from 'node:events';
4
- import { MIME } from './assets.js';
5
- import { ERR_RENDER_CANCELED, errorMessage } from './errors.js';
6
- import { RENDERER_DIR, serveAsset } from './serve.js';
7
- const PAGE_LOAD_TIMEOUT_MS = 60000;
8
- const SCREENSHOT_TIMEOUT_MS = 60000;
9
- function startServer({ html, style, tileCache, }) {
10
- const server = http.createServer((req, res) => {
11
- let url;
12
- try {
13
- url = decodeURIComponent((req.url ?? '/').split('?')[0]);
14
- }
15
- catch {
16
- res.writeHead(400, { 'Content-Type': 'text/plain' });
17
- res.end('bad request');
18
- return;
19
- }
20
- if (url === '/' || url === '/index.html') {
21
- res.writeHead(200, { 'Content-Type': MIME['.html'] });
22
- res.end(html);
23
- return;
24
- }
25
- if (serveAsset(url, res, { style, tileCache, rendererDir: RENDERER_DIR }))
26
- return;
27
- res.writeHead(404, { 'Content-Type': 'text/plain' });
28
- res.end('not found');
29
- });
30
- return new Promise((resolve) => {
31
- server.listen(0, '127.0.0.1', () => {
32
- const addr = server.address();
33
- const port = addr && typeof addr === 'object' ? addr.port : 0;
34
- resolve({ server, url: `http://127.0.0.1:${port}/` });
35
- });
36
- });
37
- }
38
- async function launchBrowser(log, browserPath) {
39
- const { chromium } = await import('playwright-core');
40
- const attempts = [];
41
- if (browserPath)
42
- attempts.push({ executablePath: browserPath });
43
- attempts.push({ channel: 'chrome' }, { channel: 'msedge' }, {});
44
- const attemptErrors = [];
45
- for (const opt of attempts) {
46
- try {
47
- const browser = await chromium.launch({ headless: true, ...opt });
48
- log(`browser: ${opt.executablePath ?? opt.channel ?? 'playwright-registry'}`);
49
- return browser;
50
- }
51
- catch (e) {
52
- attemptErrors.push(e);
53
- }
54
- }
55
- throw new Error(`could not launch a Chromium browser (tried explicit path, channel=chrome, channel=msedge, playwright registry): ${errorMessage(attemptErrors[attemptErrors.length - 1])}. ` +
56
- 'Install Google Chrome or Microsoft Edge, run "npx playwright install chromium", ' +
57
- 'or pass --browser <path>.', { cause: new AggregateError(attemptErrors, 'all browser launch attempts failed') });
58
- }
59
- // x265's CRF scale sits ~5 points above x264's for the same perceived quality.
60
- const CRF = {
61
- h264: { 'near-lossless': 16, high: 18, medium: 21, low: 26 },
62
- h265: { 'near-lossless': 20, high: 22, medium: 25, low: 30 },
63
- };
64
- function spawnEncoder(ffmpeg, fpsStr, encode, outPath) {
65
- // h265 gets hvc1: the ffmpeg-default hev1 tag is refused by QuickTime and some NLEs.
66
- const codecArgs = encode.codec === 'h265' ? ['-c:v', 'libx265', '-tag:v', 'hvc1'] : ['-c:v', 'libx264'];
67
- const ffmpegProcess = spawn(ffmpeg, [
68
- '-hide_banner', '-loglevel', 'error', '-y',
69
- '-f', 'image2pipe', '-framerate', fpsStr, '-i', '-',
70
- ...codecArgs,
71
- '-preset', encode.preset,
72
- '-crf', String(CRF[encode.codec][encode.quality]),
73
- '-pix_fmt', 'yuv420p', '-r', fpsStr,
74
- '-movflags', '+faststart', outPath,
75
- ], { stdio: ['pipe', 'ignore', 'pipe'] });
76
- let stderr = '';
77
- ffmpegProcess.stderr?.on('data', (d) => {
78
- stderr += d.toString();
79
- });
80
- // ffmpeg's stdin must never surface an unhandled 'error' (EPIPE on early exit); a drain-waiter must wake when the encoder dies.
81
- const closed = new Promise((resolve) => {
82
- ffmpegProcess.once('close', (code) => resolve(code));
83
- });
84
- const stopped = new Promise((resolve) => {
85
- ffmpegProcess.stdin.on('error', (e) => resolve(`ffmpeg stdin error: ${e.message}`));
86
- void closed.then((code) => resolve(`ffmpeg exited with code ${code}`));
87
- });
88
- return {
89
- stdin: ffmpegProcess.stdin,
90
- stopped,
91
- closed,
92
- stderrText: () => stderr,
93
- kill: () => ffmpegProcess.kill(),
94
- };
95
- }
96
- class OrderedFrameStream {
97
- encoder;
98
- pending = new Map();
99
- nextIndex = 0;
100
- constructor(encoder) {
101
- this.encoder = encoder;
102
- }
103
- async submit(index, frame) {
104
- this.pending.set(index, frame);
105
- await this.flushReady();
106
- }
107
- async flushReady() {
108
- while (this.pending.has(this.nextIndex)) {
109
- const frame = this.pending.get(this.nextIndex);
110
- this.pending.delete(this.nextIndex);
111
- if (!this.encoder.stdin.write(frame)) {
112
- const woke = await Promise.race([
113
- once(this.encoder.stdin, 'drain').then(() => 'drain'),
114
- this.encoder.stopped,
115
- ]);
116
- if (woke !== 'drain') {
117
- const stderr = this.encoder.stderrText().trim();
118
- throw new Error(`${woke}${stderr ? `: ${stderr}` : ''}`);
119
- }
120
- }
121
- this.nextIndex++;
122
- }
123
- }
124
- end() {
125
- this.encoder.stdin.end();
126
- }
127
- }
128
- function screenshotOptions(capture) {
129
- return capture === 'jpeg'
130
- ? {
131
- type: 'jpeg',
132
- quality: 95,
133
- animations: 'disabled',
134
- timeout: SCREENSHOT_TIMEOUT_MS,
135
- }
136
- : {
137
- type: 'png',
138
- animations: 'disabled',
139
- timeout: SCREENSHOT_TIMEOUT_MS,
140
- };
141
- }
142
- async function captureFrame(run, loop, page, idx) {
143
- const evalStart = Date.now();
144
- await page.evaluate((frame) => globalThis.__setFrame(frame), run.frameStart + idx);
145
- run.timing.evalMs += Date.now() - evalStart;
146
- const captureStart = Date.now();
147
- const buf = await page.screenshot(screenshotOptions(run.capture));
148
- run.timing.captureMs += Date.now() - captureStart;
149
- const done = ++loop.capturesDone;
150
- const emitStart = Date.now();
151
- await run.stream.submit(idx, buf);
152
- run.timing.emitMs += Date.now() - emitStart;
153
- if (done % 100 === 0 || done === run.frames) {
154
- run.log(`frames: ${done}/${run.frames} captured`);
155
- run.onCapture?.({ done, total: run.frames });
156
- }
157
- }
158
- async function workerLoop(run, loop, workerId) {
159
- const page = await run.active.newPage({
160
- viewport: { width: run.width, height: run.height },
161
- deviceScaleFactor: 1,
162
- });
163
- try {
164
- await page.goto(run.url, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT_MS });
165
- await page.waitForFunction('window.__READY === true', null, { timeout: PAGE_LOAD_TIMEOUT_MS });
166
- for (;;) {
167
- if (loop.failed)
168
- return;
169
- if (run.signal?.aborted)
170
- throw new Error(ERR_RENDER_CANCELED);
171
- const idx = loop.cursor++;
172
- if (idx >= run.frames)
173
- break;
174
- await captureFrame(run, loop, page, idx);
175
- }
176
- }
177
- finally {
178
- await page.close().catch(() => { });
179
- }
180
- run.log(`worker ${workerId} done`);
181
- }
182
- async function runWorkers(run, workerCount) {
183
- const loop = { cursor: 0, capturesDone: 0, failed: false };
184
- const settled = await Promise.allSettled(Array.from({ length: workerCount }, (_, i) => workerLoop(run, loop, i + 1).catch((e) => {
185
- loop.failed = true;
186
- throw e;
187
- })));
188
- const rejected = settled.find((r) => r.status === 'rejected');
189
- if (rejected)
190
- throw rejected.reason;
191
- }
192
- async function finishEncode(encoder, stream, log, outPath) {
193
- await stream.flushReady();
194
- stream.end();
195
- const code = await encoder.closed;
196
- if (code !== 0) {
197
- throw new Error(`ffmpeg exited with code ${code}: ${encoder.stderrText().trim()}`);
198
- }
199
- log(`encoded: ${outPath}`);
200
- }
201
- function formatProfile(profile, workerCount) {
202
- return (`profile: eval=${(profile.evalMs / 1000).toFixed(1)}s capture=${(profile.captureMs / 1000).toFixed(1)}s ` +
203
- `encode-backpressure=${(profile.emitMs / 1000).toFixed(1)}s (summed over ${workerCount} workers)`);
204
- }
205
- async function captureAndEncode(active, env) {
206
- const { ctx, url, timing, workerCount } = env;
207
- const { fpsStr, codec, quality, preset, outPath, signal, log, tools } = ctx;
208
- const encoder = spawnEncoder(tools.ffmpeg, fpsStr, { codec, quality, preset }, outPath);
209
- const killOnAbort = () => encoder.kill();
210
- signal?.addEventListener('abort', killOnAbort, { once: true });
211
- const stream = new OrderedFrameStream(encoder);
212
- try {
213
- await runWorkers({ ...ctx, active, url, stream, timing }, workerCount);
214
- await finishEncode(encoder, stream, log, outPath);
215
- }
216
- catch (e) {
217
- encoder.kill();
218
- throw e;
219
- }
220
- finally {
221
- signal?.removeEventListener('abort', killOnAbort);
222
- }
223
- }
224
- function reportProfile(env) {
225
- const { ctx, timing, workerCount } = env;
226
- const profile = {
227
- evalMs: Math.round(timing.evalMs),
228
- captureMs: Math.round(timing.captureMs),
229
- emitMs: Math.round(timing.emitMs),
230
- };
231
- ctx.log(formatProfile(profile, workerCount));
232
- return { profile };
233
- }
234
- export async function renderVideo(opts) {
235
- const { html, style, tileCache, width, height, frames, fpsStr, workers, outPath, log = () => { }, browserPath = null, tools, capture = 'jpeg', codec = 'h264', quality = 'high', preset = 'medium', frameStart = 0, signal, onCapture, } = opts;
236
- const workerCount = Math.max(1, Math.min(workers, frames));
237
- const ctx = {
238
- width,
239
- height,
240
- frames,
241
- frameStart,
242
- fpsStr,
243
- outPath,
244
- capture,
245
- codec,
246
- quality,
247
- preset,
248
- signal,
249
- log,
250
- onCapture,
251
- tools,
252
- };
253
- if (signal?.aborted)
254
- throw new Error(ERR_RENDER_CANCELED);
255
- const timing = { evalMs: 0, captureMs: 0, emitMs: 0 };
256
- const { server, url } = await startServer({ html, style, tileCache });
257
- const env = { ctx, url, timing, workerCount };
258
- let browser = null;
259
- try {
260
- browser = await launchBrowser(log, browserPath);
261
- await captureAndEncode(browser, env);
262
- }
263
- finally {
264
- await browser?.close().catch(() => { });
265
- server.close();
266
- }
267
- return reportProfile(env);
268
- }
@@ -1,7 +0,0 @@
1
- import { createScene } from './scene.js';
2
- export function bootScene(host, data, L, opts) {
3
- const scene = createScene(host, data, { L, hudHost: opts?.hudHost });
4
- // The pane size may only settle after creation; re-measure post-layout.
5
- requestAnimationFrame(() => scene.relayout());
6
- return scene;
7
- }