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,66 @@
1
+ import { DEG_TO_RAD, EARTH_RADIUS_M } from './geo.js';
2
+ import { bboxIntersects } from './spatial.js';
3
+ const MIN_DOWN = Math.sin(5 * DEG_TO_RAD);
4
+ const CORNERS = [[-1, -1], [1, -1], [1, 1], [-1, 1]];
5
+ export const DEFAULT_CAMERA_FOV = { horizontalDeg: 75, verticalDeg: 50 };
6
+ function wrapLon(lon) {
7
+ return ((lon + 180) % 360 + 360) % 360 - 180;
8
+ }
9
+ export function projectGroundFootprint(camera, fov = DEFAULT_CAMERA_FOV) {
10
+ const { lat, lon, altitudeM, pitchDeg, yawDeg, rollDeg = 0 } = camera;
11
+ const { horizontalDeg, verticalDeg } = fov;
12
+ if (![lat, lon, altitudeM, pitchDeg, yawDeg, rollDeg, horizontalDeg, verticalDeg].every(Number.isFinite)
13
+ || Math.abs(lat) >= 90 || Math.abs(lon) > 180 || altitudeM <= 0 || pitchDeg >= 0 || pitchDeg < -90
14
+ || horizontalDeg <= 0 || horizontalDeg >= 180 || verticalDeg <= 0 || verticalDeg >= 180)
15
+ return null;
16
+ const pitch = -pitchDeg * DEG_TO_RAD;
17
+ const yaw = yawDeg * DEG_TO_RAD;
18
+ const roll = rollDeg * DEG_TO_RAD;
19
+ const halfWidth = Math.tan(horizontalDeg * DEG_TO_RAD / 2);
20
+ const halfHeight = Math.tan(verticalDeg * DEG_TO_RAD / 2);
21
+ const polygon = [];
22
+ const offsets = [];
23
+ for (const [x, y] of CORNERS) {
24
+ const right = x * halfWidth * Math.cos(roll) - y * halfHeight * Math.sin(roll);
25
+ const up = x * halfWidth * Math.sin(roll) + y * halfHeight * Math.cos(roll);
26
+ const down = Math.sin(pitch) - up * Math.cos(pitch);
27
+ if (down < MIN_DOWN * Math.hypot(1, right, up))
28
+ return null;
29
+ const depth = altitudeM / down;
30
+ const forward = Math.cos(pitch) + up * Math.sin(pitch);
31
+ const north = depth * (forward * Math.cos(yaw) - right * Math.sin(yaw));
32
+ const east = depth * (forward * Math.sin(yaw) + right * Math.cos(yaw));
33
+ const vertexLat = lat + north / (EARTH_RADIUS_M * DEG_TO_RAD);
34
+ const deltaLon = east / (EARTH_RADIUS_M * DEG_TO_RAD * Math.cos(lat * DEG_TO_RAD));
35
+ if (Math.abs(vertexLat) >= 90 || Math.abs(deltaLon) >= 90)
36
+ return null;
37
+ offsets.push(deltaLon);
38
+ polygon.push({ lat: vertexLat, lon: wrapLon(lon + deltaLon) });
39
+ }
40
+ return Math.max(...offsets) - Math.min(...offsets) >= 180 ? null : polygon;
41
+ }
42
+ export function footprintBbox(polygon) {
43
+ const reference = polygon[0].lon;
44
+ const latitudes = polygon.map(({ lat }) => lat);
45
+ const longitudes = polygon.map(({ lon }) => wrapLon(lon - reference));
46
+ return {
47
+ minLat: Math.min(...latitudes), maxLat: Math.max(...latitudes),
48
+ minLon: polygon[longitudes.indexOf(Math.min(...longitudes))].lon,
49
+ maxLon: polygon[longitudes.indexOf(Math.max(...longitudes))].lon,
50
+ };
51
+ }
52
+ export function footprintContains(polygon, point) {
53
+ const bbox = footprintBbox(polygon);
54
+ const lon = point.lon === 180 ? -180 : point.lon;
55
+ if (!bboxIntersects(bbox, { minLat: point.lat, maxLat: point.lat, minLon: lon, maxLon: lon }))
56
+ return false;
57
+ const reference = polygon[0].lon;
58
+ const x = wrapLon(point.lon - reference);
59
+ const crosses = polygon.map((a, index) => {
60
+ const b = polygon[(index + 1) % polygon.length];
61
+ const ax = wrapLon(a.lon - reference);
62
+ const bx = wrapLon(b.lon - reference);
63
+ return (bx - ax) * (point.lat - a.lat) - (b.lat - a.lat) * (x - ax);
64
+ });
65
+ return crosses.every((value) => value >= -1e-14) || crosses.every((value) => value <= 1e-14);
66
+ }
@@ -0,0 +1,37 @@
1
+ import type { FfmpegToolPaths } from './ffmpeg-tools.js';
2
+ export type KeyframeRequest = {
3
+ kind: 'time';
4
+ tSec: number;
5
+ } | {
6
+ kind: 'frame';
7
+ frame: number;
8
+ };
9
+ export interface TelemetrySnapshot {
10
+ lat: number | null;
11
+ lon: number | null;
12
+ altRelM: number | null;
13
+ altAbsM: number | null;
14
+ speedMps: number | null;
15
+ headingDeg: number | null;
16
+ gimbalPitchDeg: number | null;
17
+ gimbalYawDeg: number | null;
18
+ iso: number | null;
19
+ shutterTime: number | null;
20
+ }
21
+ export interface ExtractedKeyframe {
22
+ path: string;
23
+ tSec: number;
24
+ frame: number;
25
+ width: number;
26
+ height: number;
27
+ telemetry: TelemetrySnapshot | null;
28
+ }
29
+ export interface ExtractKeyframesOptions {
30
+ at: readonly KeyframeRequest[];
31
+ maxWidth?: number;
32
+ outDir?: string;
33
+ tools: FfmpegToolPaths;
34
+ signal?: AbortSignal;
35
+ }
36
+ export declare function parseKeyframeSpecs(spec: string): KeyframeRequest[];
37
+ export declare function extractKeyframes(videoPath: string, options: ExtractKeyframesOptions): Promise<ExtractedKeyframe[]>;
@@ -0,0 +1,213 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { runTool } from './exec-tool.js';
4
+ import { probeVideo } from './ffmpeg.js';
5
+ import { timeAt } from './frametime.js';
6
+ import { loadTelemetrySamples } from './telemetry.js';
7
+ import { computeTelemetry } from './telemetry-math.js';
8
+ function parseFrameToken(raw, token) {
9
+ if (!/^\d+$/u.test(raw)) {
10
+ throw new Error(`invalid keyframe frame selector: ${token}`);
11
+ }
12
+ const frame = Number(raw);
13
+ if (!Number.isSafeInteger(frame) || frame < 0) {
14
+ throw new Error(`invalid keyframe frame selector: ${token}`);
15
+ }
16
+ return { kind: 'frame', frame };
17
+ }
18
+ function parseTimeToken(token) {
19
+ const raw = token.endsWith('s') || token.endsWith('S') ? token.slice(0, -1) : token;
20
+ if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/u.test(raw)) {
21
+ throw new Error(`invalid keyframe timestamp: ${token}`);
22
+ }
23
+ const tSec = Number(raw);
24
+ if (!Number.isFinite(tSec) || tSec < 0) {
25
+ throw new Error(`keyframe timestamp must be non-negative: ${token}`);
26
+ }
27
+ return { kind: 'time', tSec };
28
+ }
29
+ export function parseKeyframeSpecs(spec) {
30
+ if (typeof spec !== 'string' || spec.trim() === '') {
31
+ throw new Error('keyframe spec must not be empty');
32
+ }
33
+ return spec.split(',').map((item) => {
34
+ const token = item.trim();
35
+ if (token === '') {
36
+ throw new Error('keyframe spec must not contain empty items');
37
+ }
38
+ const frameMatch = /^(?:frame:|f)(.*)$/iu.exec(token);
39
+ return frameMatch ? parseFrameToken(frameMatch[1], token) : parseTimeToken(token);
40
+ });
41
+ }
42
+ function maxDurationOf(probe) {
43
+ return Number.isFinite(probe.durationSec) && probe.durationSec >= 0
44
+ ? probe.durationSec
45
+ : timeAt(probe.frames, probe.fps.value);
46
+ }
47
+ function resolveTargets(requests, probe) {
48
+ const maxDurationSec = maxDurationOf(probe);
49
+ return requests.map((req) => {
50
+ if (req.kind === 'time') {
51
+ if (!Number.isFinite(req.tSec) || req.tSec < 0 || req.tSec > maxDurationSec) {
52
+ throw new Error(`keyframe timestamp ${req.tSec}s is out of range [0, ${maxDurationSec}]`);
53
+ }
54
+ const frame = Math.min(probe.frames - 1, Math.max(0, Math.round(req.tSec * probe.fps.value)));
55
+ return { tSec: req.tSec, frame };
56
+ }
57
+ if (!Number.isInteger(req.frame) || req.frame < 0 || req.frame >= probe.frames) {
58
+ throw new Error(`keyframe frame ${req.frame} is out of range [0, ${probe.frames - 1}]`);
59
+ }
60
+ return { tSec: timeAt(req.frame, probe.fps.value), frame: req.frame };
61
+ });
62
+ }
63
+ function nearestTrackRecord(records, tSec) {
64
+ if (records.length === 0)
65
+ return null;
66
+ let lo = 0;
67
+ let hi = records.length - 1;
68
+ while (hi - lo > 1) {
69
+ const mid = (lo + hi) >> 1;
70
+ if (records[mid].tSec <= tSec)
71
+ lo = mid;
72
+ else
73
+ hi = mid;
74
+ }
75
+ return Math.abs(tSec - records[lo].tSec) <= Math.abs(records[hi].tSec - tSec)
76
+ ? records[lo]
77
+ : records[hi];
78
+ }
79
+ function absAltitudeOf(record) {
80
+ if (!record)
81
+ return null;
82
+ if (record.altAbs !== null && record.altAbs !== undefined)
83
+ return record.altAbs;
84
+ if (record.gpsAltMm !== null && record.gpsAltMm !== undefined) {
85
+ return record.gpsAltMm / 1000;
86
+ }
87
+ return null;
88
+ }
89
+ function hasAnySnapshotValue(snapshot) {
90
+ return (snapshot.lat !== null ||
91
+ snapshot.lon !== null ||
92
+ snapshot.altRelM !== null ||
93
+ snapshot.altAbsM !== null ||
94
+ snapshot.speedMps !== null ||
95
+ snapshot.headingDeg !== null ||
96
+ snapshot.gimbalPitchDeg !== null ||
97
+ snapshot.gimbalYawDeg !== null ||
98
+ snapshot.iso !== null ||
99
+ snapshot.shutterTime !== null);
100
+ }
101
+ function buildSnapshotLookup(loaded, probe) {
102
+ if (!loaded || loaded.trackValues.length === 0) {
103
+ return () => null;
104
+ }
105
+ const fixCount = loaded.samples.filter((sample) => sample.fix !== null).length;
106
+ const telemetry = fixCount >= 2
107
+ ? computeTelemetry(loaded, { frames: probe.frames, fpsValue: probe.fps.value })
108
+ : null;
109
+ return (tSec, frame) => {
110
+ const record = nearestTrackRecord(loaded.trackValues, tSec);
111
+ const frameData = telemetry?.frames[frame];
112
+ const snapshot = {
113
+ lat: frameData?.fix?.lat ?? record?.lat ?? null,
114
+ lon: frameData?.fix?.lon ?? record?.lng ?? null,
115
+ altRelM: record?.altRel ?? null,
116
+ altAbsM: absAltitudeOf(record),
117
+ speedMps: frameData?.speed ?? null,
118
+ headingDeg: frameData?.headingDeg ?? record?.yawDeg ?? null,
119
+ gimbalPitchDeg: record?.gimbalPitchDeg ?? null,
120
+ gimbalYawDeg: record?.gimbalYawDeg ?? null,
121
+ iso: record?.iso ?? null,
122
+ shutterTime: record?.shutterTime ?? null,
123
+ };
124
+ return hasAnySnapshotValue(snapshot) ? snapshot : null;
125
+ };
126
+ }
127
+ function outputDimensions(probe, maxWidth) {
128
+ const scaled = maxWidth !== undefined && probe.width > 0 && maxWidth < probe.width;
129
+ const width = scaled ? maxWidth : probe.width;
130
+ if (probe.width <= 0 || probe.height <= 0) {
131
+ return {
132
+ width,
133
+ height: 0,
134
+ scaleArgs: scaled ? ['-vf', `scale=${width}:-2`] : [],
135
+ };
136
+ }
137
+ if (!scaled) {
138
+ return { width, height: probe.height, scaleArgs: [] };
139
+ }
140
+ // YUV420 JPEG encoders require even heights; compute the exact even height so
141
+ // the reported dimensions match what ffmpeg writes.
142
+ const rawHeight = (probe.height * width) / probe.width;
143
+ const height = probe.height === 1 ? 1 : Math.max(2, Math.round(rawHeight / 2) * 2);
144
+ return {
145
+ width,
146
+ height,
147
+ scaleArgs: ['-vf', `scale=${width}:${height}`],
148
+ };
149
+ }
150
+ function allocateOutPath(outDir, stem, frame, tSec, usedPaths) {
151
+ const ms = Math.round(tSec * 1000);
152
+ const baseName = `${stem}_f${frame}_${ms}ms`;
153
+ let candidate = path.join(outDir, `${baseName}.jpg`);
154
+ let suffix = 2;
155
+ while (usedPaths.has(candidate)) {
156
+ candidate = path.join(outDir, `${baseName}_${suffix}.jpg`);
157
+ suffix++;
158
+ }
159
+ usedPaths.add(candidate);
160
+ return candidate;
161
+ }
162
+ export async function extractKeyframes(videoPath, options) {
163
+ if (options.at.length === 0) {
164
+ throw new Error('at least one keyframe target is required');
165
+ }
166
+ if (options.maxWidth !== undefined &&
167
+ (!Number.isInteger(options.maxWidth) || options.maxWidth < 1)) {
168
+ throw new Error('max-width must be a positive integer');
169
+ }
170
+ options.signal?.throwIfAborted();
171
+ const probe = await probeVideo(options.tools, videoPath, undefined, options.signal);
172
+ const targets = resolveTargets(options.at, probe);
173
+ const loaded = await loadTelemetrySamples(options.tools, videoPath, probe.durationSec, probe.camMeta, options.signal);
174
+ const snapshotAt = buildSnapshotLookup(loaded, probe);
175
+ const { width, height, scaleArgs } = outputDimensions(probe, options.maxWidth);
176
+ const outDir = options.outDir ?? path.dirname(videoPath);
177
+ fs.mkdirSync(outDir, { recursive: true });
178
+ const stem = path.basename(videoPath, path.extname(videoPath));
179
+ const usedPaths = new Set();
180
+ const results = [];
181
+ for (const { tSec, frame } of targets) {
182
+ options.signal?.throwIfAborted();
183
+ const outPath = allocateOutPath(outDir, stem, frame, tSec, usedPaths);
184
+ try {
185
+ // Fast input seeking: -ss before -i avoids decoding preceding GOPs.
186
+ await runTool(options.tools.ffmpeg, [
187
+ '-v', 'error',
188
+ '-y',
189
+ '-ss', tSec.toFixed(3),
190
+ '-i', videoPath,
191
+ '-frames:v', '1',
192
+ ...scaleArgs,
193
+ outPath,
194
+ ], { signal: options.signal });
195
+ }
196
+ catch (e) {
197
+ if (options.signal?.aborted)
198
+ throw e;
199
+ throw new Error(`ffmpeg failed while extracting keyframe at ${tSec.toFixed(3)}s`, {
200
+ cause: e,
201
+ });
202
+ }
203
+ results.push({
204
+ path: outPath,
205
+ tSec,
206
+ frame,
207
+ width,
208
+ height,
209
+ telemetry: snapshotAt(tSec, frame),
210
+ });
211
+ }
212
+ return results;
213
+ }
@@ -0,0 +1,2 @@
1
+ import type { LatLon } from './geo.js';
2
+ export declare function launchRedactor(endpoints: readonly LatLon[], radiusM: number): <T extends LatLon>(segments: readonly (readonly T[])[]) => T[][];
@@ -0,0 +1,39 @@
1
+ import { haversineM } from './geo.js';
2
+ import { bboxIntersects, nearestOnTrack, radiusBbox } from './spatial.js';
3
+ function projectedEdgeIntersects(start, end, zone) {
4
+ const bounds = {
5
+ minLat: Math.min(start.lat, end.lat), maxLat: Math.max(start.lat, end.lat),
6
+ minLon: Math.min(start.lon, end.lon), maxLon: Math.max(start.lon, end.lon),
7
+ };
8
+ return bboxIntersects(zone, bounds) || (bounds.maxLon - bounds.minLon >= 180 &&
9
+ bboxIntersects(zone, { ...bounds, minLon: bounds.maxLon, maxLon: bounds.minLon }));
10
+ }
11
+ export function launchRedactor(endpoints, radiusM) {
12
+ const zones = radiusM > 0 ? endpoints.map((center) => ({ center, bbox: radiusBbox(center, radiusM) })) : [];
13
+ return function redact(segments) {
14
+ const kept = [];
15
+ for (const segment of segments) {
16
+ let run = [];
17
+ const endRun = () => {
18
+ if (run.length > 0)
19
+ kept.push(run);
20
+ run = [];
21
+ };
22
+ for (const point of segment) {
23
+ if (zones.some(({ center }) => haversineM(center, point) <= radiusM)) {
24
+ endRun();
25
+ continue;
26
+ }
27
+ const previous = run.at(-1);
28
+ // Treat the rectangular edge bounds as a conservative guard for readers
29
+ // that draw straight lines in their projection instead of great circles.
30
+ if (previous && zones.some(({ center, bbox }) => projectedEdgeIntersects(previous, point, bbox) ||
31
+ (nearestOnTrack(center, [[{ ...previous, tSec: 0 }, { ...point, tSec: 1 }]])?.distanceM ?? Infinity) <= radiusM))
32
+ endRun();
33
+ run.push(point);
34
+ }
35
+ endRun();
36
+ }
37
+ return kept;
38
+ };
39
+ }
@@ -0,0 +1,7 @@
1
+ import type { CamMetaPacket } from './cammeta-decode.js';
2
+ interface CamMetaTrack {
3
+ buffer: Buffer;
4
+ packets: CamMetaPacket[];
5
+ }
6
+ export declare function readCamMetaTrack(videoPath: string, trackId: number, signal?: AbortSignal): Promise<CamMetaTrack | null>;
7
+ export {};
@@ -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,16 @@
1
+ import type { Fps } from './frametime.js';
2
+ export type MarkerFormat = 'csv' | 'fcpxml';
3
+ export interface MarkerRange {
4
+ clipPath: string;
5
+ clipName?: string;
6
+ fps: Fps;
7
+ durationSec: number;
8
+ startSec: number;
9
+ endSec: number;
10
+ label: string;
11
+ note?: string;
12
+ color?: string;
13
+ }
14
+ export declare function markerFormatOf(filePath: string): MarkerFormat;
15
+ export declare function serializeDaVinciResolveCsv(markers: readonly MarkerRange[]): string;
16
+ export declare function serializeFcpxmlMarkers(markers: readonly MarkerRange[]): string;