drone-path-core 1.0.0-rc1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +6 -3
  2. package/dist/cammeta.d.ts +3 -0
  3. package/dist/cammeta.js +23 -35
  4. package/dist/decimate.d.ts +11 -0
  5. package/dist/decimate.js +84 -0
  6. package/dist/errors.d.ts +7 -11
  7. package/dist/errors.js +9 -15
  8. package/dist/exec-tool.d.ts +1 -0
  9. package/dist/exec-tool.js +5 -1
  10. package/dist/ffmpeg.d.ts +17 -3
  11. package/dist/ffmpeg.js +25 -11
  12. package/dist/flight-grouping.d.ts +21 -0
  13. package/dist/flight-grouping.js +104 -0
  14. package/dist/geo.d.ts +3 -0
  15. package/dist/geo.js +3 -3
  16. package/dist/ground-footprint.d.ts +18 -0
  17. package/dist/ground-footprint.js +66 -0
  18. package/dist/keyframes.d.ts +37 -0
  19. package/dist/keyframes.js +213 -0
  20. package/dist/launch-redaction.d.ts +2 -0
  21. package/dist/launch-redaction.js +39 -0
  22. package/dist/mp4-cammeta.d.ts +7 -0
  23. package/dist/mp4-cammeta.js +227 -0
  24. package/dist/nle-markers.d.ts +16 -0
  25. package/dist/nle-markers.js +208 -0
  26. package/dist/shot-segmentation.d.ts +17 -0
  27. package/dist/shot-segmentation.js +428 -0
  28. package/dist/spatial.d.ts +15 -0
  29. package/dist/spatial.js +146 -0
  30. package/dist/srt-sidecar.d.ts +1 -0
  31. package/dist/srt-sidecar.js +28 -3
  32. package/dist/srt.d.ts +1 -1
  33. package/dist/srt.js +2 -2
  34. package/dist/telemetry-math.js +10 -7
  35. package/dist/telemetry.d.ts +11 -2
  36. package/dist/telemetry.js +22 -20
  37. package/dist/track-antimeridian.d.ts +2 -0
  38. package/dist/track-antimeridian.js +28 -0
  39. package/dist/track-geojson.d.ts +1 -0
  40. package/dist/track-geojson.js +4 -0
  41. package/dist/track-gpx.d.ts +1 -0
  42. package/dist/track-gpx.js +34 -10
  43. package/dist/track-kml.d.ts +1 -0
  44. package/dist/track-kml.js +12 -4
  45. package/dist/track-kmz.js +19 -24
  46. package/dist/track-write.js +9 -6
  47. package/dist/validation.d.ts +2 -0
  48. package/dist/validation.js +6 -0
  49. package/package.json +1 -1
@@ -0,0 +1,146 @@
1
+ import { DEG_TO_RAD, EARTH_RADIUS_M, RAD_TO_DEG } from './geo.js';
2
+ const ANGLE_EPSILON = 1e-12;
3
+ export function longitudeRanges({ minLon, maxLon }) {
4
+ if (minLon > maxLon)
5
+ return [[minLon, 180], [-180, maxLon]];
6
+ if (minLon === -180 && maxLon === 180)
7
+ return [[minLon, maxLon]];
8
+ if (minLon === -180)
9
+ return [[minLon, maxLon], [180, 180]];
10
+ if (maxLon === 180)
11
+ return [[minLon, maxLon], [-180, -180]];
12
+ return [[minLon, maxLon]];
13
+ }
14
+ export function bboxIntersects(a, b) {
15
+ if (a.maxLat < b.minLat || b.maxLat < a.minLat)
16
+ return false;
17
+ const ranges = longitudeRanges(b);
18
+ return longitudeRanges(a).some(([west, east]) => ranges.some(([otherWest, otherEast]) => west <= otherEast && otherWest <= east));
19
+ }
20
+ export function resolveTrackBbox(bbox, segments) {
21
+ if (bbox.maxLon - bbox.minLon <= 180)
22
+ return bbox;
23
+ // Archived extrema still describe real fixes even if decimation dropped them.
24
+ const ranges = [[bbox.minLon, bbox.minLon], [bbox.maxLon, bbox.maxLon]];
25
+ let crossesAntimeridian = false;
26
+ for (const segment of segments) {
27
+ if (segment.length === 1)
28
+ ranges.push([segment[0].lon, segment[0].lon]);
29
+ for (let i = 1; i < segment.length; i++) {
30
+ const west = Math.min(segment[i - 1].lon, segment[i].lon);
31
+ const east = Math.max(segment[i - 1].lon, segment[i].lon);
32
+ if (east - west === 180)
33
+ return { ...bbox, minLon: -180, maxLon: 180 };
34
+ if (east - west > 180) {
35
+ crossesAntimeridian = true;
36
+ ranges.push([-180, west], [east, 180]);
37
+ }
38
+ else {
39
+ ranges.push([west, east]);
40
+ }
41
+ }
42
+ }
43
+ if (!crossesAntimeridian)
44
+ return bbox;
45
+ // Leave out only the largest uncovered interval. Every indexed arc and
46
+ // recorded extremum stays inside the resulting circular bounding box.
47
+ ranges.sort(([westA], [westB]) => westA - westB);
48
+ let end = -180;
49
+ let largestGap = 0;
50
+ let minLon = -180;
51
+ let maxLon = 180;
52
+ for (const [west, east] of ranges) {
53
+ if (west - end > largestGap) {
54
+ largestGap = west - end;
55
+ minLon = west;
56
+ maxLon = end;
57
+ }
58
+ end = Math.max(end, east);
59
+ }
60
+ return { ...bbox, minLon, maxLon };
61
+ }
62
+ function wrapLongitude(lon) {
63
+ if (lon < -180)
64
+ return lon + 360;
65
+ if (lon > 180)
66
+ return lon - 360;
67
+ return lon;
68
+ }
69
+ export function radiusBbox(center, radiusM) {
70
+ // Round outward so a hit on the radius boundary survives the SQL prefilter.
71
+ const angle = radiusM / EARTH_RADIUS_M + ANGLE_EPSILON;
72
+ const degrees = angle * RAD_TO_DEG;
73
+ const minLat = Math.max(-90, center.lat - degrees);
74
+ const maxLat = Math.min(90, center.lat + degrees);
75
+ if (minLat === -90 || maxLat === 90)
76
+ return { minLat, maxLat, minLon: -180, maxLon: 180 };
77
+ const longitudeDelta = Math.asin(Math.min(1, Math.sin(angle) / Math.cos(center.lat * DEG_TO_RAD))) * RAD_TO_DEG;
78
+ return {
79
+ minLat, maxLat,
80
+ minLon: wrapLongitude(center.lon - longitudeDelta),
81
+ maxLon: wrapLongitude(center.lon + longitudeDelta),
82
+ };
83
+ }
84
+ function unitVector({ lat, lon }) {
85
+ if (Math.abs(lat) === 90)
86
+ return [0, 0, Math.sign(lat)];
87
+ const phi = lat * DEG_TO_RAD;
88
+ const lambda = (lon === 180 ? -180 : lon) * DEG_TO_RAD;
89
+ return [Math.cos(phi) * Math.cos(lambda), Math.cos(phi) * Math.sin(lambda), Math.sin(phi)];
90
+ }
91
+ function dot(a, b) {
92
+ return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
93
+ }
94
+ function cross(a, b) {
95
+ return [
96
+ a[1] * b[2] - a[2] * b[1],
97
+ a[2] * b[0] - a[0] * b[2],
98
+ a[0] * b[1] - a[1] * b[0],
99
+ ];
100
+ }
101
+ function distanceM(a, b) {
102
+ return EARTH_RADIUS_M * Math.atan2(Math.hypot(...cross(a, b)), dot(a, b));
103
+ }
104
+ function projectOntoArc(query, start, end, startTime, endTime) {
105
+ const normal = cross(start, end);
106
+ const sine = Math.hypot(...normal);
107
+ // Coincident fixes and antipodal endpoints do not define a unique great circle.
108
+ if (sine <= Number.EPSILON)
109
+ return null;
110
+ const arc = Math.atan2(sine, dot(start, end));
111
+ const tangent = cross(normal, start);
112
+ const angle = Math.atan2(dot(query, tangent) / sine, dot(query, start));
113
+ if (angle <= 0 || angle >= arc)
114
+ return null;
115
+ const alongStart = Math.cos(angle);
116
+ const alongTangent = Math.sin(angle) / sine;
117
+ const offset = (index) => start[index] * alongStart + tangent[index] * alongTangent;
118
+ return {
119
+ tSec: startTime + (endTime - startTime) * angle / arc,
120
+ distanceM: distanceM(query, [offset(0), offset(1), offset(2)]),
121
+ };
122
+ }
123
+ export function nearestOnTrack(query, segments) {
124
+ const target = unitVector(query);
125
+ let best = null;
126
+ function consider(candidate) {
127
+ if (best === null || candidate.distanceM < best.distanceM ||
128
+ (candidate.distanceM === best.distanceM && candidate.tSec < best.tSec)) {
129
+ best = candidate;
130
+ }
131
+ }
132
+ for (const segment of segments) {
133
+ let previous;
134
+ for (const point of segment) {
135
+ const vector = unitVector(point);
136
+ consider({ distanceM: distanceM(target, vector), tSec: point.tSec });
137
+ if (previous) {
138
+ const interior = projectOntoArc(target, previous.vector, vector, previous.tSec, point.tSec);
139
+ if (interior)
140
+ consider(interior);
141
+ }
142
+ previous = { vector, tSec: point.tSec };
143
+ }
144
+ }
145
+ return best;
146
+ }
@@ -1 +1,2 @@
1
1
  export declare function findSrtSidecar(videoPath: string): string | null;
2
+ export declare function createSrtSidecarLookup(): (videoPath: string) => Promise<string | null>;
@@ -1,13 +1,38 @@
1
1
  import fs from 'node:fs';
2
+ import { readdir } from 'node:fs/promises';
2
3
  import path from 'node:path';
4
+ function sidecarName(videoPath) {
5
+ const base = path.basename(videoPath).replace(/\.[^.]+$/, '');
6
+ return `${base.toLowerCase()}.srt`;
7
+ }
3
8
  export function findSrtSidecar(videoPath) {
4
9
  const dir = path.dirname(videoPath);
5
- const base = path.basename(videoPath).replace(/\.[^.]+$/, '');
6
- const sidecarName = `${base.toLowerCase()}.srt`;
10
+ const name = sidecarName(videoPath);
7
11
  for (const fileName of fs.readdirSync(dir)) {
8
- if (fileName.toLowerCase() === sidecarName) {
12
+ if (fileName.toLowerCase() === name) {
9
13
  return path.join(dir, fileName);
10
14
  }
11
15
  }
12
16
  return null;
13
17
  }
18
+ async function readSidecars(dir) {
19
+ const sidecars = new Map();
20
+ for (const name of await readdir(dir)) {
21
+ const key = name.toLowerCase();
22
+ if (key.endsWith('.srt') && !sidecars.has(key))
23
+ sidecars.set(key, path.join(dir, name));
24
+ }
25
+ return sidecars;
26
+ }
27
+ export function createSrtSidecarLookup() {
28
+ const directories = new Map();
29
+ return async (videoPath) => {
30
+ const dir = path.dirname(videoPath);
31
+ let sidecars = directories.get(dir);
32
+ if (!sidecars) {
33
+ sidecars = readSidecars(dir);
34
+ directories.set(dir, sidecars);
35
+ }
36
+ return (await sidecars).get(sidecarName(videoPath)) ?? null;
37
+ };
38
+ }
package/dist/srt.d.ts CHANGED
@@ -15,5 +15,5 @@ interface SrtParseResult {
15
15
  count: number;
16
16
  }
17
17
  export declare function parseSrtText(text: string): SrtParseResult;
18
- export declare function parseSrt(path: string): Promise<SrtParseResult>;
18
+ export declare function parseSrt(path: string, signal?: AbortSignal): Promise<SrtParseResult>;
19
19
  export {};
package/dist/srt.js CHANGED
@@ -93,6 +93,6 @@ export function parseSrtText(text) {
93
93
  }
94
94
  return { cues, noLock, count: cues.length };
95
95
  }
96
- export async function parseSrt(path) {
97
- return parseSrtText(await readFile(path, 'utf8'));
96
+ export async function parseSrt(path, signal) {
97
+ return parseSrtText(await readFile(path, { encoding: 'utf8', signal }));
98
98
  }
@@ -102,6 +102,13 @@ function computeTrackStats(fixes) {
102
102
  }
103
103
  return { bbox, trackDistanceM };
104
104
  }
105
+ function mapWindow(length, span, combine) {
106
+ const out = new Array(length);
107
+ for (let k = 0; k < length; k++) {
108
+ out[k] = combine(Math.max(0, k - span), Math.min(length - 1, k + span));
109
+ }
110
+ return out;
111
+ }
105
112
  function computeSpeedByFix(fixes) {
106
113
  if (fixes.length === 2) {
107
114
  const dt = fixes[1].tSec - fixes[0].tSec;
@@ -117,9 +124,7 @@ function computeSpeedByFix(fixes) {
117
124
  }
118
125
  rawSpeed[0] = rawSpeed[1] ?? 0;
119
126
  rawSpeed[fixes.length - 1] = rawSpeed[fixes.length - 2] ?? 0;
120
- return fixes.map((_, k) => {
121
- const lo = Math.max(0, k - SPEED_SMOOTHING_SPAN);
122
- const hi = Math.min(fixes.length - 1, k + SPEED_SMOOTHING_SPAN);
127
+ return mapWindow(fixes.length, SPEED_SMOOTHING_SPAN, (lo, hi) => {
123
128
  let sum = 0;
124
129
  let count = 0;
125
130
  for (let j = lo; j <= hi; j++) {
@@ -144,9 +149,7 @@ function computeHeadingByFix(fixes, speedByFix) {
144
149
  }
145
150
  fillHeadingGaps(rawHeading);
146
151
  const defaultHeading = rawHeading[0] ?? firstKnownHeading(rawHeading) ?? 0;
147
- const headingByFix = fixes.map((_, k) => {
148
- const lo = Math.max(0, k - HEADING_SMOOTHING_SPAN);
149
- const hi = Math.min(fixes.length - 1, k + HEADING_SMOOTHING_SPAN);
152
+ const headingByFix = mapWindow(fixes.length, HEADING_SMOOTHING_SPAN, (lo, hi) => {
150
153
  const window = [];
151
154
  for (let j = lo; j <= hi; j++) {
152
155
  window.push(rawHeading[j] ?? defaultHeading);
@@ -224,7 +227,7 @@ function buildFrameData(samples, fixes, frames, fpsValue, speedByFix, headingByF
224
227
  }
225
228
  function bridgeMissingFramePositions(frameData) {
226
229
  const first = frameData.find((d) => d.fix !== null);
227
- const last = [...frameData].reverse().find((d) => d.fix !== null);
230
+ const last = frameData.findLast((d) => d.fix !== null);
228
231
  if (!first || !last)
229
232
  return;
230
233
  let lead = 0;
@@ -1,6 +1,7 @@
1
1
  import type { GimbalDeviceConstants } from './cammeta-decode.js';
2
+ import type { CamMetaStream } from './ffmpeg.js';
2
3
  import type { FfmpegToolPaths } from './ffmpeg-tools.js';
3
- import type { Telemetry } from './telemetry-math.js';
4
+ import type { Telemetry, TelemetrySamples } from './telemetry-math.js';
4
5
  import type { TelemetryFrameInput } from './telemetry-json.js';
5
6
  import type { TrackRecord } from './track.js';
6
7
  export interface RecordingTelemetry {
@@ -10,9 +11,17 @@ export interface RecordingTelemetry {
10
11
  protoFile: string | null;
11
12
  gimbalDevice: GimbalDeviceConstants | null;
12
13
  }
13
- export declare function loadTelemetry(videoPath: string, { frames, fpsValue, durationSec, tools, }: {
14
+ export interface SourceSamples extends TelemetrySamples {
15
+ frameValues: TelemetryFrameInput[];
16
+ trackValues: TrackRecord[];
17
+ protoFile: string | null;
18
+ gimbalDevice: GimbalDeviceConstants | null;
19
+ }
20
+ export declare function loadTelemetrySamples(tools: FfmpegToolPaths, videoPath: string, durationSec: number, camMeta?: CamMetaStream | null, signal?: AbortSignal, sidecar?: string | null): Promise<SourceSamples | null>;
21
+ export declare function loadTelemetry(videoPath: string, { frames, fpsValue, durationSec, tools, camMeta, }: {
14
22
  frames: number;
15
23
  fpsValue: number;
16
24
  durationSec: number;
17
25
  tools: FfmpegToolPaths;
26
+ camMeta?: CamMetaStream | null;
18
27
  }): Promise<RecordingTelemetry>;
package/dist/telemetry.js CHANGED
@@ -1,4 +1,4 @@
1
- import { ERR_NO_TELEMETRY } from './errors.js';
1
+ import { ERR_NO_TELEMETRY, codedError } from './errors.js';
2
2
  import { parseSrt } from './srt.js';
3
3
  import { findSrtSidecar } from './srt-sidecar.js';
4
4
  import { parseCamMeta } from './cammeta.js';
@@ -33,31 +33,27 @@ function camSampleToFrameValues(sample) {
33
33
  whiteBalanceCctK: sample.whiteBalanceCctK,
34
34
  };
35
35
  }
36
- async function loadSamples(tools, videoPath, durationSec) {
37
- const cam = await parseCamMeta(tools, videoPath, durationSec, { keepAll: true });
36
+ function toTrackRecords(items, toValues) {
37
+ return items.map((item) => ({ ...toValues(item), tSec: item.tSec }));
38
+ }
39
+ export async function loadTelemetrySamples(tools, videoPath, durationSec, camMeta, signal, sidecar) {
40
+ const cam = await parseCamMeta(tools, videoPath, durationSec, { keepAll: true, stream: camMeta, signal });
38
41
  if (cam) {
39
42
  const fixSamples = cam.samples.filter((sample) => sample.fix !== null);
40
- if (fixSamples.length === 0) {
41
- throw new Error(`${ERR_NO_TELEMETRY}the CAM meta (DVTM) stream has no GPS fix pairs; ` +
42
- 'the .SRT sidecar is only consulted when no CAM meta stream is present');
43
- }
44
43
  return {
45
44
  samples: fixSamples,
46
45
  source: 'cammeta',
47
46
  method: cam.method,
48
47
  noLock: cam.noLock,
49
48
  frameValues: cam.method === 'dvtm-packets' ? cam.samples.map(camSampleToFrameValues) : [],
50
- trackValues: cam.samples.map((sample) => ({
51
- ...camSampleToFrameValues(sample),
52
- tSec: sample.tSec,
53
- })),
49
+ trackValues: toTrackRecords(cam.samples, camSampleToFrameValues),
54
50
  protoFile: cam.protoFile,
55
51
  gimbalDevice: cam.gimbalDevice,
56
52
  };
57
53
  }
58
- const srtPath = findSrtSidecar(videoPath);
54
+ const srtPath = sidecar === undefined ? findSrtSidecar(videoPath) : sidecar;
59
55
  if (srtPath) {
60
- const parsed = await parseSrt(srtPath);
56
+ const parsed = await parseSrt(srtPath, signal);
61
57
  if (parsed.count === 0)
62
58
  throw new Error(`SRT sidecar has no cues: ${srtPath}`);
63
59
  return {
@@ -72,18 +68,24 @@ async function loadSamples(tools, videoPath, durationSec) {
72
68
  method: 'srt-cues',
73
69
  noLock: parsed.noLock,
74
70
  frameValues: parsed.cues.map(srtCueToFrameValues),
75
- trackValues: parsed.cues.map((cue) => ({
76
- ...srtCueToFrameValues(cue),
77
- tSec: cue.tSec,
78
- })),
71
+ trackValues: toTrackRecords(parsed.cues, srtCueToFrameValues),
79
72
  protoFile: null,
80
73
  gimbalDevice: null,
81
74
  };
82
75
  }
83
- throw new Error(`${ERR_NO_TELEMETRY}no CAM meta (DVTM) stream and no .SRT sidecar`);
76
+ return null;
84
77
  }
85
- export async function loadTelemetry(videoPath, { frames, fpsValue, durationSec, tools, }) {
86
- const loaded = await loadSamples(tools, videoPath, durationSec);
78
+ export async function loadTelemetry(videoPath, { frames, fpsValue, durationSec, tools, camMeta, }) {
79
+ const loaded = await loadTelemetrySamples(tools, videoPath, durationSec, camMeta);
80
+ if (!loaded) {
81
+ throw codedError(`${ERR_NO_TELEMETRY}no CAM meta (DVTM) stream and no .SRT sidecar`, {
82
+ code: 'NO_TELEMETRY',
83
+ });
84
+ }
85
+ if (loaded.source === 'cammeta' && loaded.samples.length === 0) {
86
+ throw codedError(`${ERR_NO_TELEMETRY}the CAM meta (DVTM) stream has no GPS fix pairs; ` +
87
+ 'the .SRT sidecar is only consulted when no CAM meta stream is present', { code: 'NO_TELEMETRY' });
88
+ }
87
89
  const { frameValues, trackValues, protoFile, gimbalDevice, ...samples } = loaded;
88
90
  return {
89
91
  telemetry: computeTelemetry(samples, { frames, fpsValue }),
@@ -0,0 +1,2 @@
1
+ import type { LatLon } from './geo.js';
2
+ export declare function splitTrackAtAntimeridian(segments: readonly (readonly LatLon[])[]): LatLon[][];
@@ -0,0 +1,28 @@
1
+ export function splitTrackAtAntimeridian(segments) {
2
+ const split = [];
3
+ for (const segment of segments) {
4
+ const [first, ...points] = segment;
5
+ if (!first)
6
+ continue;
7
+ let run = [first];
8
+ let previous = first;
9
+ for (const point of points) {
10
+ const delta = point.lon - previous.lon;
11
+ if (Math.abs(delta) > 180) {
12
+ const boundary = delta < 0 ? 180 : -180;
13
+ const endLon = point.lon + 2 * boundary;
14
+ const step = endLon - previous.lon;
15
+ const progress = step === 0 ? 0 : (boundary - previous.lon) / step;
16
+ const lat = previous.lat + (point.lat - previous.lat) * progress;
17
+ if (progress > 0)
18
+ run.push({ lat, lon: boundary });
19
+ split.push(run);
20
+ run = progress < 1 ? [{ lat, lon: -boundary }] : [];
21
+ }
22
+ run.push(point);
23
+ previous = point;
24
+ }
25
+ split.push(run);
26
+ }
27
+ return split;
28
+ }
@@ -1,2 +1,3 @@
1
1
  import type { TrackSegment } from './track.js';
2
+ export declare function serializeGeoJsonTracks(tracks: readonly (readonly TrackSegment[])[]): string;
2
3
  export declare function serializeGeoJson(segments: readonly TrackSegment[]): string;
@@ -20,6 +20,10 @@ function itemLines(indents, itemsBySegment) {
20
20
  });
21
21
  return lines;
22
22
  }
23
+ export function serializeGeoJsonTracks(tracks) {
24
+ const features = tracks.map((segments) => serializeGeoJson(segments.map((segment) => segment.length === 1 ? [segment[0], segment[0]] : segment)).trimEnd());
25
+ return `{"type":"FeatureCollection","features":[${features.join(',\n')}]}\n`;
26
+ }
23
27
  export function serializeGeoJson(segments) {
24
28
  const allTimed = segments.length > 0 &&
25
29
  segments.every((segment) => segment.every((vertex) => vertex.timeMs !== null));
@@ -1,2 +1,3 @@
1
1
  import type { TrackSegment } from './track.js';
2
2
  export declare function serializeGpx(segments: readonly TrackSegment[]): string;
3
+ export declare function serializeGpxTracks(tracks: readonly (readonly TrackSegment[])[]): string;
package/dist/track-gpx.js CHANGED
@@ -2,15 +2,33 @@
2
2
  // and a <time> only where the vertex carries trustworthy UTC. No metadata
3
3
  // wall-clock or version strings, so identical input yields identical bytes.
4
4
  import { isoUtc } from './track.js';
5
+ function decimal(value) {
6
+ const text = String(value);
7
+ const scientific = /^(-?)(\d)(?:\.(\d+))?e([+-]?\d+)$/u.exec(text);
8
+ if (!scientific)
9
+ return text;
10
+ const [, sign, digit, fraction = '', exponent] = scientific;
11
+ const digits = digit + fraction;
12
+ const position = 1 + Number(exponent);
13
+ if (position <= 0)
14
+ return sign + '0.' + '0'.repeat(-position) + digits;
15
+ if (position >= digits.length)
16
+ return sign + digits + '0'.repeat(position - digits.length);
17
+ return sign + digits.slice(0, position) + '.' + digits.slice(position);
18
+ }
19
+ // GPX 1.1's longitude domain excludes the east edge of the antimeridian.
20
+ const GPX_EAST_EDGE = 179.99999999999997;
5
21
  function trkptLines(vertex) {
22
+ const lat = decimal(vertex.lat);
23
+ const lon = decimal(vertex.lon === 180 ? GPX_EAST_EDGE : vertex.lon);
6
24
  const children = [];
7
25
  if (vertex.altM !== null)
8
- children.push(`<ele>${vertex.altM}</ele>`);
26
+ children.push(`<ele>${decimal(vertex.altM)}</ele>`);
9
27
  if (vertex.timeMs !== null)
10
28
  children.push(`<time>${isoUtc(vertex.timeMs)}</time>`);
11
- const open = `<trkpt lat="${vertex.lat}" lon="${vertex.lon}">`;
29
+ const open = `<trkpt lat="${lat}" lon="${lon}">`;
12
30
  if (children.length === 0)
13
- return [` <trkpt lat="${vertex.lat}" lon="${vertex.lon}"/>`];
31
+ return [` <trkpt lat="${lat}" lon="${lon}"/>`];
14
32
  return [
15
33
  ` ${open}`,
16
34
  ...children.map((child) => ` ${child}`),
@@ -18,17 +36,23 @@ function trkptLines(vertex) {
18
36
  ];
19
37
  }
20
38
  export function serializeGpx(segments) {
39
+ return serializeGpxTracks([segments]);
40
+ }
41
+ export function serializeGpxTracks(tracks) {
21
42
  const lines = [
22
43
  '<?xml version="1.0" encoding="UTF-8"?>',
23
44
  '<gpx version="1.1" creator="drone-path" xmlns="http://www.topografix.com/GPX/1/1">',
24
- ' <trk>',
25
45
  ];
26
- for (const segment of segments) {
27
- lines.push(' <trkseg>');
28
- for (const vertex of segment)
29
- lines.push(...trkptLines(vertex));
30
- lines.push(' </trkseg>');
46
+ for (const segments of tracks) {
47
+ lines.push(' <trk>');
48
+ for (const segment of segments) {
49
+ lines.push(' <trkseg>');
50
+ for (const vertex of segment)
51
+ lines.push(...trkptLines(vertex));
52
+ lines.push(' </trkseg>');
53
+ }
54
+ lines.push(' </trk>');
31
55
  }
32
- lines.push(' </trk>', '</gpx>', '');
56
+ lines.push('</gpx>', '');
33
57
  return lines.join('\n');
34
58
  }
@@ -1,2 +1,3 @@
1
1
  import type { TrackSegment } from './track.js';
2
2
  export declare function serializeKml(segments: readonly TrackSegment[]): string;
3
+ export declare function serializeKmlTracks(tracks: readonly (readonly TrackSegment[])[]): string;
package/dist/track-kml.js CHANGED
@@ -35,13 +35,21 @@ function placemarkLines(segment) {
35
35
  return lines;
36
36
  }
37
37
  export function serializeKml(segments) {
38
+ return kmlDocument(segments.flatMap(placemarkLines));
39
+ }
40
+ export function serializeKmlTracks(tracks) {
41
+ return kmlDocument(tracks.flatMap((segments, index) => [
42
+ ' <Folder>', ` <name>Flight ${index + 1}</name>`,
43
+ ...segments.flatMap((segment) => placemarkLines(segment.length === 1 ? [segment[0], segment[0]] : segment))
44
+ .map((line) => ` ${line}`),
45
+ ' </Folder>',
46
+ ]));
47
+ }
48
+ function kmlDocument(placemarks) {
38
49
  const lines = [
39
50
  '<?xml version="1.0" encoding="UTF-8"?>',
40
51
  '<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">',
41
52
  ' <Document>',
42
53
  ];
43
- for (const segment of segments)
44
- lines.push(...placemarkLines(segment));
45
- lines.push(' </Document>', '</kml>', '');
46
- return lines.join('\n');
54
+ return lines.concat(placemarks, ' </Document>', '</kml>', '').join('\n');
47
55
  }
package/dist/track-kmz.js CHANGED
@@ -7,35 +7,29 @@ const ENTRY_NAME = 'doc.kml';
7
7
  // The zip epoch (1980-01-01 00:00:00) in MS-DOS date/time fields.
8
8
  const DOS_DATE_1980_01_01 = 0x0021;
9
9
  const DOS_TIME_MIDNIGHT = 0x0000;
10
- function localHeader(name, data) {
10
+ function writeCommonEntryFields(buf, offset, crc, dataLength, nameLength) {
11
+ buf.writeUInt16LE(20, offset); // version needed: 2.0
12
+ buf.writeUInt16LE(0, offset + 2); // flags
13
+ buf.writeUInt16LE(0, offset + 4); // method: stored
14
+ buf.writeUInt16LE(DOS_TIME_MIDNIGHT, offset + 6);
15
+ buf.writeUInt16LE(DOS_DATE_1980_01_01, offset + 8);
16
+ buf.writeUInt32LE(crc, offset + 10);
17
+ buf.writeUInt32LE(dataLength, offset + 14);
18
+ buf.writeUInt32LE(dataLength, offset + 18);
19
+ buf.writeUInt16LE(nameLength, offset + 22);
20
+ buf.writeUInt16LE(0, offset + 24); // extra field length
21
+ }
22
+ function localHeader(name, data, crc) {
11
23
  const header = Buffer.alloc(30);
12
24
  header.writeUInt32LE(0x04034b50, 0);
13
- header.writeUInt16LE(20, 4); // version needed: 2.0
14
- header.writeUInt16LE(0, 6); // flags
15
- header.writeUInt16LE(0, 8); // method: stored
16
- header.writeUInt16LE(DOS_TIME_MIDNIGHT, 10);
17
- header.writeUInt16LE(DOS_DATE_1980_01_01, 12);
18
- header.writeUInt32LE(crc32(data), 14);
19
- header.writeUInt32LE(data.length, 18);
20
- header.writeUInt32LE(data.length, 22);
21
- header.writeUInt16LE(name.length, 26);
22
- header.writeUInt16LE(0, 28); // extra field length
25
+ writeCommonEntryFields(header, 4, crc, data.length, name.length);
23
26
  return Buffer.concat([header, name, data]);
24
27
  }
25
- function centralDirectoryEntry(name, data, offset) {
28
+ function centralDirectoryEntry(name, dataLength, crc, offset) {
26
29
  const entry = Buffer.alloc(46);
27
30
  entry.writeUInt32LE(0x02014b50, 0);
28
31
  entry.writeUInt16LE(20, 4); // version made by: 2.0, MS-DOS
29
- entry.writeUInt16LE(20, 6); // version needed: 2.0
30
- entry.writeUInt16LE(0, 8); // flags
31
- entry.writeUInt16LE(0, 10); // method: stored
32
- entry.writeUInt16LE(DOS_TIME_MIDNIGHT, 12);
33
- entry.writeUInt16LE(DOS_DATE_1980_01_01, 14);
34
- entry.writeUInt32LE(crc32(data), 16);
35
- entry.writeUInt32LE(data.length, 20);
36
- entry.writeUInt32LE(data.length, 24);
37
- entry.writeUInt16LE(name.length, 28);
38
- entry.writeUInt16LE(0, 30); // extra field length
32
+ writeCommonEntryFields(entry, 6, crc, dataLength, name.length);
39
33
  entry.writeUInt16LE(0, 32); // comment length
40
34
  entry.writeUInt16LE(0, 34); // disk number start
41
35
  entry.writeUInt16LE(0, 36); // internal attributes
@@ -58,8 +52,9 @@ function endOfCentralDirectory(entryCount, cdSize, cdOffset) {
58
52
  export function kmzBytes(kml) {
59
53
  const name = Buffer.from(ENTRY_NAME, 'utf8');
60
54
  const data = Buffer.from(kml, 'utf8');
61
- const local = localHeader(name, data);
62
- const central = centralDirectoryEntry(name, data, 0);
55
+ const crc = crc32(data);
56
+ const local = localHeader(name, data, crc);
57
+ const central = centralDirectoryEntry(name, data.length, crc, 0);
63
58
  return Buffer.concat([
64
59
  local,
65
60
  central,
@@ -12,11 +12,7 @@ import { serializeKml } from './track-kml.js';
12
12
  import { kmzBytes } from './track-kmz.js';
13
13
  import { trackFormatOf } from './track-format.js';
14
14
  import { buildTrack, selectTrackRecords } from './track.js';
15
- export function trackFileBytes(file, input, range) {
16
- const format = trackFormatOf(file);
17
- if (format === 'json') {
18
- return serializeTelemetryDocument(buildTelemetryDocument(segmentTelemetryInput(input.document, range)));
19
- }
15
+ function serializeTrack(format, input, range) {
20
16
  const track = buildTrack(selectTrackRecords(input.track, range));
21
17
  switch (format) {
22
18
  case 'gpx':
@@ -29,6 +25,13 @@ export function trackFileBytes(file, input, range) {
29
25
  return kmzBytes(serializeKml(track));
30
26
  }
31
27
  }
28
+ export function trackFileBytes(file, input, range) {
29
+ const format = trackFormatOf(file);
30
+ if (format === 'json') {
31
+ return serializeTelemetryDocument(buildTelemetryDocument(segmentTelemetryInput(input.document, range)));
32
+ }
33
+ return serializeTrack(format, input, range);
34
+ }
32
35
  export function writeTrackFile(file, input, range) {
33
36
  const format = trackFormatOf(file);
34
37
  fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -37,5 +40,5 @@ export function writeTrackFile(file, input, range) {
37
40
  writeTelemetryDocument(file, segmentTelemetryInput(input.document, range));
38
41
  return;
39
42
  }
40
- fs.writeFileSync(file, trackFileBytes(file, input, range));
43
+ fs.writeFileSync(file, serializeTrack(format, input, range));
41
44
  }
@@ -6,4 +6,6 @@ interface ShapeWording {
6
6
  }
7
7
  export declare function strictShape<T extends z.ZodRawShape>(shape: T, wording: ShapeWording): z.ZodObject<{ -readonly [P in keyof T]: T[P]; }, z.core.$strict>;
8
8
  export declare function numberValue(name: string): z.ZodType<number>;
9
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
10
+ export declare function asRecord(value: unknown): Record<string, unknown>;
9
11
  export {};
@@ -20,3 +20,9 @@ export function strictShape(shape, wording) {
20
20
  export function numberValue(name) {
21
21
  return z.number({ error: invalidNumber(name) });
22
22
  }
23
+ export function isRecord(value) {
24
+ return typeof value === 'object' && value !== null;
25
+ }
26
+ export function asRecord(value) {
27
+ return isRecord(value) ? (value) : {};
28
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "drone-path-core",
3
- "version": "1.0.0-rc1",
3
+ "version": "1.1.0",
4
4
  "description": "Extract drone telemetry from DJI CAM-meta video streams and SRT sidecars.",
5
5
  "type": "module",
6
6
  "exports": {