drone-path 0.8.1 → 0.9.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 (58) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +17 -24
  3. package/THIRD-PARTY-NOTICES.md +7 -0
  4. package/app/main.mjs +82 -28
  5. package/app/preload.cjs +3 -0
  6. package/dist/appassets.js +2 -11
  7. package/dist/apppaths.js +2 -10
  8. package/dist/appsession.js +59 -25
  9. package/dist/appstate.js +0 -18
  10. package/dist/assets.js +0 -7
  11. package/dist/buildinfo.js +71 -0
  12. package/dist/cammeta.js +123 -84
  13. package/dist/changeset-gate.js +0 -7
  14. package/dist/cli.js +0 -15
  15. package/dist/config.js +40 -52
  16. package/dist/configfile.js +0 -8
  17. package/dist/decimate.js +2 -12
  18. package/dist/exportjob.js +3 -19
  19. package/dist/ff.js +0 -8
  20. package/dist/fftools.js +0 -10
  21. package/dist/geo.js +3 -13
  22. package/dist/inputs.js +0 -4
  23. package/dist/manual/anchors.js +1 -7
  24. package/dist/manual/build.js +0 -6
  25. package/dist/manual/cliref.js +0 -6
  26. package/dist/manual/links.js +0 -17
  27. package/dist/manual/markdown.js +2 -10
  28. package/dist/manual/model.js +0 -3
  29. package/dist/manual/module.js +0 -3
  30. package/dist/manual/nav.js +0 -2
  31. package/dist/manual/reference.js +1 -4
  32. package/dist/page.js +3 -26
  33. package/dist/paths.js +0 -12
  34. package/dist/plan.js +1 -18
  35. package/dist/png.js +0 -3
  36. package/dist/proto.js +4 -4
  37. package/dist/range.js +0 -8
  38. package/dist/render.js +3 -53
  39. package/dist/renderer/dom.js +0 -6
  40. package/dist/renderer/framemath.js +0 -4
  41. package/dist/renderer/leaflet.js +0 -4
  42. package/dist/renderer/scene.js +10 -34
  43. package/dist/renderer/theme.js +58 -10
  44. package/dist/renderer/tilesources.js +0 -10
  45. package/dist/renderer/trail.js +1 -12
  46. package/dist/restyle.js +1 -9
  47. package/dist/run.js +45 -46
  48. package/dist/serve.js +0 -13
  49. package/dist/srt.js +30 -8
  50. package/dist/summary.js +0 -3
  51. package/dist/telemetry-json-schema.js +23 -0
  52. package/dist/telemetry-json.js +107 -0
  53. package/dist/telemetry-math.js +9 -45
  54. package/dist/telemetry.js +52 -9
  55. package/dist/tilecache.js +0 -5
  56. package/dist/tiles.js +1 -31
  57. package/dist/tracing.js +3 -27
  58. package/package.json +9 -6
package/dist/page.js CHANGED
@@ -1,32 +1,13 @@
1
- // The generated headless page receives all telemetry inline (no fetch) and
2
- // exposes window.__setFrame(i) for per-frame marker/trail updates; it resolves
3
- // after the canvas has painted so screenshots are frame-exact. The map scene
4
- // itself lives in src/renderer/ - one shared implementation with the app's
5
- // React map island.
6
- //
7
- // Views:
8
- // overview - static map fitted to the whole track (trail grows with time)
9
- // follow - drone marker stays in the frame center and the map slides under
10
- // it (all tiles are loaded once up-front; the per-frame move is a
11
- // pure CSS transform, so no tile loads happen mid-render)
12
1
  import { hasAltitude, resolveHudSpec } from './config.js';
13
2
  import { decimateTrack } from './decimate.js';
14
3
  import { unproject } from './geo.js';
15
4
  import { planIntroOutroFrames, planView } from './plan.js';
16
5
  import { TILE_SOURCES } from './renderer/tilesources.js';
17
- // The one settings + telemetry -> page mapping. The pipeline's recording
18
- // mapping and the app's live restyle both plan through here, so a preview and
19
- // an export from the same settings agree frame for frame. The bbox must be
20
- // the telemetry's fix bbox (what the tile prefetch warms), never the smaller
21
- // frame-sample bbox.
22
6
  export function planPageOpts(opts) {
23
7
  const { bbox, width, height, config, source, frames, planned, previous } = opts;
24
8
  const overview = planned?.overview ?? planView(bbox, width, height, config);
25
9
  const introOutro = planned?.introOutro ?? planIntroOutroFrames(config, source);
26
10
  const hud = planned?.hud ?? resolveHudSpec(config.hud, hasAltitude(frames.alt));
27
- // Decimation depends only on the track and the working zoom, so an
28
- // unchanged zoom keeps the identical arrays and consumers can tell that no
29
- // trail work is needed.
30
11
  const decimated = previous && previous.zoom === overview.zoom
31
12
  ? previous.decimated
32
13
  : decimateTrack(frames.lat, frames.lon, overview.zoom);
@@ -34,6 +15,7 @@ export function planPageOpts(opts) {
34
15
  width,
35
16
  height,
36
17
  style: config.style,
18
+ trailColor: config.trailColor,
37
19
  view: config.view,
38
20
  center: unproject(overview.centerPx.x, overview.centerPx.y, overview.zoom),
39
21
  zoom: overview.zoom,
@@ -49,13 +31,11 @@ export function planPageOpts(opts) {
49
31
  decimated,
50
32
  };
51
33
  }
52
- // The scene data both consumers drive: the generated page inlines it as
53
- // window.__DATA, the app delivers it as the session payload. Tile URLs are
54
- // rooted at the consumer's serving base ("/tiles" or "app://bundle/tiles").
55
34
  export function buildSceneData(opts, tileBase) {
56
- const { width, height, style, view, center, zoom, attribution, lat, lon, alt, speed, headingDeg, hud, decimated, introN = 0, outroN = 0, } = opts;
35
+ const { width, height, style, trailColor, view, center, zoom, attribution, lat, lon, alt, speed, headingDeg, hud, decimated, introN = 0, outroN = 0, } = opts;
57
36
  return {
58
37
  style,
38
+ trailColor,
59
39
  tileUrl: tileBase + '/' + style + '/{z}/{x}/{y}.png',
60
40
  view,
61
41
  width,
@@ -72,9 +52,6 @@ export function buildSceneData(opts, tileBase) {
72
52
  trailFrame: decimated.frame,
73
53
  };
74
54
  }
75
- // The module boot: boots the shared scene and bridges the globals the
76
- // headless capture uses. Runs after the DOM is parsed (module semantics), so
77
- // the scene always finds its host element.
78
55
  function bootScript(dataJson) {
79
56
  return `import { bootScene } from '/renderer/boot.js';
80
57
  var D = window.__DATA = ${dataJson};
package/dist/paths.js CHANGED
@@ -1,13 +1,4 @@
1
- // Path identity and collision-free output naming have exactly one home.
2
- // Identity follows the platform's own file-name rules: Windows file names
3
- // are case-insensitive, POSIX file names are case-sensitive. The same
4
- // inputs can therefore plan different names per platform, deterministic
5
- // and idempotent on each. Case-insensitive macOS volumes are treated like
6
- // POSIX: folding darwin too would merge two genuinely distinct files on
7
- // case-sensitive volumes, and the desktop matrix is Windows + Linux.
8
1
  import path from 'node:path';
9
- // Resolved so separator and `..` spellings of one file share a key;
10
- // toLowerCase is locale-independent, so the key stays deterministic.
11
2
  export function pathKey(p, platform = process.platform) {
12
3
  const resolved = platform === 'win32' ? path.win32.resolve(p) : path.posix.resolve(p);
13
4
  return platform === 'win32' ? resolved.toLowerCase() : resolved;
@@ -15,9 +6,6 @@ export function pathKey(p, platform = process.platform) {
15
6
  export function samePath(a, b, platform = process.platform) {
16
7
  return pathKey(a, platform) === pathKey(b, platform);
17
8
  }
18
- // First free name `stem.ext`, `stem-2.ext`, `stem-3.ext`, ... in dir. The
19
- // caller says what "taken" means (names planned in this run, or files on
20
- // disk); existing names are never reused or deleted.
21
9
  export function uniquePath(dir, stem, ext, isTaken) {
22
10
  for (let n = 1;; n++) {
23
11
  const name = n === 1 ? `${stem}${ext}` : `${stem}-${n}${ext}`;
package/dist/plan.js CHANGED
@@ -1,12 +1,8 @@
1
- // Pure planning shared by the headless pipeline and the app UI: which zoom,
2
- // center and tiles cover a track at a given frame size, and how intro/outro
3
- // timing maps to frames. No I/O lives here, so the browser bundle can import
4
- // it; the preview and an export therefore always plan identically.
5
1
  import { project } from './geo.js';
6
2
  import { TILE_SOURCES } from './renderer/tilesources.js';
7
3
  const MIN_ZOOM = 2;
8
4
  const HOVER_ZOOM_FLOOR = 16;
9
- const MIN_TRACK_SPAN_PX = 80; // tiny/hovering tracks stay a useful close-up
5
+ const MIN_TRACK_SPAN_PX = 80;
10
6
  const TILE_SIZE_PX = 256;
11
7
  function fitZoomToTrack(bbox, availW, availH, maxZoom) {
12
8
  for (let zoom = maxZoom; zoom >= MIN_ZOOM; zoom--) {
@@ -19,7 +15,6 @@ function fitZoomToTrack(bbox, availW, availH, maxZoom) {
19
15
  }
20
16
  return MIN_ZOOM;
21
17
  }
22
- // Never zoom a tiny (hovering) track past a useful overview.
23
18
  function pullBackTinyTracks(zoom, bbox) {
24
19
  while (zoom > HOVER_ZOOM_FLOOR) {
25
20
  const northWest = project(bbox.minLon, bbox.maxLat, zoom);
@@ -32,9 +27,6 @@ function pullBackTinyTracks(zoom, bbox) {
32
27
  }
33
28
  return zoom;
34
29
  }
35
- // The map element is 2x the frame (intro/outro zoom-out shows up to 2x the
36
- // area) and in follow mode it also slides across the track extent. With a
37
- // native-zoom limit the tiles live one or more levels below the view zoom.
38
30
  function tilesCovering(centerPx, trackSpanPx, zoom, width, height, follow, maxNativeZoom) {
39
31
  const tileZoom = maxNativeZoom
40
32
  ? Math.min(zoom, maxNativeZoom)
@@ -54,9 +46,6 @@ function tilesCovering(centerPx, trackSpanPx, zoom, width, height, follow, maxNa
54
46
  }
55
47
  return tiles;
56
48
  }
57
- // zoomOut adds surroundings context; follow mode slides the map under a
58
- // centered marker. When the source has a maxNativeZoom below the view zoom,
59
- // tiles are fetched at the native level (Leaflet scales them).
60
49
  export function computeOverview({ bbox, width, height, maxZoom = 19, zoomOut = 0, follow = false, maxNativeZoom = null, zoomOverride = 0, }) {
61
50
  const padX = Math.round(width * 0.08);
62
51
  const padY = Math.round(height * 0.08);
@@ -70,7 +59,6 @@ export function computeOverview({ bbox, width, height, maxZoom = 19, zoomOut = 0
70
59
  zoom = pullBackTinyTracks(fitZoomToTrack(bbox, availW, availH, maxZoom), bbox);
71
60
  zoom = Math.max(MIN_ZOOM, zoom - Math.max(0, Math.floor(zoomOut)));
72
61
  }
73
- // Degenerate (hovering) track: show a close-up around the single point.
74
62
  const northWest = project(bbox.minLon, bbox.maxLat, zoom);
75
63
  const southEast = project(bbox.maxLon, bbox.minLat, zoom);
76
64
  const centerPx = {
@@ -87,9 +75,6 @@ export function computeOverview({ bbox, width, height, maxZoom = 19, zoomOut = 0
87
75
  tiles: tilesCovering(centerPx, trackSpanPx, zoom, width, height, follow, maxNativeZoom),
88
76
  };
89
77
  }
90
- // The one place that turns look settings into view planning: the tile-source
91
- // constraints (maxZoom, native zoom) are part of the rule, so callers never
92
- // hand-roll the computeOverview inputs.
93
78
  export function planView(bbox, width, height, config) {
94
79
  const src = TILE_SOURCES[config.style];
95
80
  return computeOverview({
@@ -103,8 +88,6 @@ export function planView(bbox, width, height, config) {
103
88
  follow: config.view === 'follow',
104
89
  });
105
90
  }
106
- // Intro/outro zoom timing (frames); clamp for very short clips. The clamp is
107
- // returned as data so the owning caller can report it.
108
91
  export function planIntroOutroFrames(config, source) {
109
92
  let introN = Math.max(0, Math.round(config.introSec * source.fps));
110
93
  let outroN = Math.max(0, Math.round(config.outroSec * source.fps));
package/dist/png.js CHANGED
@@ -1,6 +1,3 @@
1
- // A minimal PNG encoder: just enough (IHDR/IDAT/IEND, 8-bit RGB rows) to
2
- // emit valid solid-color tiles for the placeholder fallback, with no
3
- // dependencies beyond zlib.
4
1
  import zlib from 'node:zlib';
5
2
  const CRC_TABLE = (() => {
6
3
  const table = new Int32Array(256);
package/dist/proto.js CHANGED
@@ -1,5 +1,3 @@
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
1
  const MAX_VARINT_BYTES = 10;
4
2
  function readVarint(buf, pos, end) {
5
3
  let value = 0n;
@@ -14,7 +12,6 @@ function readVarint(buf, pos, end) {
14
12
  }
15
13
  return null;
16
14
  }
17
- /** Interpret a 64-bit varint as a signed integer. */
18
15
  function signedVarint(value) {
19
16
  return Number(BigInt.asIntN(64, value));
20
17
  }
@@ -80,7 +77,6 @@ function pushField(fields, fieldNumber, field) {
80
77
  else
81
78
  fields.set(fieldNumber, [field]);
82
79
  }
83
- /** Sub-messages are length-delimited fields; only the first occurrence is decoded. */
84
80
  export function subMessage(buf, fields, fieldNumber) {
85
81
  const field = fields.get(fieldNumber)?.[0];
86
82
  if (!field?.bytesSpan)
@@ -100,3 +96,7 @@ export function firstDouble(fields, fieldNumber) {
100
96
  const value = fields.get(fieldNumber)?.[0]?.doubleValue;
101
97
  return value ?? null;
102
98
  }
99
+ export function firstString(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 CHANGED
@@ -1,7 +1,3 @@
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
1
  export function parseRange(header, size) {
6
2
  if (header === undefined)
7
3
  return null;
@@ -32,9 +28,6 @@ export function parseRange(header, size) {
32
28
  return 'unsatisfiable';
33
29
  return { start, end: Math.min(end, size - 1) };
34
30
  }
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
31
  export function rangePlan(header, size, mime) {
39
32
  const range = parseRange(header, size);
40
33
  if (range === 'unsatisfiable') {
@@ -47,7 +40,6 @@ export function rangePlan(header, size, mime) {
47
40
  const headers = {
48
41
  'Content-Type': mime,
49
42
  'Accept-Ranges': 'bytes',
50
- // A URL-keyed cache must never replay stale bytes from this live local file.
51
43
  'Cache-Control': 'no-store',
52
44
  'Content-Length': String(range === null ? size : range.end - range.start + 1),
53
45
  };
package/dist/render.js CHANGED
@@ -1,6 +1,3 @@
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
1
  import http from 'node:http';
5
2
  import { spawn } from 'node:child_process';
6
3
  import { once } from 'node:events';
@@ -12,9 +9,6 @@ const PAGE_LOAD_TIMEOUT_MS = 60000;
12
9
  const SCREENSHOT_TIMEOUT_MS = 60000;
13
10
  function startServer({ html, style, tileCache, }) {
14
11
  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
12
  let url;
19
13
  try {
20
14
  url = decodeURIComponent((req.url ?? '/').split('?')[0]);
@@ -47,8 +41,6 @@ async function launchBrowser(log, browserPath) {
47
41
  const attempts = [];
48
42
  if (browserPath)
49
43
  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
44
  attempts.push({ channel: 'chrome' }, { channel: 'msedge' }, {});
53
45
  const attemptErrors = [];
54
46
  for (const opt of attempts) {
@@ -61,23 +53,17 @@ async function launchBrowser(log, browserPath) {
61
53
  attemptErrors.push(e);
62
54
  }
63
55
  }
64
- // Every attempt's failure survives in the cause chain; the message keeps
65
- // the final attempt's detail and the remediation steps.
66
56
  throw new Error(`could not launch a Chromium browser (tried explicit path, channel=chrome, channel=msedge, playwright registry): ${errorMessage(attemptErrors[attemptErrors.length - 1])}. ` +
67
57
  'Install Google Chrome or Microsoft Edge, run "npx playwright install chromium", ' +
68
58
  'or pass --browser <path>.', { cause: new AggregateError(attemptErrors, 'all browser launch attempts failed') });
69
59
  }
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.
60
+ // x265's CRF scale sits ~5 points above x264's for the same perceived quality.
74
61
  const CRF = {
75
62
  h264: { 'near-lossless': 16, high: 18, medium: 21, low: 26 },
76
63
  h265: { 'near-lossless': 20, high: 22, medium: 25, low: 30 },
77
64
  };
78
65
  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.
66
+ // h265 gets hvc1: the ffmpeg-default hev1 tag is refused by QuickTime and some NLEs.
81
67
  const codecArgs = encode.codec === 'h265' ? ['-c:v', 'libx265', '-tag:v', 'hvc1'] : ['-c:v', 'libx264'];
82
68
  const ffmpegProcess = spawn(ffmpeg, [
83
69
  '-hide_banner', '-loglevel', 'error', '-y',
@@ -92,9 +78,7 @@ function spawnEncoder(ffmpeg, fpsStr, encode, outPath) {
92
78
  ffmpegProcess.stderr?.on('data', (d) => {
93
79
  stderr += d.toString();
94
80
  });
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.
81
+ // ffmpeg's stdin must never surface an unhandled 'error' (EPIPE on early exit); a drain-waiter must wake when the encoder dies.
98
82
  const closed = new Promise((resolve) => {
99
83
  ffmpegProcess.once('close', (code) => resolve(code));
100
84
  });
@@ -156,12 +140,7 @@ function screenshotOptions(capture) {
156
140
  timeout: SCREENSHOT_TIMEOUT_MS,
157
141
  };
158
142
  }
159
- // One frame: evaluate, screenshot, record and stream it into ffmpeg in
160
- // order.
161
143
  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
144
  const evalStart = Date.now();
166
145
  await page.evaluate((frame) => globalThis.__setFrame(frame), run.frameStart + idx);
167
146
  run.timing.evalMs += Date.now() - evalStart;
@@ -169,8 +148,6 @@ async function captureFrame(run, loop, page, idx) {
169
148
  const buf = await page.screenshot(screenshotOptions(run.capture));
170
149
  const captureMs = Date.now() - captureStart;
171
150
  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
151
  const done = ++loop.capturesDone;
175
152
  run.batches.recordFrame(done, captureMs);
176
153
  const emitStart = Date.now();
@@ -181,7 +158,6 @@ async function captureFrame(run, loop, page, idx) {
181
158
  run.onCapture?.({ done, total: run.frames });
182
159
  }
183
160
  }
184
- // One worker's page and frame loop.
185
161
  async function workerLoop(run, loop, workerId) {
186
162
  const page = await run.active.newPage({
187
163
  viewport: { width: run.width, height: run.height },
@@ -191,8 +167,6 @@ async function workerLoop(run, loop, workerId) {
191
167
  await page.goto(run.url, { waitUntil: 'domcontentloaded', timeout: PAGE_LOAD_TIMEOUT_MS });
192
168
  await page.waitForFunction('window.__READY === true', null, { timeout: PAGE_LOAD_TIMEOUT_MS });
193
169
  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
170
  if (loop.failed)
197
171
  return;
198
172
  if (run.signal?.aborted)
@@ -208,9 +182,6 @@ async function workerLoop(run, loop, workerId) {
208
182
  }
209
183
  run.log(`worker ${workerId} done`);
210
184
  }
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
185
  async function runWorkers(run, workerCount) {
215
186
  const loop = { cursor: 0, capturesDone: 0, failed: false };
216
187
  const settled = await Promise.allSettled(Array.from({ length: workerCount }, (_, i) => workerLoop(run, loop, i + 1).catch((e) => {
@@ -226,7 +197,6 @@ async function runWorkers(run, workerCount) {
226
197
  async function finishEncode(encoder, stream, encodeSpan, log, outPath) {
227
198
  await stream.flushReady();
228
199
  stream.end();
229
- // `closed` (not `once(ffmpeg, 'close')`): ffmpeg may already have exited.
230
200
  const code = await encoder.closed;
231
201
  encodeSpan.setAttribute('render.ffmpeg.exitCode', code ?? -1);
232
202
  if (code !== 0) {
@@ -238,9 +208,6 @@ function formatProfile(profile, workerCount) {
238
208
  return (`profile: eval=${(profile.evalMs / 1000).toFixed(1)}s capture=${(profile.captureMs / 1000).toFixed(1)}s ` +
239
209
  `encode-backpressure=${(profile.emitMs / 1000).toFixed(1)}s (summed over ${workerCount} workers)`);
240
210
  }
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
211
  export class FrameBatchRecorder {
245
212
  tracer;
246
213
  parent;
@@ -256,8 +223,6 @@ export class FrameBatchRecorder {
256
223
  this.cadence = cadence;
257
224
  }
258
225
  recordFrame(capturedSoFar, captureMs) {
259
- // close() is permanent: a straggling frame must not re-open a batch under
260
- // the already-ended capture span.
261
226
  if (this.closed)
262
227
  return;
263
228
  this.openSpan ??= this.tracer.startSpan('render.capture.batch', {
@@ -277,7 +242,6 @@ export class FrameBatchRecorder {
277
242
  span.setAttribute('render.frame.maxMs', Math.max(...durations));
278
243
  span.end();
279
244
  }
280
- // A half-open batch at close time is normal (nothing in flight).
281
245
  close(error) {
282
246
  if (this.closed)
283
247
  return;
@@ -291,15 +255,10 @@ export class FrameBatchRecorder {
291
255
  this.durations = [];
292
256
  }
293
257
  }
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
258
  async function captureAndEncode(active, env) {
298
259
  const { ctx, tracer, renderSpan, url, timing, workerCount } = env;
299
260
  const { fpsStr, codec, quality, preset, outPath, signal, width, height, frames, frameStart, capture, log, onCapture, tools, } = ctx;
300
261
  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
262
  const killOnAbort = () => encoder.kill();
304
263
  signal?.addEventListener('abort', killOnAbort, { once: true });
305
264
  const stream = new OrderedFrameStream(encoder);
@@ -338,8 +297,6 @@ async function captureAndEncode(active, env) {
338
297
  signal?.removeEventListener('abort', killOnAbort);
339
298
  }
340
299
  }
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
300
  function reportProfile(env) {
344
301
  const { ctx, timing, renderSpan, workerCount } = env;
345
302
  const profile = {
@@ -355,11 +312,6 @@ function reportProfile(env) {
355
312
  ctx.log(formatProfile(profile, workerCount));
356
313
  return { profile };
357
314
  }
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
315
  export async function renderVideo(opts) {
364
316
  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
317
  const tracer = trace?.tracer ?? NOOP_TRACER;
@@ -392,8 +344,6 @@ export async function renderVideo(opts) {
392
344
  const timing = { evalMs: 0, captureMs: 0, emitMs: 0 };
393
345
  const { server, url } = await startServer({ html, style, tileCache });
394
346
  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
347
  let browser = null;
398
348
  try {
399
349
  browser = await launchBrowser(log, browserPath);
@@ -1,8 +1,3 @@
1
- // Renderer markup and styling, shared verbatim by the generated page and the
2
- // app's map islands so both look and measure identically. Element ids are the
3
- // renderer's DOM contract. The styles are scoped to one scene host each: the
4
- // app mounts two scenes at once (player island and export preview), so bare
5
- // selectors would let one scene's scale values restyle the other.
6
1
  export function sceneCss(src, theme, width, height, scale, scope) {
7
2
  const at = `.${scope}`;
8
3
  return `
@@ -123,7 +118,6 @@ export function droneMarkerMarkup(coreColor) {
123
118
  '" stroke="rgba(255,255,255,0.9)" stroke-width="0.9" stroke-linejoin="round"/></svg>' +
124
119
  '</div></div>');
125
120
  }
126
- /** Returns the element the renderer's DOM contract guarantees. */
127
121
  export function el(root, selector) {
128
122
  const found = root.querySelector(selector);
129
123
  if (!found)
@@ -1,5 +1,3 @@
1
- // Pure viewport and timeline math for the shared renderer. Kept free of DOM
2
- // and Leaflet so the frame-exact behaviors stay unit-testable.
3
1
  export function computeScale(width, height) {
4
2
  return Math.max(0.7, Math.min(2.2, Math.min(width, height) / 1024));
5
3
  }
@@ -7,7 +5,6 @@ export function smoothstep(t) {
7
5
  const clamped = Math.max(0, Math.min(1, t));
8
6
  return clamped * clamped * (3 - 2 * clamped);
9
7
  }
10
- // Intro/outro zoom-out: 0.5 = one zoom level further out, smoothstepped.
11
8
  export function introOutroScale(i, introN, outroN, totalN) {
12
9
  let kIn = 1;
13
10
  let kOut = 1;
@@ -22,7 +19,6 @@ export function introOutroScale(i, introN, outroN, totalN) {
22
19
  export function metersPerPixel(lat, zoom) {
23
20
  return (156543.033928 * Math.cos((lat * Math.PI) / 180)) / Math.pow(2, zoom);
24
21
  }
25
- // The map never zooms during a render, so the scale bar picks one step once.
26
22
  export function scaleBarMeters(mPerPx, maxPx) {
27
23
  const steps = [5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000, 10000];
28
24
  let best = steps[0];
@@ -1,5 +1 @@
1
- // The minimal Leaflet surface the shared renderer touches. Consumers pass the
2
- // real namespace in (the generated page takes window.L, the app its bundled
3
- // module import), so this code stays free of bundler and global assumptions
4
- // and tests can drive it with a fake.
5
1
  export {};
@@ -1,16 +1,3 @@
1
- // The shared map renderer: it receives all telemetry inline (no fetch), paints
2
- // the map once, and exposes setFrame(i) for per-frame marker/trail updates.
3
- // Headless capture workers (via the generated page's window.__setFrame bridge)
4
- // and the app's React map island both drive this one implementation;
5
- // setFrame resolves after the canvas has painted so screenshots are
6
- // frame-exact. update(data) restyles in place for the app's settings panel,
7
- // rebuilding only the decorations the new settings actually invalidate.
8
- //
9
- // Views:
10
- // overview - static map fitted to the whole track (trail grows with time)
11
- // follow - drone marker stays in the frame center and the map slides under
12
- // it (all tiles are loaded once up-front; the per-frame move is a
13
- // pure CSS transform, so no tile loads happen mid-render)
14
1
  import { TILE_SOURCES } from './tilesources.js';
15
2
  import { droneMarkerMarkup, el, hudMarkup, mapMarkup, quietAttributionLinks, sceneCss } from './dom.js';
16
3
  import { computeScale, introOutroScale, metersPerPixel, scaleBarMeters } from './framemath.js';
@@ -24,9 +11,6 @@ function setChipText(chip, value, format) {
24
11
  return;
25
12
  chip.textContent = value === null || value === undefined ? '--' : format(value);
26
13
  }
27
- // Per-scene style scope: the app mounts two scenes at once (the player island
28
- // and the export preview), and one scene's scale values must never restyle the
29
- // other's elements.
30
14
  let scopeCount = 0;
31
15
  class SceneState {
32
16
  ready;
@@ -84,9 +68,7 @@ class SceneState {
84
68
  this.frameEl = el(host, '#map-frame');
85
69
  this.scalelineEl = el(host, '#scaleline');
86
70
  this.scaletextEl = el(host, '#scaletext');
87
- // Before the decorations below: Leaflet defers marker DOM creation until
88
- // the map has a view, so the arrow/wrap elements only exist after this
89
- // first call.
71
+ // Leaflet only creates marker DOM once the map has a view: layoutMap() must precede buildDecor() so the arrow/wrap elements exist.
90
72
  this.layoutMap();
91
73
  this.decor = this.buildDecor();
92
74
  this.rebuildHud();
@@ -110,12 +92,10 @@ class SceneState {
110
92
  return data.lat.map((la, i) => [la, data.lon[i]]);
111
93
  }
112
94
  applyChrome() {
113
- this.styleEl.textContent = sceneCss(TILE_SOURCES[this.data.style], themeFor(this.data.style), this.data.width, this.data.height, this.scale(), this.scopeClass);
95
+ this.styleEl.textContent = sceneCss(TILE_SOURCES[this.data.style], themeFor(this.data.style, this.data.trailColor), this.data.width, this.data.height, this.scale(), this.scopeClass);
114
96
  this.attrEl.innerHTML = this.data.attribution;
115
97
  quietAttributionLinks(this.attrEl);
116
98
  }
117
- // The map fills its frame at any size (headless: the export canvas; app:
118
- // the pane currently holding it), so every frame size change re-lays out.
119
99
  layoutMap() {
120
100
  const { data, map, mapEl, frameEl } = this;
121
101
  const vw = frameEl.clientWidth || data.width;
@@ -137,7 +117,6 @@ class SceneState {
137
117
  map.invalidateSize();
138
118
  map.setView(data.view === 'follow' ? this.bb.getCenter() : [data.center.lat, data.center.lon], data.zoom);
139
119
  const c0 = map.project(map.getCenter(), data.zoom);
140
- // Static scale bar (the map never zooms during a render).
141
120
  const latC = data.view === 'follow' ? this.bb.getCenter().lat : data.center.lat;
142
121
  const mPerPx = metersPerPixel(latC, data.zoom);
143
122
  const bestM = scaleBarMeters(mPerPx, 110 * this.scale());
@@ -172,11 +151,9 @@ class SceneState {
172
151
  layers.push(ghost);
173
152
  return layers;
174
153
  }
175
- // The live trail layers (empty until the controller fills them): glow,
176
- // casing and core, thickest first so the core stays on top.
154
+ // Creation order sets stacking: thickest first so the core stays on top.
177
155
  buildTrailLayers(theme) {
178
- // All geometry is pre-decimated (smoothFactor 0 skips Leaflet's own
179
- // simplification) and the canvas renderer keeps redraws rAF-batched.
156
+ // smoothFactor 0 keeps Leaflet from re-simplifying the pre-decimated path.
180
157
  const wCore = Math.max(3, 5.5 * this.scale());
181
158
  const trailGlow = this.L.polyline([], {
182
159
  color: theme.glow,
@@ -197,7 +174,7 @@ class SceneState {
197
174
  });
198
175
  trailCasing.addTo(this.map);
199
176
  const trail = this.L.polyline([], {
200
- color: theme.core,
177
+ color: theme.trailCore,
201
178
  weight: wCore,
202
179
  opacity: 1,
203
180
  lineCap: 'round',
@@ -230,7 +207,7 @@ class SceneState {
230
207
  return { startDot, drone };
231
208
  }
232
209
  buildDecor() {
233
- const theme = themeFor(this.data.style);
210
+ const theme = themeFor(this.data.style, this.data.trailColor);
234
211
  const s = this.scale();
235
212
  const ghostLatlngs = this.data.trailLat.map((la, i) => [la, this.data.trailLon[i]]);
236
213
  const ghostDash = Math.round(7 * s) + ' ' + Math.round(9 * s);
@@ -297,9 +274,7 @@ class SceneState {
297
274
  const k = introOutroScale(i, this.data.introN, this.data.outroN, this.data.lat.length);
298
275
  this.updateTransform(i, k);
299
276
  this.updateHud(i);
300
- // Canvas painting is deferred to requestAnimationFrame; the headless
301
- // capture awaits this barrier so screenshots never catch the previous
302
- // frame.
277
+ // Canvas painting is deferred to requestAnimationFrame
303
278
  return new Promise((resolve) => {
304
279
  requestAnimationFrame(() => {
305
280
  requestAnimationFrame(() => resolve());
@@ -318,14 +293,14 @@ class SceneState {
318
293
  this.bb = this.L.latLngBounds(this.latlngs);
319
294
  }
320
295
  const chromeChanged = next.style !== prev.style ||
296
+ next.trailColor !== prev.trailColor ||
321
297
  next.width !== prev.width ||
322
298
  next.height !== prev.height ||
323
299
  next.attribution !== prev.attribution;
324
300
  if (chromeChanged)
325
301
  this.applyChrome();
326
302
  if (next.style !== prev.style) {
327
- // The zoom constraints are per source (topo tiles are native to z17),
328
- // so a style switch swaps the layer instead of only its URL.
303
+ // Zoom constraints are per tile layer (topo is native to z17), so a style switch swaps the layer instead of only its URL.
329
304
  this.tiles.remove();
330
305
  this.tiles = this.makeTileLayer(next.tileUrl, next.style);
331
306
  this.tiles.addTo(this.map);
@@ -334,6 +309,7 @@ class SceneState {
334
309
  this.tiles.setUrl(next.tileUrl);
335
310
  }
336
311
  const decorInvalidated = next.style !== prev.style ||
312
+ next.trailColor !== prev.trailColor ||
337
313
  next.trailLat !== prev.trailLat ||
338
314
  next.lat !== prev.lat ||
339
315
  next.width !== prev.width ||