drone-path-core 1.0.0-rc1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,227 @@
1
+ import { open } from 'node:fs/promises';
2
+ // Keep the optimization bounded. Larger or uncommon layouts use the tool path.
3
+ const MAX_BOX_BYTES = 64 * 1024 * 1024;
4
+ const MAX_CAM_BYTES = 128 * 1024 * 1024;
5
+ const MAX_SAMPLES = 1_000_000;
6
+ const MAX_TOP_LEVEL_BOXES = 4096;
7
+ class UnsupportedLayout extends Error {
8
+ }
9
+ function requireLayout(ok) {
10
+ if (!ok)
11
+ throw new UnsupportedLayout('unsupported mp4 sample layout');
12
+ }
13
+ function boxAt(header, offset, end) {
14
+ const shortSize = header.readUInt32BE(0);
15
+ const headerSize = shortSize === 1 ? 16 : 8;
16
+ const size = shortSize === 1
17
+ ? Number(header.readBigUInt64BE(8))
18
+ : shortSize || end - offset;
19
+ requireLayout(Number.isSafeInteger(size) && size >= headerSize && size <= end - offset);
20
+ return {
21
+ type: header.toString('latin1', 4, 8),
22
+ payload: offset + headerSize,
23
+ end: offset + size,
24
+ };
25
+ }
26
+ function childBoxes(container) {
27
+ const boxes = [];
28
+ for (let offset = 0; offset < container.length;) {
29
+ const child = boxAt(container.subarray(offset, offset + 16), offset, container.length);
30
+ boxes.push(child);
31
+ offset = child.end;
32
+ }
33
+ return boxes;
34
+ }
35
+ function getBox(container, boxes, type) {
36
+ const matches = boxes.filter((box) => box.type === type);
37
+ requireLayout(matches.length === 1);
38
+ return container.subarray(matches[0].payload, matches[0].end);
39
+ }
40
+ function getChild(container, type) {
41
+ return getBox(container, childBoxes(container), type);
42
+ }
43
+ async function readExactly(file, buffer, position, signal) {
44
+ for (let offset = 0; offset < buffer.length;) {
45
+ signal?.throwIfAborted();
46
+ const { bytesRead } = await file.read(buffer, offset, buffer.length - offset, position + offset);
47
+ requireLayout(bytesRead > 0);
48
+ offset += bytesRead;
49
+ }
50
+ }
51
+ async function readTopLevel(file, size, signal) {
52
+ const boxes = [];
53
+ for (let offset = 0; offset < size;) {
54
+ requireLayout(boxes.length < MAX_TOP_LEVEL_BOXES);
55
+ const header = Buffer.alloc(Math.min(16, size - offset));
56
+ await readExactly(file, header, offset, signal);
57
+ const box = boxAt(header, offset, size);
58
+ boxes.push(box);
59
+ offset = box.end;
60
+ }
61
+ return boxes;
62
+ }
63
+ function readTrackField(header) {
64
+ const version = header.readUInt8(0);
65
+ requireLayout(version === 0 || version === 1);
66
+ return header.readUInt32BE(version === 0 ? 12 : 20);
67
+ }
68
+ function findTrack(movie, boxes, trackId) {
69
+ for (const box of boxes) {
70
+ if (box.type !== 'trak')
71
+ continue;
72
+ const track = movie.subarray(box.payload, box.end);
73
+ if (readTrackField(getChild(track, 'tkhd')) === trackId)
74
+ return track;
75
+ }
76
+ throw new UnsupportedLayout('missing cam meta track');
77
+ }
78
+ function entryCount(table, width) {
79
+ const count = table.readUInt32BE(4);
80
+ requireLayout(table.readUInt32BE(0) === 0 && count > 0 && count <= MAX_SAMPLES);
81
+ requireLayout(table.length === 8 + count * width);
82
+ return count;
83
+ }
84
+ function sampleSizes(table) {
85
+ const constant = table.readUInt32BE(4);
86
+ const count = table.readUInt32BE(8);
87
+ requireLayout(table.readUInt32BE(0) === 0 && count > 0 && count <= MAX_SAMPLES);
88
+ requireLayout(table.length === 12 + (constant === 0 ? count * 4 : 0));
89
+ return Array.from({ length: count }, (_, sample) => constant || table.readUInt32BE(12 + sample * 4));
90
+ }
91
+ function packetTimestamp(seconds) {
92
+ // ffprobe prints six decimal places and rounds exact halfway values to even.
93
+ // After factoring out powers of five, binary halfway values are odd / 128.
94
+ const ticksAt128Hz = seconds * 128;
95
+ if (ticksAt128Hz % 4 === 1) {
96
+ const micros = BigInt(ticksAt128Hz) * 15625n / 2n;
97
+ return Number(`${micros}e-6`);
98
+ }
99
+ return Number(seconds.toFixed(6));
100
+ }
101
+ function readPacketTimes(table, sizes, timescale) {
102
+ const packets = [];
103
+ let ticks = 0;
104
+ const count = entryCount(table, 8);
105
+ const timeBase = 1 / timescale;
106
+ for (let entry = 0; entry < count; entry++) {
107
+ const offset = 8 + entry * 8;
108
+ const samples = table.readUInt32BE(offset);
109
+ const delta = table.readUInt32BE(offset + 4);
110
+ requireLayout(samples > 0 && delta > 0 && packets.length + samples <= sizes.length);
111
+ for (let sample = 0; sample < samples; sample++) {
112
+ packets.push({ tSec: packetTimestamp(ticks * timeBase), size: sizes[packets.length] });
113
+ ticks += delta;
114
+ }
115
+ requireLayout(Number.isSafeInteger(ticks));
116
+ }
117
+ requireLayout(packets.length === sizes.length);
118
+ return { packets, ticks };
119
+ }
120
+ function validateEdit(track, trackBoxes, movie, movieBoxes, mediaScale, mediaTicks) {
121
+ if (!trackBoxes.some(({ type }) => type === 'edts'))
122
+ return;
123
+ const edit = getChild(getBox(track, trackBoxes, 'edts'), 'elst');
124
+ const version = edit.readUInt8(0);
125
+ requireLayout((version === 0 && edit.length === 20) || (version === 1 && edit.length === 28));
126
+ const duration = version === 0 ? edit.readUInt32BE(8) : Number(edit.readBigUInt64BE(8));
127
+ const start = version === 0 ? edit.readInt32BE(12) : Number(edit.readBigInt64BE(16));
128
+ const movieScale = readTrackField(getBox(movie, movieBoxes, 'mvhd'));
129
+ // A single edit covering the whole track at normal speed leaves PTS unchanged.
130
+ requireLayout(edit.readUInt32BE(4) === 1 && start === 0 &&
131
+ edit.readUInt32BE(edit.length - 4) === 0x00010000 &&
132
+ movieScale > 0 && Number.isSafeInteger(duration) &&
133
+ duration / movieScale >= mediaTicks / mediaScale);
134
+ }
135
+ function validateDataReference(mediaInfo, descriptions) {
136
+ requireLayout(descriptions.readUInt32BE(4) === 1);
137
+ const [description] = childBoxes(descriptions.subarray(8));
138
+ requireLayout(description && descriptions.readUInt16BE(8 + description.payload + 6) === 1);
139
+ const references = getChild(getChild(mediaInfo, 'dinf'), 'dref');
140
+ requireLayout(references.readUInt32BE(4) > 0);
141
+ const [entry] = childBoxes(references.subarray(8));
142
+ requireLayout(entry && entry.type === 'url ' && references.readUInt32BE(8 + entry.payload) === 1);
143
+ }
144
+ function readChunkLayout(table, boxes, sizes, mediaData) {
145
+ const wide = boxes.some(({ type }) => type === 'co64');
146
+ requireLayout(!wide || !boxes.some(({ type }) => type === 'stco'));
147
+ const offsets = getBox(table, boxes, wide ? 'co64' : 'stco');
148
+ const width = wide ? 8 : 4;
149
+ const chunkCount = entryCount(offsets, width);
150
+ const mapping = getBox(table, boxes, 'stsc');
151
+ const mapCount = entryCount(mapping, 12);
152
+ const chunks = [];
153
+ let sample = 0;
154
+ for (let row = 0; row < mapCount; row++) {
155
+ const offset = 8 + row * 12;
156
+ const first = mapping.readUInt32BE(offset);
157
+ const end = row + 1 === mapCount ? chunkCount + 1 : mapping.readUInt32BE(offset + 12);
158
+ const samples = mapping.readUInt32BE(offset + 4);
159
+ requireLayout(first === chunks.length + 1 && end > first && end <= chunkCount + 1);
160
+ requireLayout(samples > 0 && mapping.readUInt32BE(offset + 8) === 1);
161
+ for (let chunk = first; chunk < end; chunk++) {
162
+ const offsetIndex = 8 + (chunk - 1) * width;
163
+ const position = wide ? Number(offsets.readBigUInt64BE(offsetIndex)) : offsets.readUInt32BE(offsetIndex);
164
+ requireLayout(sample + samples <= sizes.length && Number.isSafeInteger(position));
165
+ let size = 0;
166
+ for (const limit = sample + samples; sample < limit; sample++)
167
+ size += sizes[sample];
168
+ requireLayout(mediaData.some(({ payload, end }) => position >= payload && size <= end - position));
169
+ chunks.push({ offset: position, size });
170
+ }
171
+ }
172
+ requireLayout(sample === sizes.length);
173
+ return chunks;
174
+ }
175
+ async function readTrack(file, size, trackId, signal) {
176
+ const top = await readTopLevel(file, size, signal);
177
+ const movies = top.filter(({ type }) => type === 'moov');
178
+ requireLayout(movies.length === 1 && !top.some(({ type }) => type === 'moof'));
179
+ const [{ payload, end }] = movies;
180
+ requireLayout(end - payload <= MAX_BOX_BYTES);
181
+ const movie = Buffer.alloc(end - payload);
182
+ await readExactly(file, movie, payload, signal);
183
+ const movieBoxes = childBoxes(movie);
184
+ requireLayout(!movieBoxes.some(({ type }) => type === 'mvex'));
185
+ const track = findTrack(movie, movieBoxes, trackId);
186
+ const trackBoxes = childBoxes(track);
187
+ const media = getBox(track, trackBoxes, 'mdia');
188
+ const timescale = readTrackField(getChild(media, 'mdhd'));
189
+ const mediaInfo = getChild(media, 'minf');
190
+ const table = getChild(mediaInfo, 'stbl');
191
+ const boxes = childBoxes(table);
192
+ requireLayout(timescale > 0 && !boxes.some(({ type }) => type === 'ctts' || type === 'stz2'));
193
+ validateDataReference(mediaInfo, getBox(table, boxes, 'stsd'));
194
+ const sizes = sampleSizes(getBox(table, boxes, 'stsz'));
195
+ const bytes = sizes.reduce((total, sample) => total + sample, 0);
196
+ requireLayout(bytes > 0 && bytes <= MAX_CAM_BYTES && sizes.every((size) => size > 0));
197
+ const { packets, ticks } = readPacketTimes(getBox(table, boxes, 'stts'), sizes, timescale);
198
+ validateEdit(track, trackBoxes, movie, movieBoxes, timescale, ticks);
199
+ const chunks = readChunkLayout(table, boxes, sizes, top.filter(({ type }) => type === 'mdat'));
200
+ const buffer = Buffer.alloc(bytes);
201
+ let target = 0;
202
+ for (const chunk of chunks) {
203
+ await readExactly(file, buffer.subarray(target, target + chunk.size), chunk.offset, signal);
204
+ target += chunk.size;
205
+ }
206
+ return { buffer, packets };
207
+ }
208
+ export async function readCamMetaTrack(videoPath, trackId, signal) {
209
+ signal?.throwIfAborted();
210
+ try {
211
+ const file = await open(videoPath, 'r');
212
+ try {
213
+ const { size } = await file.stat();
214
+ return await readTrack(file, size, trackId, signal);
215
+ }
216
+ finally {
217
+ await file.close();
218
+ }
219
+ }
220
+ catch (error) {
221
+ signal?.throwIfAborted();
222
+ if (error instanceof UnsupportedLayout || error instanceof RangeError ||
223
+ (error instanceof Error && 'code' in error))
224
+ return null;
225
+ throw error;
226
+ }
227
+ }
@@ -0,0 +1,15 @@
1
+ import type { Bbox, LatLon } from './geo.js';
2
+ export interface TimedPoint extends LatLon {
3
+ tSec: number;
4
+ }
5
+ export interface ClosestApproach {
6
+ tSec: number;
7
+ distanceM: number;
8
+ }
9
+ type LongitudeRange = readonly [number, number];
10
+ export declare function longitudeRanges({ minLon, maxLon }: Bbox): LongitudeRange[];
11
+ export declare function bboxIntersects(a: Bbox, b: Bbox): boolean;
12
+ export declare function resolveTrackBbox(bbox: Bbox, segments: readonly (readonly LatLon[])[]): Bbox;
13
+ export declare function radiusBbox(center: LatLon, radiusM: number): Bbox;
14
+ export declare function nearestOnTrack(query: LatLon, segments: readonly (readonly TimedPoint[])[]): ClosestApproach | null;
15
+ export {};
@@ -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
@@ -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,21 @@ 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 new Error(`${ERR_NO_TELEMETRY}no CAM meta (DVTM) stream and no .SRT sidecar`);
82
+ if (loaded.source === 'cammeta' && loaded.samples.length === 0) {
83
+ throw new Error(`${ERR_NO_TELEMETRY}the CAM meta (DVTM) stream has no GPS fix pairs; ` +
84
+ 'the .SRT sidecar is only consulted when no CAM meta stream is present');
85
+ }
87
86
  const { frameValues, trackValues, protoFile, gimbalDevice, ...samples } = loaded;
88
87
  return {
89
88
  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;