drone-path-engine 0.0.0-stage → 1.0.0-rc1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/THIRD-PARTY-NOTICES.md +11 -0
- package/dist/assets.d.ts +34 -0
- package/dist/assets.js +60 -0
- package/dist/config.d.ts +207 -0
- package/dist/config.js +581 -0
- package/dist/configfile.d.ts +20 -0
- package/dist/configfile.js +86 -0
- package/dist/decimate.d.ts +11 -0
- package/dist/decimate.js +84 -0
- package/dist/ffmpeg-output.d.ts +9 -0
- package/dist/ffmpeg-output.js +40 -0
- package/dist/logging.d.ts +1 -0
- package/dist/logging.js +1 -0
- package/dist/paths.d.ts +4 -0
- package/dist/paths.js +21 -0
- package/dist/pipeline.d.ts +90 -0
- package/dist/pipeline.js +430 -0
- package/dist/plan.d.ts +47 -0
- package/dist/plan.js +112 -0
- package/dist/png.d.ts +1 -0
- package/dist/png.js +32 -0
- package/dist/range.d.ts +19 -0
- package/dist/range.js +50 -0
- package/dist/recordings.d.ts +5 -0
- package/dist/recordings.js +45 -0
- package/dist/render-page.d.ts +35 -0
- package/dist/render-page.js +85 -0
- package/dist/render.d.ts +57 -0
- package/dist/render.js +397 -0
- package/dist/renderer/boot.d.ts +4 -0
- package/dist/renderer/boot.js +28 -0
- package/dist/renderer/dom.d.ts +28 -0
- package/dist/renderer/dom.js +179 -0
- package/dist/renderer/framemath.d.ts +5 -0
- package/dist/renderer/framemath.js +30 -0
- package/dist/renderer/scene.d.ts +38 -0
- package/dist/renderer/scene.js +401 -0
- package/dist/renderer/theme.d.ts +13 -0
- package/dist/renderer/theme.js +82 -0
- package/dist/renderer/tilesources.d.ts +14 -0
- package/dist/renderer/tilesources.js +38 -0
- package/dist/renderer/trail.d.ts +18 -0
- package/dist/renderer/trail.js +42 -0
- package/dist/restyle.d.ts +13 -0
- package/dist/restyle.js +16 -0
- package/dist/serve.d.ts +6 -0
- package/dist/serve.js +27 -0
- package/dist/tilecache.d.ts +12 -0
- package/dist/tilecache.js +21 -0
- package/dist/tiles.d.ts +25 -0
- package/dist/tiles.js +215 -0
- package/dist/version.d.ts +1 -0
- package/dist/version.js +3 -0
- package/package.json +37 -4
|
@@ -0,0 +1,45 @@
|
|
|
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
|
+
function listMp4(dir, recurse) {
|
|
10
|
+
const found = [];
|
|
11
|
+
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
12
|
+
const full = path.join(dir, entry.name);
|
|
13
|
+
if (entry.isDirectory()) {
|
|
14
|
+
if (recurse)
|
|
15
|
+
found.push(...listMp4(full, recurse));
|
|
16
|
+
}
|
|
17
|
+
else if (entry.isFile() && isRecordingName(entry.name)) {
|
|
18
|
+
found.push(full);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
return found;
|
|
22
|
+
}
|
|
23
|
+
export function collectRecordings(inputs, opts) {
|
|
24
|
+
const files = [];
|
|
25
|
+
for (const item of inputs) {
|
|
26
|
+
const full = path.resolve(item);
|
|
27
|
+
if (!fs.existsSync(full))
|
|
28
|
+
throw new Error(`input not found: ${item}`);
|
|
29
|
+
const st = fs.statSync(full);
|
|
30
|
+
if (st.isDirectory()) {
|
|
31
|
+
files.push(...listMp4(full, opts.recurse));
|
|
32
|
+
}
|
|
33
|
+
else if (isRecordingName(full)) {
|
|
34
|
+
files.push(full);
|
|
35
|
+
}
|
|
36
|
+
else {
|
|
37
|
+
throw new Error(`not an .mp4 recording: ${full}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
const unique = [...new Set(files.map((f) => path.resolve(f)))].sort((a, b) => a.localeCompare(b, 'en'));
|
|
41
|
+
if (unique.length === 0) {
|
|
42
|
+
throw new Error('no .mp4 recordings found in the given input');
|
|
43
|
+
}
|
|
44
|
+
return unique;
|
|
45
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { AppearanceSettings, HudLayout, RenderConfig } from './config.js';
|
|
2
|
+
import type { DecimatedTrack } from './decimate.js';
|
|
3
|
+
import type { Bbox, LatLon } from 'drone-path-core/geo';
|
|
4
|
+
import type { IntroOutroFrames, OverviewPlan } from './plan.js';
|
|
5
|
+
import type { SceneData } from './renderer/scene.js';
|
|
6
|
+
import type { FrameChannels } from 'drone-path-core/telemetry-math';
|
|
7
|
+
export interface RenderPageOpts extends FrameChannels, Pick<RenderConfig, 'width' | 'height'>, Pick<AppearanceSettings, 'style' | 'view' | 'zoom' | 'trailColor' | 'hud'> {
|
|
8
|
+
center: LatLon;
|
|
9
|
+
attribution: string;
|
|
10
|
+
decimated: DecimatedTrack;
|
|
11
|
+
introN?: number;
|
|
12
|
+
outroN?: number;
|
|
13
|
+
}
|
|
14
|
+
export declare function planPageOpts(opts: {
|
|
15
|
+
bbox: Bbox;
|
|
16
|
+
width: number;
|
|
17
|
+
height: number;
|
|
18
|
+
config: AppearanceSettings;
|
|
19
|
+
source: {
|
|
20
|
+
fps: number;
|
|
21
|
+
frames: number;
|
|
22
|
+
};
|
|
23
|
+
frames: FrameChannels;
|
|
24
|
+
planned?: {
|
|
25
|
+
overview: OverviewPlan;
|
|
26
|
+
introOutro: IntroOutroFrames;
|
|
27
|
+
hud: HudLayout;
|
|
28
|
+
};
|
|
29
|
+
previous?: {
|
|
30
|
+
zoom: number;
|
|
31
|
+
decimated: DecimatedTrack;
|
|
32
|
+
};
|
|
33
|
+
}): RenderPageOpts;
|
|
34
|
+
export declare function buildSceneData(opts: RenderPageOpts, tileBase: string): SceneData;
|
|
35
|
+
export declare function buildPageHtml(opts: RenderPageOpts): string;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { hasAltitude, resolveHudLayout } from './config.js';
|
|
2
|
+
import { decimateTrack } from './decimate.js';
|
|
3
|
+
import { unproject } from 'drone-path-core/geo';
|
|
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.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { Writable } from 'node:stream';
|
|
2
|
+
import type { RenderConfig } from './config.js';
|
|
3
|
+
import type { FfmpegToolPaths } from 'drone-path-core/ffmpeg-tools';
|
|
4
|
+
import type { LogFn } from './logging.js';
|
|
5
|
+
interface Encoder {
|
|
6
|
+
stdin: Writable;
|
|
7
|
+
stopped: Promise<string>;
|
|
8
|
+
closed: Promise<number | null>;
|
|
9
|
+
stderrText(): string;
|
|
10
|
+
spawnError(): Error | null;
|
|
11
|
+
kill(): void;
|
|
12
|
+
}
|
|
13
|
+
export declare class OrderedFrameStream {
|
|
14
|
+
private readonly encoder;
|
|
15
|
+
private readonly maxPending;
|
|
16
|
+
private readonly pending;
|
|
17
|
+
private nextIndex;
|
|
18
|
+
private flushing;
|
|
19
|
+
private waiters;
|
|
20
|
+
private abortedError;
|
|
21
|
+
private abortReject;
|
|
22
|
+
private readonly abortPromise;
|
|
23
|
+
constructor(encoder: Pick<Encoder, 'stdin' | 'stopped' | 'stderrText'>, maxPending?: number);
|
|
24
|
+
submit(index: number, frame: Buffer): Promise<void>;
|
|
25
|
+
flushReady(): Promise<void>;
|
|
26
|
+
abort(err: unknown): void;
|
|
27
|
+
end(): void;
|
|
28
|
+
private drainReady;
|
|
29
|
+
private waitForSpace;
|
|
30
|
+
private wakeWaiters;
|
|
31
|
+
private rejectWaiters;
|
|
32
|
+
}
|
|
33
|
+
export interface CaptureProgress {
|
|
34
|
+
done: number;
|
|
35
|
+
total: number;
|
|
36
|
+
}
|
|
37
|
+
export interface RenderJobOptions extends Pick<RenderConfig, 'style' | 'tileCache' | 'width' | 'height' | 'workers' | 'capture' | 'codec' | 'quality' | 'preset'> {
|
|
38
|
+
html: string;
|
|
39
|
+
frames: number;
|
|
40
|
+
frameStart?: number;
|
|
41
|
+
fpsStr: string;
|
|
42
|
+
outPath: string;
|
|
43
|
+
log?: LogFn;
|
|
44
|
+
browserPath?: string | null;
|
|
45
|
+
tools: FfmpegToolPaths;
|
|
46
|
+
signal?: AbortSignal;
|
|
47
|
+
onCapture?: (progress: CaptureProgress) => void;
|
|
48
|
+
}
|
|
49
|
+
interface RenderProfile {
|
|
50
|
+
evalMs: number;
|
|
51
|
+
captureMs: number;
|
|
52
|
+
emitMs: number;
|
|
53
|
+
}
|
|
54
|
+
export declare function renderVideo(opts: RenderJobOptions): Promise<{
|
|
55
|
+
profile: RenderProfile;
|
|
56
|
+
}>;
|
|
57
|
+
export {};
|
package/dist/render.js
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
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 'drone-path-core/errors';
|
|
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, log, }) {
|
|
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, reject) => {
|
|
31
|
+
const onListenError = (err) => {
|
|
32
|
+
reject(new Error(`local render server error: ${err.message}`, { cause: err }));
|
|
33
|
+
};
|
|
34
|
+
server.once('error', onListenError);
|
|
35
|
+
server.listen(0, '127.0.0.1', () => {
|
|
36
|
+
server.off('error', onListenError);
|
|
37
|
+
server.on('error', (err) => {
|
|
38
|
+
log?.(`render server error: ${err.message}`);
|
|
39
|
+
});
|
|
40
|
+
const addr = server.address();
|
|
41
|
+
const port = addr && typeof addr === 'object' ? addr.port : 0;
|
|
42
|
+
resolve({ server, url: `http://127.0.0.1:${port}/` });
|
|
43
|
+
});
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
async function launchBrowser(log, browserPath) {
|
|
47
|
+
const { chromium } = await import('playwright-core');
|
|
48
|
+
const attempts = [];
|
|
49
|
+
if (browserPath)
|
|
50
|
+
attempts.push({ executablePath: browserPath });
|
|
51
|
+
attempts.push({ channel: 'chrome' }, { channel: 'msedge' }, {});
|
|
52
|
+
const attemptErrors = [];
|
|
53
|
+
for (const opt of attempts) {
|
|
54
|
+
try {
|
|
55
|
+
const browser = await chromium.launch({ headless: true, ...opt });
|
|
56
|
+
log(`browser: ${opt.executablePath ?? opt.channel ?? 'playwright-registry'}`);
|
|
57
|
+
return browser;
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
attemptErrors.push(e);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
throw new Error(`could not launch a Chromium browser (tried explicit path, channel=chrome, channel=msedge, playwright registry): ${errorMessage(attemptErrors[attemptErrors.length - 1])}. ` +
|
|
64
|
+
'Install Google Chrome or Microsoft Edge, run "npx playwright install chromium", ' +
|
|
65
|
+
'or pass --browser <path>.', { cause: new AggregateError(attemptErrors, 'all browser launch attempts failed') });
|
|
66
|
+
}
|
|
67
|
+
// x265's CRF scale sits ~5 points above x264's for the same perceived quality.
|
|
68
|
+
const CRF = {
|
|
69
|
+
h264: { 'near-lossless': 16, high: 18, medium: 21, low: 26 },
|
|
70
|
+
h265: { 'near-lossless': 20, high: 22, medium: 25, low: 30 },
|
|
71
|
+
};
|
|
72
|
+
function spawnEncoder(ffmpeg, fpsStr, encode, outPath) {
|
|
73
|
+
// h265 gets hvc1: the ffmpeg-default hev1 tag is refused by QuickTime and some NLEs.
|
|
74
|
+
const codecArgs = encode.codec === 'h265' ? ['-c:v', 'libx265', '-tag:v', 'hvc1'] : ['-c:v', 'libx264'];
|
|
75
|
+
const ffmpegProcess = spawn(ffmpeg, [
|
|
76
|
+
'-hide_banner', '-loglevel', 'error', '-y',
|
|
77
|
+
'-f', 'image2pipe', '-framerate', fpsStr, '-i', '-',
|
|
78
|
+
...codecArgs,
|
|
79
|
+
'-preset', encode.preset,
|
|
80
|
+
'-crf', String(CRF[encode.codec][encode.quality]),
|
|
81
|
+
'-pix_fmt', 'yuv420p', '-r', fpsStr,
|
|
82
|
+
'-movflags', '+faststart', outPath,
|
|
83
|
+
], { stdio: ['pipe', 'ignore', 'pipe'], windowsHide: true });
|
|
84
|
+
let stderr = '';
|
|
85
|
+
ffmpegProcess.stderr?.on('data', (d) => {
|
|
86
|
+
stderr += d.toString();
|
|
87
|
+
});
|
|
88
|
+
// ffmpeg's process and stdin must never surface unhandled 'error' events (ENOENT on spawn, EPIPE on early exit); waiters must wake when the encoder dies.
|
|
89
|
+
let procError = null;
|
|
90
|
+
const closed = new Promise((resolve) => {
|
|
91
|
+
ffmpegProcess.once('close', (code) => resolve(code));
|
|
92
|
+
ffmpegProcess.once('error', (e) => {
|
|
93
|
+
procError = e;
|
|
94
|
+
resolve(null);
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
ffmpegProcess.on('error', () => { });
|
|
98
|
+
const stopped = new Promise((resolve) => {
|
|
99
|
+
ffmpegProcess.stdin.on('error', (e) => resolve(`ffmpeg stdin error: ${e.message}`));
|
|
100
|
+
void closed.then((code) => resolve(procError
|
|
101
|
+
? `ffmpeg process error: ${procError.message}`
|
|
102
|
+
: `ffmpeg exited with code ${code}`));
|
|
103
|
+
});
|
|
104
|
+
return {
|
|
105
|
+
stdin: ffmpegProcess.stdin,
|
|
106
|
+
stopped,
|
|
107
|
+
closed,
|
|
108
|
+
stderrText: () => stderr,
|
|
109
|
+
spawnError: () => procError,
|
|
110
|
+
kill: () => ffmpegProcess.kill(),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
export class OrderedFrameStream {
|
|
114
|
+
encoder;
|
|
115
|
+
maxPending;
|
|
116
|
+
pending = new Map();
|
|
117
|
+
nextIndex = 0;
|
|
118
|
+
flushing = null;
|
|
119
|
+
waiters = [];
|
|
120
|
+
abortedError = null;
|
|
121
|
+
abortReject = null;
|
|
122
|
+
abortPromise;
|
|
123
|
+
constructor(encoder, maxPending = 1) {
|
|
124
|
+
this.encoder = encoder;
|
|
125
|
+
this.maxPending = maxPending;
|
|
126
|
+
this.abortPromise = new Promise((_resolve, reject) => {
|
|
127
|
+
this.abortReject = reject;
|
|
128
|
+
});
|
|
129
|
+
this.abortPromise.catch(() => { });
|
|
130
|
+
}
|
|
131
|
+
async submit(index, frame) {
|
|
132
|
+
if (this.abortedError !== null)
|
|
133
|
+
throw this.abortedError;
|
|
134
|
+
this.pending.set(index, frame);
|
|
135
|
+
if (this.flushing) {
|
|
136
|
+
await this.flushing;
|
|
137
|
+
}
|
|
138
|
+
else if (this.pending.has(this.nextIndex)) {
|
|
139
|
+
await this.flushReady();
|
|
140
|
+
}
|
|
141
|
+
if (this.abortedError !== null)
|
|
142
|
+
throw this.abortedError;
|
|
143
|
+
while (this.pending.size >= this.maxPending || this.flushing !== null) {
|
|
144
|
+
if (this.pending.has(this.nextIndex) && this.flushing === null) {
|
|
145
|
+
await this.flushReady();
|
|
146
|
+
}
|
|
147
|
+
else if (this.flushing !== null) {
|
|
148
|
+
await this.flushing;
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
await this.waitForSpace();
|
|
152
|
+
}
|
|
153
|
+
if (this.abortedError !== null)
|
|
154
|
+
throw this.abortedError;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
flushReady() {
|
|
158
|
+
if (this.flushing)
|
|
159
|
+
return this.flushing;
|
|
160
|
+
if (this.abortedError !== null)
|
|
161
|
+
return Promise.reject(this.abortedError);
|
|
162
|
+
const run = this.drainReady().finally(() => {
|
|
163
|
+
if (this.flushing === run)
|
|
164
|
+
this.flushing = null;
|
|
165
|
+
this.wakeWaiters();
|
|
166
|
+
});
|
|
167
|
+
this.flushing = run;
|
|
168
|
+
return run;
|
|
169
|
+
}
|
|
170
|
+
abort(err) {
|
|
171
|
+
if (this.abortedError !== null)
|
|
172
|
+
return;
|
|
173
|
+
this.abortedError = err;
|
|
174
|
+
this.pending.clear();
|
|
175
|
+
this.abortReject?.(err);
|
|
176
|
+
this.rejectWaiters(err);
|
|
177
|
+
}
|
|
178
|
+
end() {
|
|
179
|
+
this.encoder.stdin.end();
|
|
180
|
+
}
|
|
181
|
+
async drainReady() {
|
|
182
|
+
try {
|
|
183
|
+
while (this.pending.has(this.nextIndex)) {
|
|
184
|
+
if (this.abortedError !== null)
|
|
185
|
+
throw this.abortedError;
|
|
186
|
+
const frame = this.pending.get(this.nextIndex);
|
|
187
|
+
this.pending.delete(this.nextIndex);
|
|
188
|
+
if (!this.encoder.stdin.write(frame)) {
|
|
189
|
+
const raceAc = new AbortController();
|
|
190
|
+
try {
|
|
191
|
+
const woke = await Promise.race([
|
|
192
|
+
once(this.encoder.stdin, 'drain', { signal: raceAc.signal }).then(() => 'drain'),
|
|
193
|
+
this.encoder.stopped,
|
|
194
|
+
this.abortPromise,
|
|
195
|
+
]);
|
|
196
|
+
if (woke !== 'drain') {
|
|
197
|
+
const stderr = this.encoder.stderrText().trim();
|
|
198
|
+
throw new Error(`${woke}${stderr ? `: ${stderr}` : ''}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
finally {
|
|
202
|
+
raceAc.abort();
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
this.nextIndex++;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
catch (e) {
|
|
209
|
+
if (this.abortedError === null) {
|
|
210
|
+
this.abortedError = e;
|
|
211
|
+
this.pending.clear();
|
|
212
|
+
this.rejectWaiters(e);
|
|
213
|
+
}
|
|
214
|
+
throw e;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
waitForSpace() {
|
|
218
|
+
if (this.abortedError !== null)
|
|
219
|
+
return Promise.reject(this.abortedError);
|
|
220
|
+
return new Promise((resolve, reject) => {
|
|
221
|
+
this.waiters.push({ resolve, reject });
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
wakeWaiters() {
|
|
225
|
+
if (this.abortedError !== null || this.flushing !== null || this.pending.size >= this.maxPending) {
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
const queued = this.waiters;
|
|
229
|
+
this.waiters = [];
|
|
230
|
+
for (const w of queued)
|
|
231
|
+
w.resolve();
|
|
232
|
+
}
|
|
233
|
+
rejectWaiters(err) {
|
|
234
|
+
const queued = this.waiters;
|
|
235
|
+
this.waiters = [];
|
|
236
|
+
for (const w of queued)
|
|
237
|
+
w.reject(err);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
function screenshotOptions(capture) {
|
|
241
|
+
return capture === 'jpeg'
|
|
242
|
+
? {
|
|
243
|
+
type: 'jpeg',
|
|
244
|
+
quality: 95,
|
|
245
|
+
animations: 'disabled',
|
|
246
|
+
timeout: SCREENSHOT_TIMEOUT_MS,
|
|
247
|
+
}
|
|
248
|
+
: {
|
|
249
|
+
type: 'png',
|
|
250
|
+
animations: 'disabled',
|
|
251
|
+
timeout: SCREENSHOT_TIMEOUT_MS,
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
async function captureFrame(run, loop, page, idx) {
|
|
255
|
+
const evalStart = Date.now();
|
|
256
|
+
await page.evaluate((frame) => globalThis.__setFrame(frame), run.frameStart + idx);
|
|
257
|
+
run.timing.evalMs += Date.now() - evalStart;
|
|
258
|
+
const captureStart = Date.now();
|
|
259
|
+
const buf = await page.screenshot(screenshotOptions(run.capture));
|
|
260
|
+
run.timing.captureMs += Date.now() - captureStart;
|
|
261
|
+
const done = ++loop.capturesDone;
|
|
262
|
+
const emitStart = Date.now();
|
|
263
|
+
await run.stream.submit(idx, buf);
|
|
264
|
+
run.timing.emitMs += Date.now() - emitStart;
|
|
265
|
+
if (done % 100 === 0 || done === run.frames) {
|
|
266
|
+
run.log(`frames: ${done}/${run.frames} captured`);
|
|
267
|
+
run.onCapture?.({ done, total: run.frames });
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
async function workerLoop(run, loop, workerId) {
|
|
271
|
+
const page = await run.active.newPage({
|
|
272
|
+
viewport: { width: run.width, height: run.height },
|
|
273
|
+
deviceScaleFactor: 1,
|
|
274
|
+
});
|
|
275
|
+
try {
|
|
276
|
+
await page.goto(run.url, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT_MS });
|
|
277
|
+
await page.waitForFunction('window.__READY === true', null, { timeout: PAGE_LOAD_TIMEOUT_MS });
|
|
278
|
+
for (;;) {
|
|
279
|
+
if (loop.failed)
|
|
280
|
+
return;
|
|
281
|
+
if (run.signal?.aborted)
|
|
282
|
+
throw new Error(ERR_RENDER_CANCELED);
|
|
283
|
+
const idx = loop.cursor++;
|
|
284
|
+
if (idx >= run.frames)
|
|
285
|
+
break;
|
|
286
|
+
await captureFrame(run, loop, page, idx);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
finally {
|
|
290
|
+
await page.close().catch(() => { });
|
|
291
|
+
}
|
|
292
|
+
run.log(`worker ${workerId} done`);
|
|
293
|
+
}
|
|
294
|
+
async function runWorkers(run, workerCount) {
|
|
295
|
+
const loop = { cursor: 0, capturesDone: 0, failed: false };
|
|
296
|
+
const settled = await Promise.allSettled(Array.from({ length: workerCount }, (_, i) => workerLoop(run, loop, i + 1).catch((e) => {
|
|
297
|
+
loop.failed = true;
|
|
298
|
+
run.stream.abort(e);
|
|
299
|
+
throw e;
|
|
300
|
+
})));
|
|
301
|
+
const rejected = settled.find((r) => r.status === 'rejected');
|
|
302
|
+
if (rejected)
|
|
303
|
+
throw rejected.reason;
|
|
304
|
+
}
|
|
305
|
+
async function finishEncode(encoder, stream, log, outPath) {
|
|
306
|
+
await stream.flushReady();
|
|
307
|
+
stream.end();
|
|
308
|
+
const code = await encoder.closed;
|
|
309
|
+
const procError = encoder.spawnError();
|
|
310
|
+
if (procError) {
|
|
311
|
+
throw new Error(`ffmpeg process error: ${procError.message}`, { cause: procError });
|
|
312
|
+
}
|
|
313
|
+
if (code !== 0) {
|
|
314
|
+
throw new Error(`ffmpeg exited with code ${code}: ${encoder.stderrText().trim()}`);
|
|
315
|
+
}
|
|
316
|
+
log(`encoded: ${outPath}`);
|
|
317
|
+
}
|
|
318
|
+
function formatProfile(profile, workerCount) {
|
|
319
|
+
return (`profile: eval=${(profile.evalMs / 1000).toFixed(1)}s capture=${(profile.captureMs / 1000).toFixed(1)}s ` +
|
|
320
|
+
`encode-backpressure=${(profile.emitMs / 1000).toFixed(1)}s (summed over ${workerCount} workers)`);
|
|
321
|
+
}
|
|
322
|
+
async function captureAndEncode(active, env) {
|
|
323
|
+
const { ctx, url, timing, workerCount } = env;
|
|
324
|
+
const { fpsStr, codec, quality, preset, outPath, signal, log, tools } = ctx;
|
|
325
|
+
const encoder = spawnEncoder(tools.ffmpeg, fpsStr, { codec, quality, preset }, outPath);
|
|
326
|
+
const stream = new OrderedFrameStream(encoder, workerCount);
|
|
327
|
+
const abortEncode = () => {
|
|
328
|
+
encoder.kill();
|
|
329
|
+
stream.abort(new Error(ERR_RENDER_CANCELED));
|
|
330
|
+
};
|
|
331
|
+
signal?.addEventListener('abort', abortEncode, { once: true });
|
|
332
|
+
try {
|
|
333
|
+
await runWorkers({ ...ctx, active, url, stream, timing }, workerCount);
|
|
334
|
+
if (signal?.aborted)
|
|
335
|
+
throw new Error(ERR_RENDER_CANCELED);
|
|
336
|
+
await finishEncode(encoder, stream, log, outPath);
|
|
337
|
+
}
|
|
338
|
+
catch (e) {
|
|
339
|
+
encoder.kill();
|
|
340
|
+
await encoder.closed;
|
|
341
|
+
if (signal?.aborted) {
|
|
342
|
+
throw e instanceof Error && e.message === ERR_RENDER_CANCELED
|
|
343
|
+
? e
|
|
344
|
+
: new Error(ERR_RENDER_CANCELED, { cause: e });
|
|
345
|
+
}
|
|
346
|
+
throw e;
|
|
347
|
+
}
|
|
348
|
+
finally {
|
|
349
|
+
signal?.removeEventListener('abort', abortEncode);
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
function reportProfile(env) {
|
|
353
|
+
const { ctx, timing, workerCount } = env;
|
|
354
|
+
const profile = {
|
|
355
|
+
evalMs: Math.round(timing.evalMs),
|
|
356
|
+
captureMs: Math.round(timing.captureMs),
|
|
357
|
+
emitMs: Math.round(timing.emitMs),
|
|
358
|
+
};
|
|
359
|
+
ctx.log(formatProfile(profile, workerCount));
|
|
360
|
+
return { profile };
|
|
361
|
+
}
|
|
362
|
+
export async function renderVideo(opts) {
|
|
363
|
+
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;
|
|
364
|
+
const workerCount = Math.max(1, Math.min(workers, frames));
|
|
365
|
+
const ctx = {
|
|
366
|
+
width,
|
|
367
|
+
height,
|
|
368
|
+
frames,
|
|
369
|
+
frameStart,
|
|
370
|
+
fpsStr,
|
|
371
|
+
outPath,
|
|
372
|
+
capture,
|
|
373
|
+
codec,
|
|
374
|
+
quality,
|
|
375
|
+
preset,
|
|
376
|
+
signal,
|
|
377
|
+
log,
|
|
378
|
+
onCapture,
|
|
379
|
+
tools,
|
|
380
|
+
};
|
|
381
|
+
if (signal?.aborted)
|
|
382
|
+
throw new Error(ERR_RENDER_CANCELED);
|
|
383
|
+
const timing = { evalMs: 0, captureMs: 0, emitMs: 0 };
|
|
384
|
+
const { server, url } = await startServer({ html, style, tileCache, log });
|
|
385
|
+
const env = { ctx, url, timing, workerCount };
|
|
386
|
+
let browser = null;
|
|
387
|
+
try {
|
|
388
|
+
browser = await launchBrowser(log, browserPath);
|
|
389
|
+
await captureAndEncode(browser, env);
|
|
390
|
+
}
|
|
391
|
+
finally {
|
|
392
|
+
await browser?.close().catch(() => { });
|
|
393
|
+
server.closeAllConnections?.();
|
|
394
|
+
server.close();
|
|
395
|
+
}
|
|
396
|
+
return reportProfile(env);
|
|
397
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
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
|
+
let disposed = false;
|
|
5
|
+
let rafId;
|
|
6
|
+
const baseDispose = scene.dispose.bind(scene);
|
|
7
|
+
const booted = {
|
|
8
|
+
setFrame: (i) => scene.setFrame(i),
|
|
9
|
+
relayout: () => scene.relayout(),
|
|
10
|
+
update: (next) => scene.update(next),
|
|
11
|
+
ready: scene.ready,
|
|
12
|
+
dispose: () => {
|
|
13
|
+
disposed = true;
|
|
14
|
+
if (rafId !== undefined) {
|
|
15
|
+
cancelAnimationFrame(rafId);
|
|
16
|
+
rafId = undefined;
|
|
17
|
+
}
|
|
18
|
+
baseDispose();
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
// The pane size may only settle after creation; re-measure post-layout.
|
|
22
|
+
rafId = requestAnimationFrame(() => {
|
|
23
|
+
rafId = undefined;
|
|
24
|
+
if (!disposed)
|
|
25
|
+
booted.relayout();
|
|
26
|
+
});
|
|
27
|
+
return booted;
|
|
28
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { HudLayout } from '../config.js';
|
|
2
|
+
import type { TileSource } from './tilesources.js';
|
|
3
|
+
import type { Theme } from './theme.js';
|
|
4
|
+
export declare function sceneCss(src: TileSource, theme: Theme, width: number, height: number, scale: number, scope: string): string;
|
|
5
|
+
export declare const EXPORT_HUD_LABELS: {
|
|
6
|
+
readonly heading: "HDG";
|
|
7
|
+
readonly alt: "ALT";
|
|
8
|
+
readonly speed: "SPD";
|
|
9
|
+
};
|
|
10
|
+
export declare function hudMarkup(hud: HudLayout): string;
|
|
11
|
+
/**
|
|
12
|
+
* The app strip's readout columns (#272): both always render so the strip's
|
|
13
|
+
* shape never depends on settings; a disabled chip keeps its column and shows
|
|
14
|
+
* the dimmed "--" placeholder instead of a value. The ids and .num/.unit spans
|
|
15
|
+
* match the export HUD contract, so the scene's value queries work for both.
|
|
16
|
+
*/
|
|
17
|
+
export interface StripLabels {
|
|
18
|
+
speed: string;
|
|
19
|
+
altitude: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function stripReadoutMarkup(hud: HudLayout, labels?: StripLabels): string;
|
|
22
|
+
/** A null hud keeps the chips out of the map frame: the caller mounts them in
|
|
23
|
+
a strip outside the map image instead. */
|
|
24
|
+
export declare function mapMarkup(hud: HudLayout | null, attribution: string): string;
|
|
25
|
+
/** Attribution links are on-screen credits, not controls: keyboard skips them. */
|
|
26
|
+
export declare function quietAttributionLinks(attr: HTMLElement): void;
|
|
27
|
+
export declare function droneMarkerMarkup(coreColor: string): string;
|
|
28
|
+
export declare function el<T extends Element>(root: ParentNode, selector: string): T;
|