drone-path 0.0.0 → 0.8.1
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/CHANGELOG.md +186 -0
- package/LICENSE +21 -0
- package/README.md +83 -6
- package/THIRD-PARTY-NOTICES.md +77 -0
- package/app/main.mjs +496 -0
- package/app/preload.cjs +31 -0
- package/app/update-policy.d.mts +6 -0
- package/app/update-policy.mjs +6 -0
- package/app/update.d.mts +10 -0
- package/app/update.mjs +54 -0
- package/bin/drone-path.mjs +5 -0
- package/dist/appassets.js +44 -0
- package/dist/apppaths.js +28 -0
- package/dist/appsession.js +128 -0
- package/dist/appstate.js +109 -0
- package/dist/assets.js +67 -0
- package/dist/cammeta.js +292 -0
- package/dist/changeset-gate.js +46 -0
- package/dist/cli.js +156 -0
- package/dist/config.js +469 -0
- package/dist/configfile.js +81 -0
- package/dist/decimate.js +94 -0
- package/dist/errors.js +4 -0
- package/dist/exportjob.js +106 -0
- package/dist/ff.js +121 -0
- package/dist/fftools.js +65 -0
- package/dist/geo.js +70 -0
- package/dist/inputs.js +59 -0
- package/dist/manual/anchors.js +23 -0
- package/dist/manual/build.js +78 -0
- package/dist/manual/cliref.js +36 -0
- package/dist/manual/links.js +76 -0
- package/dist/manual/markdown.js +101 -0
- package/dist/manual/model.js +4 -0
- package/dist/manual/module.js +8 -0
- package/dist/manual/nav.js +13 -0
- package/dist/manual/reference.js +26 -0
- package/dist/page.js +108 -0
- package/dist/paths.js +28 -0
- package/dist/plan.js +119 -0
- package/dist/png.js +52 -0
- package/dist/proto.js +102 -0
- package/dist/range.js +58 -0
- package/dist/render.js +408 -0
- package/dist/renderer/boot.js +7 -0
- package/dist/renderer/dom.js +132 -0
- package/dist/renderer/framemath.js +34 -0
- package/dist/renderer/leaflet.js +5 -0
- package/dist/renderer/scene.js +358 -0
- package/dist/renderer/theme.js +34 -0
- package/dist/renderer/tilesources.js +34 -0
- package/dist/renderer/trail.js +53 -0
- package/dist/restyle.js +24 -0
- package/dist/run.js +446 -0
- package/dist/serve.js +70 -0
- package/dist/srt.js +76 -0
- package/dist/summary.js +22 -0
- package/dist/telemetry-math.js +302 -0
- package/dist/telemetry.js +38 -0
- package/dist/tilecache.js +26 -0
- package/dist/tiles.js +241 -0
- package/dist/tracing.js +208 -0
- package/dist/version.js +3 -0
- package/package.json +94 -8
package/dist/proto.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Just enough of the format for the DJI DVTM messages: varint, fixed64,
|
|
2
|
+
// fixed32 and length-delimited fields, one nesting level at a time.
|
|
3
|
+
const MAX_VARINT_BYTES = 10;
|
|
4
|
+
function readVarint(buf, pos, end) {
|
|
5
|
+
let value = 0n;
|
|
6
|
+
let shift = 0n;
|
|
7
|
+
let i = pos;
|
|
8
|
+
while (i < end && i - pos < MAX_VARINT_BYTES) {
|
|
9
|
+
const byte = buf[i++];
|
|
10
|
+
value |= BigInt(byte & 0x7f) << shift;
|
|
11
|
+
if ((byte & 0x80) === 0)
|
|
12
|
+
return { value, next: i };
|
|
13
|
+
shift += 7n;
|
|
14
|
+
}
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
/** Interpret a 64-bit varint as a signed integer. */
|
|
18
|
+
function signedVarint(value) {
|
|
19
|
+
return Number(BigInt.asIntN(64, value));
|
|
20
|
+
}
|
|
21
|
+
export function parseProtoFields(buf, start, end) {
|
|
22
|
+
const fields = new Map();
|
|
23
|
+
let pos = start;
|
|
24
|
+
while (pos < end) {
|
|
25
|
+
const key = readVarint(buf, pos, end);
|
|
26
|
+
if (!key)
|
|
27
|
+
break;
|
|
28
|
+
const fieldNumber = Number(key.value >> 3n);
|
|
29
|
+
const wireType = Number(key.value & 7n);
|
|
30
|
+
pos = key.next;
|
|
31
|
+
const field = readValue(buf, pos, end, wireType, fieldNumber);
|
|
32
|
+
if (!field)
|
|
33
|
+
break; // groups / unknown wire types / truncation: stop this level
|
|
34
|
+
pos = field.next;
|
|
35
|
+
pushField(fields, fieldNumber, field.protoField);
|
|
36
|
+
}
|
|
37
|
+
return fields;
|
|
38
|
+
}
|
|
39
|
+
function readValue(buf, pos, end, wireType, fieldNumber) {
|
|
40
|
+
const base = { wireType, fieldNumber };
|
|
41
|
+
if (wireType === 0) {
|
|
42
|
+
const v = readVarint(buf, pos, end);
|
|
43
|
+
return v && { protoField: { ...base, varintValue: v.value }, next: v.next };
|
|
44
|
+
}
|
|
45
|
+
if (wireType === 1) {
|
|
46
|
+
if (pos + 8 > end)
|
|
47
|
+
return null;
|
|
48
|
+
return {
|
|
49
|
+
protoField: { ...base, doubleValue: buf.readDoubleLE(pos) },
|
|
50
|
+
next: pos + 8,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
if (wireType === 2) {
|
|
54
|
+
const len = readVarint(buf, pos, end);
|
|
55
|
+
if (!len)
|
|
56
|
+
return null;
|
|
57
|
+
const payloadStart = len.next;
|
|
58
|
+
const n = Number(len.value);
|
|
59
|
+
if (payloadStart + n > end)
|
|
60
|
+
return null;
|
|
61
|
+
return {
|
|
62
|
+
protoField: { ...base, bytesSpan: [payloadStart, payloadStart + n] },
|
|
63
|
+
next: payloadStart + n,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
if (wireType === 5) {
|
|
67
|
+
if (pos + 4 > end)
|
|
68
|
+
return null;
|
|
69
|
+
return {
|
|
70
|
+
protoField: { ...base, floatValue: buf.readFloatLE(pos) },
|
|
71
|
+
next: pos + 4,
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
return null;
|
|
75
|
+
}
|
|
76
|
+
function pushField(fields, fieldNumber, field) {
|
|
77
|
+
const existing = fields.get(fieldNumber);
|
|
78
|
+
if (existing)
|
|
79
|
+
existing.push(field);
|
|
80
|
+
else
|
|
81
|
+
fields.set(fieldNumber, [field]);
|
|
82
|
+
}
|
|
83
|
+
/** Sub-messages are length-delimited fields; only the first occurrence is decoded. */
|
|
84
|
+
export function subMessage(buf, fields, fieldNumber) {
|
|
85
|
+
const field = fields.get(fieldNumber)?.[0];
|
|
86
|
+
if (!field?.bytesSpan)
|
|
87
|
+
return null;
|
|
88
|
+
const [start, end] = field.bytesSpan;
|
|
89
|
+
return parseProtoFields(buf, start, end);
|
|
90
|
+
}
|
|
91
|
+
export function firstVarint(fields, fieldNumber) {
|
|
92
|
+
const value = fields.get(fieldNumber)?.[0]?.varintValue;
|
|
93
|
+
return value !== undefined ? signedVarint(value) : null;
|
|
94
|
+
}
|
|
95
|
+
export function firstFloat(fields, fieldNumber) {
|
|
96
|
+
const value = fields.get(fieldNumber)?.[0]?.floatValue;
|
|
97
|
+
return value ?? null;
|
|
98
|
+
}
|
|
99
|
+
export function firstDouble(fields, fieldNumber) {
|
|
100
|
+
const value = fields.get(fieldNumber)?.[0]?.doubleValue;
|
|
101
|
+
return value ?? null;
|
|
102
|
+
}
|
package/dist/range.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// HTTP byte-range parsing and response planning (RFC 7233) shared by the
|
|
2
|
+
// headless render server and the app's custom-scheme handler.
|
|
3
|
+
// Malformed range headers are ignored (full response); only syntactically
|
|
4
|
+
// valid but unsatisfiable ranges earn a 416.
|
|
5
|
+
export function parseRange(header, size) {
|
|
6
|
+
if (header === undefined)
|
|
7
|
+
return null;
|
|
8
|
+
const text = Array.isArray(header) ? header[0] : header;
|
|
9
|
+
const m = /^bytes=(\d*)-(\d*)$/.exec(text.trim());
|
|
10
|
+
if (!m)
|
|
11
|
+
return null;
|
|
12
|
+
const from = m[1];
|
|
13
|
+
const to = m[2];
|
|
14
|
+
if (from === '' && to === '')
|
|
15
|
+
return null;
|
|
16
|
+
let start;
|
|
17
|
+
let end;
|
|
18
|
+
if (from === '') {
|
|
19
|
+
const suffix = Number(to);
|
|
20
|
+
if (!Number.isFinite(suffix) || suffix <= 0)
|
|
21
|
+
return 'unsatisfiable';
|
|
22
|
+
start = Math.max(0, size - suffix);
|
|
23
|
+
end = size - 1;
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
start = Number(from);
|
|
27
|
+
end = to === '' ? size - 1 : Number(to);
|
|
28
|
+
if (!Number.isFinite(start) || !Number.isFinite(end))
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
if (start > end || start >= size)
|
|
32
|
+
return 'unsatisfiable';
|
|
33
|
+
return { start, end: Math.min(end, size - 1) };
|
|
34
|
+
}
|
|
35
|
+
// Everything both transports compute by hand for one Range request: status,
|
|
36
|
+
// the response headers, and the byte span (or 416 body) to send. Only the
|
|
37
|
+
// transport write is left to the caller.
|
|
38
|
+
export function rangePlan(header, size, mime) {
|
|
39
|
+
const range = parseRange(header, size);
|
|
40
|
+
if (range === 'unsatisfiable') {
|
|
41
|
+
return {
|
|
42
|
+
status: 416,
|
|
43
|
+
headers: { 'Content-Range': `bytes */${size}`, 'Content-Type': 'text/plain' },
|
|
44
|
+
body: 'range not satisfiable',
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
const headers = {
|
|
48
|
+
'Content-Type': mime,
|
|
49
|
+
'Accept-Ranges': 'bytes',
|
|
50
|
+
// A URL-keyed cache must never replay stale bytes from this live local file.
|
|
51
|
+
'Cache-Control': 'no-store',
|
|
52
|
+
'Content-Length': String(range === null ? size : range.end - range.start + 1),
|
|
53
|
+
};
|
|
54
|
+
if (range === null)
|
|
55
|
+
return { status: 200, headers };
|
|
56
|
+
headers['Content-Range'] = `bytes ${range.start}-${range.end}/${size}`;
|
|
57
|
+
return { status: 206, headers, span: range };
|
|
58
|
+
}
|
package/dist/render.js
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
1
|
+
// Frames are captured by N parallel pages and streamed to ffmpeg's stdin in
|
|
2
|
+
// exact frame order (no scratch frame files on disk). The headless browser is
|
|
3
|
+
// the system Chrome/Edge via playwright-core - no browser download.
|
|
4
|
+
import http from 'node:http';
|
|
5
|
+
import { spawn } from 'node:child_process';
|
|
6
|
+
import { once } from 'node:events';
|
|
7
|
+
import { MIME } from './assets.js';
|
|
8
|
+
import { errorMessage } from './errors.js';
|
|
9
|
+
import { RENDERER_DIR, serveAsset } from './serve.js';
|
|
10
|
+
import { NOOP_TRACER, stage } from './tracing.js';
|
|
11
|
+
const PAGE_LOAD_TIMEOUT_MS = 60000;
|
|
12
|
+
const SCREENSHOT_TIMEOUT_MS = 60000;
|
|
13
|
+
function startServer({ html, style, tileCache, }) {
|
|
14
|
+
const server = http.createServer((req, res) => {
|
|
15
|
+
// A malformed request URL (e.g. "GET /%") must not crash the render:
|
|
16
|
+
// decodeURIComponent throws URIError, which would surface as an
|
|
17
|
+
// uncaughtException inside this handler.
|
|
18
|
+
let url;
|
|
19
|
+
try {
|
|
20
|
+
url = decodeURIComponent((req.url ?? '/').split('?')[0]);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
res.writeHead(400, { 'Content-Type': 'text/plain' });
|
|
24
|
+
res.end('bad request');
|
|
25
|
+
return;
|
|
26
|
+
}
|
|
27
|
+
if (url === '/' || url === '/index.html') {
|
|
28
|
+
res.writeHead(200, { 'Content-Type': MIME['.html'] });
|
|
29
|
+
res.end(html);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (serveAsset(url, res, { style, tileCache, rendererDir: RENDERER_DIR }))
|
|
33
|
+
return;
|
|
34
|
+
res.writeHead(404, { 'Content-Type': 'text/plain' });
|
|
35
|
+
res.end('not found');
|
|
36
|
+
});
|
|
37
|
+
return new Promise((resolve) => {
|
|
38
|
+
server.listen(0, '127.0.0.1', () => {
|
|
39
|
+
const addr = server.address();
|
|
40
|
+
const port = addr && typeof addr === 'object' ? addr.port : 0;
|
|
41
|
+
resolve({ server, url: `http://127.0.0.1:${port}/` });
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
async function launchBrowser(log, browserPath) {
|
|
46
|
+
const { chromium } = await import('playwright-core');
|
|
47
|
+
const attempts = [];
|
|
48
|
+
if (browserPath)
|
|
49
|
+
attempts.push({ executablePath: browserPath });
|
|
50
|
+
// System Chrome/Edge first (nothing to download), then the Playwright
|
|
51
|
+
// browser registry (usable after `npx playwright install chromium`).
|
|
52
|
+
attempts.push({ channel: 'chrome' }, { channel: 'msedge' }, {});
|
|
53
|
+
const attemptErrors = [];
|
|
54
|
+
for (const opt of attempts) {
|
|
55
|
+
try {
|
|
56
|
+
const browser = await chromium.launch({ headless: true, ...opt });
|
|
57
|
+
log(`browser: ${opt.executablePath ?? opt.channel ?? 'playwright-registry'}`);
|
|
58
|
+
return browser;
|
|
59
|
+
}
|
|
60
|
+
catch (e) {
|
|
61
|
+
attemptErrors.push(e);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// Every attempt's failure survives in the cause chain; the message keeps
|
|
65
|
+
// the final attempt's detail and the remediation steps.
|
|
66
|
+
throw new Error(`could not launch a Chromium browser (tried explicit path, channel=chrome, channel=msedge, playwright registry): ${errorMessage(attemptErrors[attemptErrors.length - 1])}. ` +
|
|
67
|
+
'Install Google Chrome or Microsoft Edge, run "npx playwright install chromium", ' +
|
|
68
|
+
'or pass --browser <path>.', { cause: new AggregateError(attemptErrors, 'all browser launch attempts failed') });
|
|
69
|
+
}
|
|
70
|
+
// The quality level as an encoder CRF per codec (lower is better): x265's
|
|
71
|
+
// CRF scale sits about five points above x264's for the same perceived
|
|
72
|
+
// quality. h264 "high" is the CRF 18 that shipped before quality became
|
|
73
|
+
// configurable.
|
|
74
|
+
const CRF = {
|
|
75
|
+
h264: { 'near-lossless': 16, high: 18, medium: 21, low: 26 },
|
|
76
|
+
h265: { 'near-lossless': 20, high: 22, medium: 25, low: 30 },
|
|
77
|
+
};
|
|
78
|
+
function spawnEncoder(ffmpeg, fpsStr, encode, outPath) {
|
|
79
|
+
// h265 gets the hvc1 sample tag: the ffmpeg-default hev1 tag is refused by
|
|
80
|
+
// QuickTime and some NLEs.
|
|
81
|
+
const codecArgs = encode.codec === 'h265' ? ['-c:v', 'libx265', '-tag:v', 'hvc1'] : ['-c:v', 'libx264'];
|
|
82
|
+
const ffmpegProcess = spawn(ffmpeg, [
|
|
83
|
+
'-hide_banner', '-loglevel', 'error', '-y',
|
|
84
|
+
'-f', 'image2pipe', '-framerate', fpsStr, '-i', '-',
|
|
85
|
+
...codecArgs,
|
|
86
|
+
'-preset', encode.preset,
|
|
87
|
+
'-crf', String(CRF[encode.codec][encode.quality]),
|
|
88
|
+
'-pix_fmt', 'yuv420p', '-r', fpsStr,
|
|
89
|
+
'-movflags', '+faststart', outPath,
|
|
90
|
+
], { stdio: ['pipe', 'ignore', 'pipe'] });
|
|
91
|
+
let stderr = '';
|
|
92
|
+
ffmpegProcess.stderr?.on('data', (d) => {
|
|
93
|
+
stderr += d.toString();
|
|
94
|
+
});
|
|
95
|
+
// ffmpeg's stdin must never surface an unhandled 'error' (EPIPE when the
|
|
96
|
+
// encoder exits early), and a worker parked on 'drain' must wake up when it
|
|
97
|
+
// dies instead of waiting forever. `closed` also resolves for late waits.
|
|
98
|
+
const closed = new Promise((resolve) => {
|
|
99
|
+
ffmpegProcess.once('close', (code) => resolve(code));
|
|
100
|
+
});
|
|
101
|
+
const stopped = new Promise((resolve) => {
|
|
102
|
+
ffmpegProcess.stdin.on('error', (e) => resolve(`ffmpeg stdin error: ${e.message}`));
|
|
103
|
+
void closed.then((code) => resolve(`ffmpeg exited with code ${code}`));
|
|
104
|
+
});
|
|
105
|
+
return {
|
|
106
|
+
stdin: ffmpegProcess.stdin,
|
|
107
|
+
stopped,
|
|
108
|
+
closed,
|
|
109
|
+
stderrText: () => stderr,
|
|
110
|
+
kill: () => ffmpegProcess.kill(),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
class OrderedFrameStream {
|
|
114
|
+
encoder;
|
|
115
|
+
pending = new Map();
|
|
116
|
+
nextIndex = 0;
|
|
117
|
+
constructor(encoder) {
|
|
118
|
+
this.encoder = encoder;
|
|
119
|
+
}
|
|
120
|
+
async submit(index, frame) {
|
|
121
|
+
this.pending.set(index, frame);
|
|
122
|
+
await this.flushReady();
|
|
123
|
+
}
|
|
124
|
+
async flushReady() {
|
|
125
|
+
while (this.pending.has(this.nextIndex)) {
|
|
126
|
+
const frame = this.pending.get(this.nextIndex);
|
|
127
|
+
this.pending.delete(this.nextIndex);
|
|
128
|
+
if (!this.encoder.stdin.write(frame)) {
|
|
129
|
+
const woke = await Promise.race([
|
|
130
|
+
once(this.encoder.stdin, 'drain').then(() => 'drain'),
|
|
131
|
+
this.encoder.stopped,
|
|
132
|
+
]);
|
|
133
|
+
if (woke !== 'drain') {
|
|
134
|
+
const stderr = this.encoder.stderrText().trim();
|
|
135
|
+
throw new Error(`${woke}${stderr ? `: ${stderr}` : ''}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
this.nextIndex++;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
end() {
|
|
142
|
+
this.encoder.stdin.end();
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function screenshotOptions(capture) {
|
|
146
|
+
return capture === 'jpeg'
|
|
147
|
+
? {
|
|
148
|
+
type: 'jpeg',
|
|
149
|
+
quality: 95,
|
|
150
|
+
animations: 'disabled',
|
|
151
|
+
timeout: SCREENSHOT_TIMEOUT_MS,
|
|
152
|
+
}
|
|
153
|
+
: {
|
|
154
|
+
type: 'png',
|
|
155
|
+
animations: 'disabled',
|
|
156
|
+
timeout: SCREENSHOT_TIMEOUT_MS,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
// One frame: evaluate, screenshot, record and stream it into ffmpeg in
|
|
160
|
+
// order.
|
|
161
|
+
async function captureFrame(run, loop, page, idx) {
|
|
162
|
+
// __setFrame resolves after the canvas painted (canvas drawing is
|
|
163
|
+
// deferred to requestAnimationFrame); awaiting it keeps every
|
|
164
|
+
// screenshot on the current frame.
|
|
165
|
+
const evalStart = Date.now();
|
|
166
|
+
await page.evaluate((frame) => globalThis.__setFrame(frame), run.frameStart + idx);
|
|
167
|
+
run.timing.evalMs += Date.now() - evalStart;
|
|
168
|
+
const captureStart = Date.now();
|
|
169
|
+
const buf = await page.screenshot(screenshotOptions(run.capture));
|
|
170
|
+
const captureMs = Date.now() - captureStart;
|
|
171
|
+
run.timing.captureMs += captureMs;
|
|
172
|
+
// The local count (not the shared one read after an await) keeps every
|
|
173
|
+
// boundary event exactly-once under worker races.
|
|
174
|
+
const done = ++loop.capturesDone;
|
|
175
|
+
run.batches.recordFrame(done, captureMs);
|
|
176
|
+
const emitStart = Date.now();
|
|
177
|
+
await run.stream.submit(idx, buf);
|
|
178
|
+
run.timing.emitMs += Date.now() - emitStart;
|
|
179
|
+
if (done % 100 === 0 || done === run.frames) {
|
|
180
|
+
run.log(`frames: ${done}/${run.frames} captured`);
|
|
181
|
+
run.onCapture?.({ done, total: run.frames });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// One worker's page and frame loop.
|
|
185
|
+
async function workerLoop(run, loop, workerId) {
|
|
186
|
+
const page = await run.active.newPage({
|
|
187
|
+
viewport: { width: run.width, height: run.height },
|
|
188
|
+
deviceScaleFactor: 1,
|
|
189
|
+
});
|
|
190
|
+
try {
|
|
191
|
+
await page.goto(run.url, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT_MS });
|
|
192
|
+
await page.waitForFunction('window.__READY === true', null, { timeout: PAGE_LOAD_TIMEOUT_MS });
|
|
193
|
+
for (;;) {
|
|
194
|
+
// A doomed render stops at the next frame: survivors have to settle
|
|
195
|
+
// before the batch and capture spans are wound down.
|
|
196
|
+
if (loop.failed)
|
|
197
|
+
return;
|
|
198
|
+
if (run.signal?.aborted)
|
|
199
|
+
throw new Error('render canceled');
|
|
200
|
+
const idx = loop.cursor++;
|
|
201
|
+
if (idx >= run.frames)
|
|
202
|
+
break;
|
|
203
|
+
await captureFrame(run, loop, page, idx);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
finally {
|
|
207
|
+
await page.close().catch(() => { });
|
|
208
|
+
}
|
|
209
|
+
run.log(`worker ${workerId} done`);
|
|
210
|
+
}
|
|
211
|
+
// The frame loop: workers race for frame indices and stream every capture
|
|
212
|
+
// into ffmpeg in exact order. allSettled, not all: the batch spans and the
|
|
213
|
+
// captured-frame count must be final before the capture span is wound down.
|
|
214
|
+
async function runWorkers(run, workerCount) {
|
|
215
|
+
const loop = { cursor: 0, capturesDone: 0, failed: false };
|
|
216
|
+
const settled = await Promise.allSettled(Array.from({ length: workerCount }, (_, i) => workerLoop(run, loop, i + 1).catch((e) => {
|
|
217
|
+
loop.failed = true;
|
|
218
|
+
throw e;
|
|
219
|
+
})));
|
|
220
|
+
const rejected = settled.find((r) => r.status === 'rejected');
|
|
221
|
+
run.batches.close(rejected?.reason);
|
|
222
|
+
run.captureSpan.setAttribute('render.frames.captured', loop.capturesDone);
|
|
223
|
+
if (rejected)
|
|
224
|
+
throw rejected.reason;
|
|
225
|
+
}
|
|
226
|
+
async function finishEncode(encoder, stream, encodeSpan, log, outPath) {
|
|
227
|
+
await stream.flushReady();
|
|
228
|
+
stream.end();
|
|
229
|
+
// `closed` (not `once(ffmpeg, 'close')`): ffmpeg may already have exited.
|
|
230
|
+
const code = await encoder.closed;
|
|
231
|
+
encodeSpan.setAttribute('render.ffmpeg.exitCode', code ?? -1);
|
|
232
|
+
if (code !== 0) {
|
|
233
|
+
throw new Error(`ffmpeg exited with code ${code}: ${encoder.stderrText().trim()}`);
|
|
234
|
+
}
|
|
235
|
+
log(`encoded: ${outPath}`);
|
|
236
|
+
}
|
|
237
|
+
function formatProfile(profile, workerCount) {
|
|
238
|
+
return (`profile: eval=${(profile.evalMs / 1000).toFixed(1)}s capture=${(profile.captureMs / 1000).toFixed(1)}s ` +
|
|
239
|
+
`encode-backpressure=${(profile.emitMs / 1000).toFixed(1)}s (summed over ${workerCount} workers)`);
|
|
240
|
+
}
|
|
241
|
+
// One `render.capture.batch` subspan per cadence of captured frames, carrying
|
|
242
|
+
// the per-frame capture spread of that batch. Per-frame spans would bury the
|
|
243
|
+
// trace in thousands of near-identical spans and overflow the exporter queue.
|
|
244
|
+
export class FrameBatchRecorder {
|
|
245
|
+
tracer;
|
|
246
|
+
parent;
|
|
247
|
+
frames;
|
|
248
|
+
cadence;
|
|
249
|
+
openSpan = null;
|
|
250
|
+
durations = [];
|
|
251
|
+
closed = false;
|
|
252
|
+
constructor(tracer, parent, frames, cadence = 100) {
|
|
253
|
+
this.tracer = tracer;
|
|
254
|
+
this.parent = parent;
|
|
255
|
+
this.frames = frames;
|
|
256
|
+
this.cadence = cadence;
|
|
257
|
+
}
|
|
258
|
+
recordFrame(capturedSoFar, captureMs) {
|
|
259
|
+
// close() is permanent: a straggling frame must not re-open a batch under
|
|
260
|
+
// the already-ended capture span.
|
|
261
|
+
if (this.closed)
|
|
262
|
+
return;
|
|
263
|
+
this.openSpan ??= this.tracer.startSpan('render.capture.batch', {
|
|
264
|
+
parent: this.parent,
|
|
265
|
+
});
|
|
266
|
+
this.durations.push(captureMs);
|
|
267
|
+
const boundary = capturedSoFar % this.cadence === 0 || capturedSoFar === this.frames;
|
|
268
|
+
if (!boundary)
|
|
269
|
+
return;
|
|
270
|
+
const span = this.openSpan;
|
|
271
|
+
const durations = this.durations;
|
|
272
|
+
this.openSpan = null;
|
|
273
|
+
this.durations = [];
|
|
274
|
+
span.setAttribute('render.frames.captured', capturedSoFar);
|
|
275
|
+
span.setAttribute('render.frame.minMs', Math.min(...durations));
|
|
276
|
+
span.setAttribute('render.frame.avgMs', Math.round((durations.reduce((a, b) => a + b, 0) / durations.length) * 10) / 10);
|
|
277
|
+
span.setAttribute('render.frame.maxMs', Math.max(...durations));
|
|
278
|
+
span.end();
|
|
279
|
+
}
|
|
280
|
+
// A half-open batch at close time is normal (nothing in flight).
|
|
281
|
+
close(error) {
|
|
282
|
+
if (this.closed)
|
|
283
|
+
return;
|
|
284
|
+
this.closed = true;
|
|
285
|
+
if (this.openSpan === null)
|
|
286
|
+
return;
|
|
287
|
+
if (error !== undefined)
|
|
288
|
+
this.openSpan.fail(error);
|
|
289
|
+
this.openSpan.end();
|
|
290
|
+
this.openSpan = null;
|
|
291
|
+
this.durations = [];
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
// The encode span encloses the capture span on purpose: frames stream into
|
|
295
|
+
// ffmpeg while they are still being captured, and the trace must show that
|
|
296
|
+
// overlap.
|
|
297
|
+
async function captureAndEncode(active, env) {
|
|
298
|
+
const { ctx, tracer, renderSpan, url, timing, workerCount } = env;
|
|
299
|
+
const { fpsStr, codec, quality, preset, outPath, signal, width, height, frames, frameStart, capture, log, onCapture, tools, } = ctx;
|
|
300
|
+
const encoder = spawnEncoder(tools.ffmpeg, fpsStr, { codec, quality, preset }, outPath);
|
|
301
|
+
// A cancel must reach the encoder directly: a worker parked on stdin
|
|
302
|
+
// backpressure would otherwise never notice the abort.
|
|
303
|
+
const killOnAbort = () => encoder.kill();
|
|
304
|
+
signal?.addEventListener('abort', killOnAbort, { once: true });
|
|
305
|
+
const stream = new OrderedFrameStream(encoder);
|
|
306
|
+
try {
|
|
307
|
+
await stage(tracer, 'render.encode', renderSpan, {
|
|
308
|
+
'render.codec': codec,
|
|
309
|
+
'render.quality': quality,
|
|
310
|
+
'render.preset': preset,
|
|
311
|
+
}, async (encodeSpan) => {
|
|
312
|
+
await stage(tracer, 'render.capture', renderSpan, {}, async (captureSpan) => {
|
|
313
|
+
await runWorkers({
|
|
314
|
+
active,
|
|
315
|
+
url,
|
|
316
|
+
width,
|
|
317
|
+
height,
|
|
318
|
+
frames,
|
|
319
|
+
frameStart,
|
|
320
|
+
capture,
|
|
321
|
+
signal,
|
|
322
|
+
log,
|
|
323
|
+
onCapture,
|
|
324
|
+
stream,
|
|
325
|
+
batches: new FrameBatchRecorder(tracer, captureSpan, frames),
|
|
326
|
+
timing,
|
|
327
|
+
captureSpan,
|
|
328
|
+
}, workerCount);
|
|
329
|
+
});
|
|
330
|
+
await finishEncode(encoder, stream, encodeSpan, log, outPath);
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
catch (e) {
|
|
334
|
+
encoder.kill();
|
|
335
|
+
throw e;
|
|
336
|
+
}
|
|
337
|
+
finally {
|
|
338
|
+
signal?.removeEventListener('abort', killOnAbort);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
// The profile stage: fold the summed stage timings into what the caller gets,
|
|
342
|
+
// mirrored on the render span and in the log.
|
|
343
|
+
function reportProfile(env) {
|
|
344
|
+
const { ctx, timing, renderSpan, workerCount } = env;
|
|
345
|
+
const profile = {
|
|
346
|
+
evalMs: Math.round(timing.evalMs),
|
|
347
|
+
captureMs: Math.round(timing.captureMs),
|
|
348
|
+
emitMs: Math.round(timing.emitMs),
|
|
349
|
+
};
|
|
350
|
+
renderSpan.setAttributes({
|
|
351
|
+
'render.evalMs': profile.evalMs,
|
|
352
|
+
'render.captureMs': profile.captureMs,
|
|
353
|
+
'render.emitMs': profile.emitMs,
|
|
354
|
+
});
|
|
355
|
+
ctx.log(formatProfile(profile, workerCount));
|
|
356
|
+
return { profile };
|
|
357
|
+
}
|
|
358
|
+
// Every output frame gets its own capture (held frames judder whenever the map
|
|
359
|
+
// moves, so there is no frame-step option), streamed to ffmpeg in exact frame
|
|
360
|
+
// order.
|
|
361
|
+
// Traced as `render` over `render.capture` (+ batch subspans) and
|
|
362
|
+
// `render.encode`; capture and encode overlap by design.
|
|
363
|
+
export async function renderVideo(opts) {
|
|
364
|
+
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, trace, onCapture, } = opts;
|
|
365
|
+
const tracer = trace?.tracer ?? NOOP_TRACER;
|
|
366
|
+
const workerCount = Math.max(1, Math.min(workers, frames));
|
|
367
|
+
const ctx = {
|
|
368
|
+
width,
|
|
369
|
+
height,
|
|
370
|
+
frames,
|
|
371
|
+
frameStart,
|
|
372
|
+
fpsStr,
|
|
373
|
+
outPath,
|
|
374
|
+
capture,
|
|
375
|
+
codec,
|
|
376
|
+
quality,
|
|
377
|
+
preset,
|
|
378
|
+
signal,
|
|
379
|
+
log,
|
|
380
|
+
onCapture,
|
|
381
|
+
tools,
|
|
382
|
+
};
|
|
383
|
+
return stage(tracer, 'render', trace?.parent, {
|
|
384
|
+
'render.workers': workerCount,
|
|
385
|
+
'render.capture.mode': capture,
|
|
386
|
+
'render.codec': codec,
|
|
387
|
+
'render.quality': quality,
|
|
388
|
+
'render.preset': preset,
|
|
389
|
+
}, async (renderSpan) => {
|
|
390
|
+
if (signal?.aborted)
|
|
391
|
+
throw new Error('render canceled');
|
|
392
|
+
const timing = { evalMs: 0, captureMs: 0, emitMs: 0 };
|
|
393
|
+
const { server, url } = await startServer({ html, style, tileCache });
|
|
394
|
+
const env = { ctx, tracer, renderSpan, url, timing, workerCount };
|
|
395
|
+
// The try spans startup as well: a browser-launch failure must still
|
|
396
|
+
// close the server, whose listening socket would keep the process alive.
|
|
397
|
+
let browser = null;
|
|
398
|
+
try {
|
|
399
|
+
browser = await launchBrowser(log, browserPath);
|
|
400
|
+
await captureAndEncode(browser, env);
|
|
401
|
+
}
|
|
402
|
+
finally {
|
|
403
|
+
await browser?.close().catch(() => { });
|
|
404
|
+
server.close();
|
|
405
|
+
}
|
|
406
|
+
return reportProfile(env);
|
|
407
|
+
});
|
|
408
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createScene } from './scene.js';
|
|
2
|
+
export function bootScene(host, data, L) {
|
|
3
|
+
const scene = createScene(host, data, { L });
|
|
4
|
+
// The pane size may only settle after creation; re-measure post-layout.
|
|
5
|
+
requestAnimationFrame(() => scene.relayout());
|
|
6
|
+
return scene;
|
|
7
|
+
}
|